SpringMVC使用< mvc:annotation-driven/>配置标签全面开启MVC相关注解功能。
请求映射与参数注解
@RequestMapping
//localhost:8080/SpringMVC_war/anno-demo/hello
@Controller //控制器注解
@RequestMapping("/anno-demo") //类中请求映射注解
//@RequestMapping(value="/anno-demo") //使用value属性指定映射
public class AnnoDemoController {
@RequestMapping("/hello") //方法层级的请求注解
public ModelAndView hello(){
ModelAndView modelAndView = new ModelAndView();
return modelAndView;
}
}
@RequestMapping 是一个通用的请求映射,可以通过method属性指定不同的请求。
//等同于@GetMapping(value="hello")
@RequestMapping(value="/hello",method=RequestMethod.GET)
同时,还可以通过consumes和produces属性指定请求和返回的媒体格式。
- consumes处理请求的提交内容(Content-Type),例如application/json,text/html。
- produces返回的内容类型。
@RequestMapping(value="/users",method=RequestMethod.POST,
consumes="application/json",produces="application/json;charset=UTF-8")
@ResponseBody
public List<User> addUser(@RequestBody User user1){
return null;
}
设置headers属性可以限定包含此请求头参数的请求。
@RequestMapping(path="/request",headers="type=withHeaderAttr")
设置请求的URL包含参数,/request?name=value1
@RequestMapping(path="request",params="type=withParams")
@RequestParam使用在映射方法的形参中,用来匹配一些简单的类型,默认情况下,请求参数与映射方法参数需要同名。可以设置required属性为false来取消限制,还可以使用value属性设置映射到前端请求的参数名。
@RequestMapping("/hello")
public ModelAndView hello(@RequsetParam(value="userName",required=true) String userName){
}
@RequestParam也可以不使用,容器会根据参数名称自动匹配。如果方法的形参是一个对象类型的话,容器还会将请求中的参数自动装箱,也就是创建该类的对象。
//localhost:8080/hello?name=Oscar
@Controller
@RequestMapping("/hello")
public MOdelAndView hello(User user){//将会创建User对象,并将name传给user
}
@PathVariable注解使用在映射方法参数中,用来绑定映射注解中的URL占位符的值,并赋给该参数。
@RequestMapping(value="/hello/{username}")
public ModelAndView hello(@PathVariable String username){
}
当使用/hello/ZhangSan 时,会将路径中的ZhangSan绑定给username。