(三) SpringMVC 之 @RequestMapping
(三) SpringMVC 之 @RequestMapping
1、@RequestMapping 简介
这个注解用来标记一个接口,这算是我们在接口开发中,使用最多的注解之一。
标记请求 URL 很简单,只需要在相应的方法上添加该注解即可:
@Controller
public class HelloController {
@RequestMapping("/hello")
public ModelAndView hello() {
return new ModelAndView("hello");
}
}
这里 @RequestMapping("/hello") 表示当请求地址为 /hello 的时候,这个方法会被触发。其中,地址可以是多个,就是可以多个地址映射到同一个方法。
@Controller
public class HelloController {
@RequestMapping({"/hello","/hello2"})
public ModelAndView hello() {
return new ModelAndView("hello");
}
}
这个配置,表示 /hello 和 /hello2 都可以访问到该方法。
2、请求窄化
同一个项目中,会存在多个接口,例如订单相关的接口都是 /order/xxx 格式的,用户相关的接口都是 /user/xxx 格式的。为了方便处理,这里的前缀(就是 /order、/user)可以统一在 Controller 上面处理。
@Controller
@RequestMapping("/user")
public class HelloController {
@RequestMapping({"/hello","/hello2"})
public ModelAndView hello() {
return new ModelAndView("hello");
}
}
当类上加了 @RequestMapping 注解之后,此时,要想访问到 hello ,地址就应该是 /user/hello 或者 /user/hello2
3、请求方法限定:method属性
默认情况下,使用 @RequestMapping 注解定义好的方法,可以被 GET 请求访问到,也可以被 POST 请求访问到,但是 DELETE 请求以及 PUT 请求不可以访问到。当然,我们也可以指定具体的访问方法:
@Controller
@RequestMapping("/user")
public class HelloController {
@RequestMapping(value = "/hello",method = RequestMethod.GET)
public ModelAndView hello() {
return new ModelAndView("hello");
}
}
通过 @RequestMapping 注解,指定了该接口只能被 GET 请求访问到,此时,该接口就不可以被 POST 以及请求请求访问到了。强行访问会报如下错误:

当然,限定的方法也可以有多个:
@Controller
@RequestMapping("/user")
public class HelloController {
@RequestMapping(value = "/hello",method = {RequestMethod.GET,RequestMethod.POST,RequestMethod.PUT,RequestMethod.DELETE})
public ModelAndView hello() {
return new ModelAndView("hello");
}
}
4、consumes、produces属性
consumes:指定处理请求的提交内容类型(Content-Type),例如application/json, text/html;
produces:指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回。
@RequestMapping(value = "/hello", consumes = "application/json", produces = "application/json")
public void hello(HttpServletRequest request,HttpServletResponse response) throws IOException {
response.getWriter().write("Hello-springMvc");
}
5 、params、headers属性
params: 指定request中必须包含某些参数值,才让该方法处理。
headers: 指定request中必须包含某些指定的header值,才能让该方法处理请求。
params示例:
@RequestMapping(value = "/hello.do",params = "id=10")
public void hello(HttpServletRequest request,HttpServletResponse response) throws IOException {
response.getWriter().write("Hello-springMvc");
}
headers示例:
@RequestMapping(value = "/hello.do",headers = "Referer=http://www.baidu.com/")
public void hello(HttpServletRequest request,HttpServletResponse response) throws IOException {
response.getWriter().write("Hello-springMvc");
}

浙公网安备 33010602011771号