RequestMapping中有六个属性分别是:
value: 指定请求的实际地址,指定的地址可以是URI Template 模式;
method: 指定请求的method类型, GET、POST、PUT、DELETE等;
consumes: 指定处理请求的提交内容类型(Content-Type),例如application/json, text/html;
produces: 指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回;
params: 指定request中必须包含某些参数值是,才让该方法处理。
headers: 指定request中必须包含某些指定的header值,才能让该方法处理请求。
其中比较常用的是value,method,params;
1.RequestMapping最基础的用法就是实现类或者方法的访问控制:例如下面案例就是方法上面的控制:
- @RequestMapping(value = "testlogin.do",method = RequestMethod.POST)
- public String testLogin(){
- return "redirect:login";
- }
- <form id="loginTestForm" action="testlogin.do" method="post">
- <input type="submit" value="submit">
- </form>
这里需要注意的是form表单中提交的方式要和方法里面的method一直,否则就会报错。上面的例子中两个都是post方法提交的。
2.RequestMapping带参数的情况:
- @RequestMapping(value = "testlogin.do",method = RequestMethod.POST)
- public String testLogin(@RequestParam("departmentId") String departmentId){
- System.out.println("输入的参数为:"+departmentId);
- return "redirect:login";
- }
- <form id="loginTestForm" action="testlogin.do" method="post">
- <input type="text" name="departmentId" id="departmentId"></br>
- <input type="submit" value="submit">
- </form>
- <form id="loginTestForm" action="testlogin.do?departmentId=123" method="post">
- <input type="submit" value="submit">
- </form>
3.RequestMapping中获取URL中的参数信息:
- <form id="loginTestForm" action="testlogin.do/adc" method="post">
- <input type="submit" value="submit">
- </form>
- @RequestMapping(value = "testlogin.do/{departmentId}",method = RequestMethod.POST)
- public String testLogin(@PathVariable("departmentId") String departmentId){
- System.out.println("输入的URL参数为:"+departmentId);
- return "redirect:login";
- }
当然也可以绑定多个参数,例如:
- @RequestMapping(value = "testlogin.do/departmentId/{departmentId}/departmentName/{departmentName}",method = RequestMethod.POST)
- public String testLogin(@PathVariable("departmentId") String departmentId,@PathVariable("departmentName") String departmentName){
- System.out.println("输入的URL参数为1:"+departmentId);
- tem.out.println("输入的URL参数为2:"+departmentName);
- return "redirect:login";
- }
到这里RequestMapping一些常用的方法就介绍完了,当然还有很多其他的用法。例如:在类中中实现action控制,方法之间相互访问跳转之类的,不过这些方法的实现基本都是基于RequestMapping这些常用方法实现的。