springMVC中的注解
@RequestMapping
概念:处理请求地址映射(将请求映射到Controller的方法上)。
说明:用在类或方法上
用在类上: 表示该方法是一个可以响应请求的方法。
用在方法上:表示类中所有响应请求的方法都是以该地址作为父路径。
属性:
value: 指定请求的url
method:指定请求的method类型(GET、POST、PUT、DELETE等)
params: 指定request中必须包含的参数值
headers: 指定request中必须包含的header值
consumes:指定类或方法可以接受的MIME类型
produces: 指定类或方法可以返回的MIME类型
@RequestParam
概念:将请求的单个参数映射到方法的参数上。
说明:用在方法的参数上。
属性:
value: 请求的参数名
required: 是否必须传入该参数,默认为true。
defaultValue: 默认值,该属性存在时,required属性自动设为false。
注意:接收查询参数(url中的参数),不能接收body中的参数。get、post方法均适用。
@PathVariable
概念:将请求URL中的模板变量映射到方法的参数上。
说明:用在方法的参数上。
举例:
@RequestMapping(value = "{pageName}", method = RequestMethod.GET)
public String toPage(@PathVariable("pageName") String pageName) {
System.out.println("ok");
return pageName;
}
@RequestBody
作用:
读取request请求中body里面的数据,使用系统默认的HttpMessageConverter进行解析,然后将HttpMessageConverter返回的对象绑定到controller中方法的参数上。
使用场景:根据request请求头中Content-Type的值来判断:
1)multipart/form-data
不能使用@RequestBody来处理
2)其它格式(application/json、application/xml等)
必须使用@RequestBody来处理
3)application/x-www-form-urlencoded
GET、POST请求: 可选(@RequestParam、@ModelAttribute也可以处理该类型的请求参数)
PUT请求: 必须使用@RequestBody来处理
说明:request中body里面的数据编码格式是由header里面的Content-Type属性指定。
举例:
@RequestMapping(value = "/user/save", method = RequestMethod.POST)
public void saveUser(@RequestBody User user) {
userService.save(user);
}
注意:不能接收查询参数(url中的参数),可以接收body中的参数。
@ResponseBody
作用:
将Controller中方法要返回的对象(即返回值) 通过适当的HttpMessageConverter转换为指定格式后,写入到response对象的body数据区。
使用场景:
返回数据的格式为json、xml等。
注意:
在使用该注解后,方法的返回值不会被解析为跳转路径(即不会再走视图解析器),而是直接将数据写入到response对象的body数据区中。
举例:
@RequestMapping(value = "/user/sex/{name}", method = RequestMethod.GET)
@ResponseBody
public String getUserSexByName(@PathVariable("name") String name) {
return userService.getUserSexByName(name);
}
结果:
在浏览器页面中显示:MALE
@RestController
说明:
1)@RestController是spring4的新特性。
2)当需要实现一个RESTful web services的时候,只需要在类上添加@RestController注解即可,方法的返回值将会被写入到response的body中。
定义:
/**
* A convenience annotation that is itself annotated with @Controller and @ResponseBody.
* Types that carry this annotation are treated as controllers where @RequestMapping methods assume @ResponseBody semantics by default.
*
* 注解本身被@Controller和@ResponseBody修饰。
* 被这个注解修饰的Type被认为是一个Controller,这个Controller中所有被@RequestMapping修饰的方法默认都会被@ResponseBody修饰。
* 相当于:@RestController = @Controller + @ResponseBody
*
* @since 4.0
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {
String value() default "";
}
注意:在使用该注解后,方法的返回值不会被解析为跳转路径(即不会再走视图解析器),而是直接将数据写入到response对象的body数据区中。
@ControllerAdvice
说明:使用 @ControllerAdvice + @ExceptionHandler 来统一处理controller中各方法抛出的异常。
步骤:
1.定义一个被@ControllerAdvice注解修饰的类
2.在该类中指定各异常的处理逻辑
举例:
@ControllerAdvice
public class GlobalExceptionHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler(MyException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public MyResponseBody handleError(HttpServletRequest request, MyException e) {
LOGGER.error("request uri [{}] error, method: [{}]", request.getRequestURI(), request.getMethod(), e);
return new MyResponseBody();
}
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public MyResponseBody handleError(HttpServletRequest request, Exception e) {
LOGGER.error("request uri [{}] error, method: [{}]", request.getRequestURI(), request.getMethod(), e);
return new MyResponseBody();
}
}