最近在学习spring mvc的时间常常遇到RequestMapping,便小小的整理一下
通配符
在RequestMapping中我们可以使用*号表示通配符从而匹配一系列的请求:
@RequestMapping("/test*.do")
表示请求的url中只要是以test开头就可以被当前方法处理。
@RequestMapping("/*test.do")
表示请求的url中只要是以test结尾就可以被当前方法处理。
@RequestMapping("monkey/*/test.do")
表示在test.do的前面,只能有两级路径,第一级必须是monkey,而第二级随意,例如:monkey/1024/test.do。这种称为路径级数的精确匹配。
@RequestMapping("monkey/**/test.do")
表示在test.do的资源名称前面,必须以monkey路径开头,而其它级的路径包含几级,各级又叫什么名称,均随意,例如:monkey/1/0/2/4/test.do。 这种称为路径级数的可变匹配。
请求的提交方式
在@RequestMapping中有一个method属性,改属性可以设置接收请求的提交方式:
@RequestMapping(value="/test.do",method = RequestMethod.POST)
public ModelAndView test(HttpServletRequest request, HttpServletResponse response) throws Exception {
ModelAndView mv = new ModelAndView();
mv.addObject("hello", "test");
mv.setViewName("test1");
return mv;
}
上面的注解表示,只有当/test.do的请求的方式是post的时候才会执行当前方法,对于其他请求方式不进行处理。如果不写method属性的话,无论你是使用get或者post或者其他方式,它都会进行处理。
上面的RequestMethod是一个枚举类型,里面包含了大部分的提交方式。
示例,创建一个Controller,里面添加连个方法分别只处理get和post方式的请求:
package com.baron.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Controller//表示当前类是一个controller
@RequestMapping("/test")//表示是一个命名空间namespace
public class TestController03 {
@RequestMapping(value="/requestGet.do",method = RequestMethod.GET)
public ModelAndView reqGet(HttpServletRequest request, HttpServletResponse response) throws Exception {
ModelAndView mv = new ModelAndView();
mv.addObject("method", "get请求");
mv.setViewName("get");
return mv;
}
@RequestMapping(value="/requestPost.do",method = RequestMethod.POST)
public ModelAndView reqPost(HttpServletRequest request, HttpServletResponse response) throws Exception {
ModelAndView mv = new ModelAndView();
mv.addObject("hello", "post请求");
mv.setViewName("post");
return mv;
}
}
index.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<form action="/test/requestGet.do" method="get">
<input type="submit" value="get请求">
</form>
<br>
<form action="/test/requestPost.do" method="post">
<input type="submit" value="post请求">
</form>
</body>
</html>
请求中携带的参数
在RequestMapping中还有一个属性是params,通过这个属性我们可以指定请求中必须携带的参数。
@RequestMapping(value="/test.do" , params={"name" , "age"})
要求请求中必须携带请求参数 name 与 age
@RequestMapping(value="/test.do" , params={"!name" , "age"})
要求请求中必须携带请求参数 age,但必须不能携带参数 name
@RequestMapping(value="/test.do" , params={"name=jack" , "age=23"})
要求请求中必须携带请求参数 name,且其值必须为jack;必须携带参数 age,其值必须为 23
@RequestMapping(value="/test.do" , params="name!=jack")
要求请求中必须携带请求参数name,且其值必须不能为jack