注:在类上使用注解@RequestMapping(value="/User")
一、通过@PathVariabl注解获取路径中传递参数
/**
* 通过@PathVariable注解获取路径中传递参数
* @param id
* @param str
*/
@RequestMapping(value="/{id}/{str}")
public ModelAndView test(@PathVariable String id,@PathVariable String str){
System.out.println(id);
System.out.println(str);
return new ModelAndView("user/helloWorld");
}
如请求的URL为“控制器URL/User/123/lixiaoxi”,则自动将URL中模板变量{id}和{str}绑定到通过@PathVariable注解的同名参数上,即入参后id=123、str=lixiaoxi。
二、用@ModelAttribute注解获取POST请求的FORM表单数据
JSP
<form method="post" action="<%=request.getContextPath()%>/User/doSubmit">
a: <input id="a" type="text" name="a"/>
b: <input id="b" type="text" name="b"/>
<input type="submit" value="提交" />
</form>
Java Pojo
package demo.model;
public class Pojo {
private String a;
private int b;
public String getA(){
return this.a;
}
public void setA(String a){
this.a=a;
}
public int getB(){
return this.b;
}
public void setB(int b){
this.b=b;
}
}
Java Controller
/**
* 用@ModelAttribute注解获取POST请求的FORM表单数据
* @param pojo
* @return
*/
@RequestMapping(value="/doSubmit",method=RequestMethod.POST)
public String doSubmit(@ModelAttribute("pojo") Pojo pojo){
System.out.println(pojo.getA());
System.out.println(pojo.getB());
return "user/helloWorld";
}
三、直接用HttpServletRequest获取
Java
/**
* 直接用HttpServletRequest获取
* @param request
* @param response
* @return
*/
@RequestMapping(value="/get",method= RequestMethod.GET)
public String get(HttpServletRequest request, HttpServletResponse response) {
System.out.println(request.getParameter("a"));
return "user/helloWorld " ;
}
四、用注解@RequestParam绑定请求参数a到变量a
当请求参数a不存在时会有异常发生,可以通过设置属性required=false解决,
例如: @RequestParam(value="a", required=false)
JAVA
/**
* 用注解@RequestParam绑定请求参数a到变量a
* @param a
* @return
*/
@RequestMapping(value= "/requestParam" , method= RequestMethod.GET)
public String setupForm(@RequestParam("a") String a) {
System.out.println(a);
return "user/helloWorld " ;
}