1、通过@PathVariabl注解获取路径中传递参数
@RequestMapping(value = "/{name}")
public ModelAndView getPerson(@PathVariable String name){
System.out.println(name);
return new ModelAndView("/page");
}
2、用@ModelAttribute注解获取POST请求的FORM表单数据
(1) FORM表单
<form name="loginForm" action="/login" method="post">
<input type="text" name="name" /><br/><br/>
<input type="password" name="password" /><br/><br/>
<input type="submit" value="提交" />
</form>
(2) 定义JAVA POJO
public class Person() {
private String name;
private String password;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
(3) 后台代码
@RequestMapping(value="/login", method = RequestMethod.POST)
public ModelAndView toMainPage(@ModelAttribute("person") Person person){
String name = person.getName();
System.out.println(name);
String password = person.getPassword();
System.out.println(password );
return new ModelAndView("/loginSuccess");
}
注意, 其中表单中的name字段需要和POJO的属性字段一致
3、直接通过HttpServletRequest获取
@RequestMapping(value="/addPerson", method = RequestMethod.POST)
public ModelAndView addPerson(HttpServletRequest request, HttpServletResponse response){
String name = request.getParameter("name");
return new ModelAndView("/addSuccess");
}
4、用注解@RequestParam绑定请求参数
当请求参数不存在时会有异常发生,可以通过设置属性required=false解决
@RequestMapping(value="/getPerson", method = RequestMethod.GET)
public ModelAndView getPerson(@RequestParam("name") String name){
System.out.println(name);
return new ModelAndView("/addSuccess");
}