SpringMVC参数接收
1、通过HttpRequest
@RequestMapping("/save.do")
public String Save(HttpServletRequest request){
String userName=request.getParameter("userName");
String gender = request.getParameter("gender");
System.out.println("UserName:"+userName);
System.out.println("Gender:"+gender);
return "index";
}
2、通过Model
public class User {
private String userName;
private String gender;
private Integer age;
get set方法省略
}
提交表单的数据 只要包含userName,gender,age,Spring会自动注入
@RequestMapping("/save1.do")
public String Save(User user){
System.out.println("(Model)UserName:"+user.getUserName());
System.out.println("(Model)Gender:"+user.getGender());
return "index";
}
3、通过URL
@RequestMapping("/save2/{userName}/{gender}.do")
public String Save(@PathVariable("userName")String userName,@PathVariable("gender")String gender ){
System.out.println("(url)UserName:"+userName);
System.out.println("(url)Gender:"+gender);
return "index";
}
请求的URL/save2/cym/m.do, 接收到的参数值userName=cym,gender=m
4
@RequestMapping("/save3.do")
public String Save3(String userName){
try {
String strTemp = new String(userName.getBytes("ISO-8859-1"),"utf-8");
System.out.println("(url)UserName:"+strTemp);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return "index";
}
请求的URL/save3.do?userName=cym
5 ModelMap
@RequestMapping("/modelmap.do")
public String par1(ModelMap map){
map.put("msg", "2015-01-13");
return "modelmap";
}
jsp页面通过${msg}可以取到值
6 ModelAttribute
@RequestMapping("/modelattribute.do")
public String par2(@ModelAttribute("user")User user){
user.setAge(30);
user.setGender("F");
user.setUserName("cwg");
return "modelmap";
}
jsp页面取值 ${user.age } ${user.gender } ${user.userName }
将user变成session级别
@Controller
@RequestMapping("/session")
@SessionAttributes("user")
public class SessionController {
@ModelAttribute("user")
public User getUser(){
return new User();
}
@RequestMapping("/modelattribute.do")
public String par2(@ModelAttribute("user")User user){
user.setAge(30);
user.setGender("F");
user.setUserName("cwg");
return "modelmap";
}
}
注:通过这种方式将user作用域提升到session级别不能通过HttpSession对象iinvalidate(),removeAttribute清除
可能用如下方式清除
@RequestMapping("/loginout.do")
public String loginout(SessionStatus sessionStatus){
sessionStatus.setComplete();
return "modelmap";
}