day02
湖南
SpringMvc请求参数获取的几种方法
1.直接把表单的参数写在Controller相应的方法的形参中,适用于get方式提交,不适用于post方式提交。
URL形式:http://localhost/SSMDemo/demo/addUser1?username=elliottmoo&password=111111 提交的参数需要和Controller方法中的入参名称一致。
/**
* 1.直接把表单的参数写在Controller相应的方法的形参中
* @param username
* @param password
* @return
*/
@RequestMapping("/addUser1")
public String addUser1(String username,String password) {
System.out.println("username is:"+username);
System.out.println("password is:"+password);
return "demo/index";
}
2.通过HttpServletRequest接收,post方式和get方式都可以
/**
* 2、通过HttpServletRequest接收
* @param request
* @return
*/
@RequestMapping("/addUser2")
public String addUser2(HttpServletRequest request) {
String username=request.getParameter("username");
String password=request.getParameter("password");
System.out.println("username is:"+username);
System.out.println("password is:"+password);
return "demo/index";
}
3.通过一个bean来接收,post方式和get方式都可以
/**
* 3、通过一个bean来接收
* @param user
* @return
*/
@RequestMapping("/addUser3")
public String addUser3(UserModel user) {
System.out.println("username is:"+user.getUsername());
System.out.println("password is:"+user.getPassword());
return "demo/index";
}
4.通过@PathVariable获取路径中的参数
例如,访问http://localhost/SSMDemo/demo/addUser4/lixiaoxi/111111 路径时,则自动将URL中模板变量{username}和{password}绑定到通过@PathVariable注解的同名参数上,即入参后username=elliottmoo、password=111111
/**
* 4、通过@PathVariable获取路径中的参数
* @param username
* @param password
* @return
*/
@RequestMapping(value="/addUser4/{username}/{password}",method=RequestMethod.GET)
public String addUser4(@PathVariable String username,@PathVariable String password) {
System.out.println("username is:"+username);
System.out.println("password is:"+password);
return "demo/index";
}
5.用注解@RequestParam绑定请求参数到方法入参
当请求参数username不存在时会有异常发生,可以通过设置属性required=false解决,例如: @RequestParam(value="username", required=false)
/**
* 6、用注解@RequestParam绑定请求参数到方法入参
* @param username
* @param password
* @return
*/
@RequestMapping(value="/addUser6",method=RequestMethod.GET)
public String addUser6(@RequestParam("username") String username,@RequestParam("password") String password) {
System.out.println("username is:"+username);
System.out.println("password is:"+password);
return "demo/index";
}
6.SpringMVC中传递的参数对象中包含list的情况
var answerQues = {};
answerQues.type_id = select_type_id;
answerQues.queList = r; //var r = []; r是个数组 r.push({id:123,ques:'问题'});
answerQues.answId = answId;
answerQues.answ = answ_;
answerQues.quesId = quesId;
answerQues.ques = ques;
$.ajax({
url:ajax_add_edit_url,
type: 'POST',
async: false,
dataType:'json',
contentType : 'application/json;charset=utf-8', //设置请求头信息
data: JSON.stringify(answerQues),//将对象序列化成JSON字符串,必须是字符串,不能直接传对象
success:function(res){
if(res){
}
}
});
@ResponseBody
@RequestMapping("add.do")
public String add(HttpServletRequest request,@RequestBody AnswerQues answerQues){//@RequestBody一定要加上
system.out.print(answerQues.toString());
return "SUCCESS";
}