传值的几种方式&&postman接口测试:
http://blog.****.net/lzj3462144/article/details/76980779?foxhandler=RssReadRenderProcessHandler;
ssm框架学习---开发中使用springMVC接收参数的问题:
http://blog.****.net/whu_zcj/article/details/53506572;
---------------------------------------------------------请求------------------------------------------------------------
首先说下什么是参数绑定:从客户端的请求key-value,经过参数绑定,将数据绑定到controller的方法形参上
过程:客户端请求----处理器适配器调用springmvc提供的参数绑定组建将key/value数据转化成controller方法的形参上(参数绑定组建,现在的springMvc提供了很多转换器,一般不需要自己写,学要用到的话,依据具体需求自定义converter)----controller形参
默认支持的类型:就可以使用
HttpServletRequest
HttpServletRespose
HttpSession
Model/ModelMap:最终用来填充request域
其它简单的数据类型
一、针对一般的表单提交或者使用ajax提交的数据
我前端表单代码如下:
-
<%@ page contentType="text/html; charset=utf-8"%>
-
<!DOCTYPE html>
-
<html lang="en">
-
<head>
-
<meta charset="UTF-8">
-
<title>登录</title>
-
</head>
-
<body >
-
<div style="margin:100px auto;width: 600px;height:400px;background-color: lavender;text-align: center">
-
<br>
-
<form method="post" action="/doLogin.action">
-
<h3>登录</h3>
-
<br>
-
<br>
-
<label>用户名:</label><input type="text" name="username">
-
<br> <br>
-
<label>密 码:</label><input type="password" name="password">
-
<br><br> <br>
-
<div style="text-align: center">
-
<button type="submit">登录</button>
-
<button type="reset">重置</button>
-
<br>
-
<p><a href="register.jsp">还没有帐号?点击这里注册!</a></p>
-
</div>
-
</form>
-
</div>
-
</body>
-
</html>
从代码中看到,我提交到doLgoin.action这个路由
(1)第一种,直接将参数放到对应的路由方法作为参数列表
注意name属性的对应
-
@RequestMapping("/doLogin")
-
public ModelAndView doLogin(String username,String password){
-
User user =userService.selectUserByName(username);
-
ModelAndView modelAndView = new ModelAndView();
-
if(user.getPassword().equals(password)){
-
modelAndView.addObject("user",user);
-
modelAndView.setViewName("main");
-
}else{
-
-
}
-
return modelAndView;
-
}
(2)第二种,通过httpServerletReques来接收如下
-
@RequestMapping("/doLogin")
-
public ModelAndView doLogin(HttpServletRequest request){
-
User user =userService.selectUserByName(request.getParameter("username"));
-
ModelAndView modelAndView = new ModelAndView();
-
if(user.getPassword().equals(request.getParameter("password"))){
-
modelAndView.addObject("user",user);
-
modelAndView.setViewName("main");
-
}else{
-
-
}
-
return modelAndView;
-
}
(3)第三种方式,通过建立一个前端的vo对象,和User类很类似,这种适合字段比较多的,一次性传过去
-
public class UserVo {
-
private String username;
-
private String password;
-
-
public String getUsername() {
-
return username;
-
}
-
-
public void setUsername(String username) {
-
this.username = username;
-
}
-
-
public String getPassword() {
-
return password;
-
}
-
-
public void setPassword(String password) {
-
this.password = password;
-
}
-
-
}
然后controller里面改为如下;
-
@RequestMapping("/doLogin")
-
//方法三
-
public ModelAndView doLogin(UserVo userVo){
-
User user =userService.selectUserByName(userVo.getUsername());
-
ModelAndView modelAndView = new ModelAndView();
-
if(user.getPassword().equals(userVo.getPassword())){
-
modelAndView.addObject("user",user);
-
modelAndView.setViewName("main");
-
}else{
-
-
}
-
return modelAndView;
-
}
(4)第四种,基于json传输
目前提倡前后端分离,json作为一种很简单高效的数据传输格式,前端与后端只需要传输json数据即可,不参与到路由指定和页面渲染,定义好统一接口之后,前后端各司其职,互补打扰
当返回对象都是json串,对于请求是json串,需要使用@RequestBody将json串转化为java对象,对于请求时key -value类型的,不需要进行转化,之所以返回json串的原因,方便客户端对返回结果进行解析
为了能够使用json需要在pom.xml文件中添加jar包依赖
-
<!-- 引入JSON -->
-
<dependency>
-
<groupId>org.codehaus.jackson</groupId>
-
<artifactId>jackson-core-asl</artifactId>
-
<version>1.9.13</version>
-
</dependency>
-
-
<dependency>
-
<groupId>org.codehaus.jackson</groupId>
-
<artifactId>jackson-mapper-asl</artifactId>
-
<version>1.9.13</version>
-
</dependency>
另外需要在spring-mvc的配置文件中配置转换器,因为上面提到了实际上就是java对象和json串之间的转换如下;
-
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean>
对于使用注解驱动配置处理器适配器的如下的则不需要上述的操作;
-
<!-- 配置处理器映射器和处理器适配器 -->
-
<mvc:annotation-driven></mvc:annotation-driven>
1。采用请求json串的方式
-
<script type="text/javascript" src="js/jquery-3.1.1.min.js"></script>
-
<script type="text/javascript">
-
$(document).ready(function () {
-
//请求json,输出json
-
$("#regist").click(function () {
-
alert("ok!");
-
-
$.ajax({
-
type:'post',
-
url:'${pageContext.request.contextPath}/doRegist.action',
-
//这里设置contentType为json
-
contentType:'application/json;charset=utf-8',
-
//数据格式时json串
-
data:'{"username":"zcj","password":"admin","repeatpwd":"admin"}',
-
success:function (result) {
-
alert(result)
-
},
-
error:function (result) {
-
-
}
-
});
-
});
-
-
});
-
</script>
后台controller如下:
-
@RequestMapping("/doRegist")
-
public @ResponseBody UserVo doRegist(@RequestBody UserVo userVo){
-
return userVo;
-
}
然后运行,发现报错了,错误码415
the server refused this request because the request entity is in a format not supported
后来找了一下,是因为缺少jacson databind这个包,因为默认前面我们在配置转换器的时候我们使用了注解驱动方式,它里面在帮我们自动配置jacson的转换器时实际内容如下
-
<mvc:message-converters>
-
<bean
-
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
-
<property name="objectMapper">
-
<!--下面这个部分用到了databind-->
-
<bean class="com.fasterxml.jackson.databind.ObjectMapper">
-
<property name="dateFormat">
-
<bean class="java.text.SimpleDateFormat">
-
<constructor-arg type="java.lang.String" value="yyyy-MM-dd HH:mm:ss" />
-
</bean>
-
</property>
-
</bean>
-
</property>
-
</bean>
-
</mvc:message-converters>
上面注释部分用到了一个包,因此在pom.xml中需要增加jacson的依赖如下:
-
<dependency>
-
<groupId>com.fasterxml.jackson.core</groupId>
-
<artifactId>jackson-databind</artifactId>
-
<version>2.8.5</version>
-
</dependency>
因此,请求json和返回json,需要注意添加jacson的三个jar包和在请求的contentType中设置application/json,并将数据写成jacson串的格式
2。请求为普通的key-value格式的,返回json串,这种一般和浏览器中使用get方式后买你带参数方式类似
-
//请求key-value,输出json
-
$("#regist").click(function () {
-
$.ajax({
-
type:'post',
-
url:'${pageContext.request.contextPath}/doRegist.action',
-
//这里设置contentType为不需要设置,默认就好
-
//数据格式为key-value
-
data:'username=zcj&password=admin&repeatpwd=admin',
-
success:function (result) {
-
alert(result.username);
-
},
-
error:function (result) {
-
-
}
-
});
-
});
后台也没什么变化,就是将解析json串的@RequesBody注解给拿掉就好了如下:
-
@RequestMapping("/doRegist")
-
public @ResponseBody UserVo doRegist(UserVo userVo){
-
return userVo;
-
}
上述两种方法中都用到了一个用于接收前端数据的vo,UserVo定义如下:
-
package com.ajin.vo;
-
-
-
public class UserVo {
-
private String username;
-
private String password;
-
private String repeatpwd;
-
-
public String getRepeatpwd() {
-
return repeatpwd;
-
}
-
-
public void setRepeatpwd(String repeatpwd) {
-
this.repeatpwd = repeatpwd;
-
}
-
-
public String getUsername() {
-
return username;
-
}
-
-
public void setUsername(String username) {
-
this.username = username;
-
}
-
-
public String getPassword() {
-
return password;
-
}
-
-
public void setPassword(String password) {
-
this.password = password;
-
}
-
-
}
二、浏览器url中这种方式的数据获取
(5)第五种,接收来自url中的参数
这个一般是针对使用get方式,来自url中传递的参数的解析,使用的是@RequestParam这个注解
之所以需要这个注解是因为,对于第一种这样的情况,必须要求request传入的参数名称和controller的参数一样,使用注解就可以通过指定value属性,实现形参名称和传入的参数名称不一样的情况
-
http://localhost:8080/main.action?name=test
后台controller
-
@RequestMapping("/main")
-
public ModelAndView main(@RequestParam(value = "name") String username ){
-
User user=new User();
-
user.setName(username);
-
ModelAndView modelAndView = new ModelAndView();
-
modelAndView.addObject("user",user);
-
modelAndView.setViewName("main");
-
return modelAndView;
-
}
可以看到我们url中参数是name,在controller中形参名称叫username,解除了必须一致的约束
对于有些比如时间这样的格式,我们在定义自己的vo时,就可能出现需要把日期串转化为java对象中的日期类型
方法:
1。实现Converter<String,Date>接口
-
import org.springframework.core.convert.converter.Converter;
-
import java.text.ParseException;
-
import java.text.SimpleDateFormat;
-
import java.util.Date;
-
-
/**
-
* Created by ajin on 16-12-8.
-
*/
-
public class StringDateConverter implements Converter<String,Date> {
-
//实现convert方法
-
public Date convert(String s) {
-
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
-
try {
-
return simpleDateFormat.parse(s);
-
}catch (ParseException e){
-
e.printStackTrace();
-
}
-
return null;
-
}
-
}
并在spring-mvc的配置文件中加上如下
-
<!-- 配置处理器映射器和处理器适配器 -->
-
<mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
-
-
<!-- 自定义参数绑定 -->
-
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
-
<!-- 转换器-->
-
<property name="converters">
-
<list>
-
<!-- 日期格式转换-->
-
<bean class="com.ajin.converter.StringDateConverter"></bean>
-
</list>
-
</property>
-
</bean>
springMVC和strusts的区别:
1。springmvc是基于方法开发的,struts2是基于类开发的
(1)springmvc将url和controller方法映射。映射成功后,生成一个handler对象,对象只包含方法,方法执行结束,形参数据销毁
(2)springmvc可以设置为单例模式,struts2通过类的成员变量来接收,无法使用单例。
(3)struts2经过测试,速度慢因为strusts2标签,建议jstl
---------------------------------------------------------postman--------------------------------------------------------------
最近在用postman测试postman接口,对于springmvc传值这一块,测试了几种常用方式,总结一下。对于postman这个工具的使用也增加了了解。postman测试很棒,有了工具,测试接口,事倍功半。
一、单个参数传递
[email protected]注解
-
<span style="font-family:KaiTi_GB2312;font-size:18px;"> /**
-
* 测试单个参数@RequestBody
-
*/
-
@CrossOrigin
-
@RequestMapping(value = {"/insertTestParamsRequest"}, method = RequestMethod.GET)
-
@ResponseBody
-
public void insertTestParamsRequest(@RequestBody String name, @RequestBody String age) {
-
System.out.println("name=====" + name);
-
System.out.println("age=====" + age);
-
}
-
</span>
测试请求路径
[email protected]
常用来处理简单类型的绑定,通过Request.getParameter() 获取的String可直接转换为简单类型的情况( ;
该注解有两个属性: value、required; value用来指定要传入值的id名称,required用来指示参数是否必须绑定;
-
<span style="font-family:KaiTi_GB2312;font-size:18px;"> /**
-
* 测试单个参数@RequestParam
-
*/
-
@CrossOrigin
-
@RequestMapping(value = {"/insertTestParams"}, method = RequestMethod.GET)
-
@ResponseBody
-
public void insertTestParams(HttpServletRequest request, @RequestParam String name, @RequestParam String age) {
-
System.out.println("name=====" + name);
-
System.out.println("age=====" + age);
-
}</span>
请求路径:

[email protected]注解
路径为resultful风格,将参数当做请求路径。
当使用@RequestMapping URI template 样式映射时, 即 Url/{paramId}, 这时的paramId可通过 @Pathvariable注解绑定它传过来的值到方法的参数上。
-
<span style="font-family:KaiTi_GB2312;font-size:18px;"> /**
-
* 测试单个参数@PathVariable
-
*/
-
@CrossOrigin
-
@RequestMapping(value = {"/insertTest/{name}/{age}"}, method = RequestMethod.GET)
-
@ResponseBody
-
public void insertTestPathVeriable(HttpServletRequest request, @PathVariable("name") String name, @PathVariable String age) {
-
System.out.println("name=====" + name);
-
System.out.println("age=====" + age);
-
}</span>
上面代码把URI template 中变量 name的值和age的值,绑定到方法的参数上。若方法参数名称和需要绑定的uri template中变量名称不一致,需要在@PathVariable("name")指定uri template中的名称。
二、传递pojo对象
[email protected]注解
-
<span style="font-family:KaiTi_GB2312;font-size:18px;"> /*测试添加实体*/
-
@CrossOrigin
-
@RequestMapping(value = {"/insertEntityTest"}, method = RequestMethod.POST)
-
@ResponseBody
-
public void insertEntityTest(@RequestBody CurriculumScheduleEntity curriculumScheduleEntity) {
-
System.out.println("name=====" + curriculumScheduleEntity.getClassId());
-
System.out.println("age=====" + curriculumScheduleEntity.getTeachclassId());
-
}</span>
postman通过json格式测试

2.直接写实体
-
<span style="font-family:KaiTi_GB2312;font-size:18px;"> /*测试添加实体*/
-
@CrossOrigin
-
@RequestMapping(value = {"/insertTest"}, method = RequestMethod.POST)
-
@ResponseBody
-
public void insertTest(CurriculumScheduleEntity curriculumScheduleEntity) {
-
System.out.println("name=====" + curriculumScheduleEntity.getClassId());
-
System.out.println("age=====" + curriculumScheduleEntity.getWeekId());
-
}</span>
form表单测试
-
<span style="font-family:KaiTi_GB2312;font-size:18px;"><div>
-
<form action="/curriculumSchedule/insertTest" method="post">
-
classId :<input name="classId"><br>
-
teachClassId:<input name="weekId"><br>
-
<input type="submit" value="提交">
-
</form>
-
</div></span>
postman测试格式

三、postman测试List类型参数
以List<string>为例,测试批量删除方法,参数为List<String>。写这个其实没有什么技术,但是中午在测试List接口的时候,用postman测试,格式一致写错,不知道用postman该怎么测试了。所以花费了一点时间,记录下来,思考这个工具的执行过程。

Controller方法
