- 在异常及异常父类中找到 @ResponseStatus 注解,然后使用这个注解的属性进行处理。
- 定义一个 @ResponseStatus 注解修饰的异常类
- 若在处理器方法中抛出了上述异常:若ExceptionHandlerExceptionResolver 不解析上述异常。由于触发的异常 UnauthorizedException 带有@ResponseStatus 注解。因此会被ResponseStatusExceptionResolver 解析到。最后响应UNAUTHORIZED 代码给客户端。HttpStatus.UNAUTHORIZED 代表响应码401,无权限。 关于其他的响应码请参考 HttpStatus 枚举类型源码。
org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver Implementation of the HandlerExceptionResolver interface that uses the @ResponseStatus annotation to map exceptions to HTTP status codes. This exception resolver is enabled by default in the |
1 实验代码
- 页面链接
<a href=”testResponseStatusExceptionResolver?i=10″>testResponseStatusExceptionResolver</a> |
- 自定义异常类
package com.atguigu.springmvc.exception;
import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus;
/** * 自定义异常类 HttpStatus.FORBIDDEN 不允许的,禁用的 */ @ResponseStatus(value=HttpStatus.FORBIDDEN,reason=”用户名称和密码不匹配“) public class UsernameNotMatchPasswordException extends RuntimeException{} |
- 控制器方法
@RequestMapping(value=”/testResponseStatusExceptionResolver”) public String testResponseStatusExceptionResolver(@RequestParam(“i”) int i){ if(i==13){ throw new UsernameNotMatchPasswordException(); } System.out.println(“testResponseStatusExceptionResolver…”); return “success”; } |
- 出现的错误消息
- 没使用注解时:@ResponseStatus(value=HttpStatus.FORBIDDEN,reason=”用户名称和密码不匹配“)
- 使用注解时:@ResponseStatus(value=HttpStatus.FORBIDDEN,reason=”用户名称和密码不匹配“)
- 测试在方法上使用注解
@ResponseStatus(value=HttpStatus.NOT_FOUND,reason=”测试方法上设置响应状态码“) @RequestMapping(value=”/testResponseStatusExceptionResolver”) public String testResponseStatusExceptionResolver(@RequestParam(“i”) int i){ if(i==13){ throw new UsernameNotMatchPasswordException(); } System.out.println(“testResponseStatusExceptionResolver…”); return “success”; } |
- ResponseStatus
package org.springframework.web.bind.annotation;
import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target;
import org.springframework.http.HttpStatus;
/** * Marks a method or exception class with the status code and reason that should be returned. The status code is applied * to the HTTP response when the handler method is invoked, or whenever said exception is thrown. * * @author Arjen Poutsma * @see org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver * @since 3.0 */ @Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface ResponseStatus {
HttpStatus value();
String reason() default “”;
} |
- HttpStatus
上一篇: java培训异常处理之ExceptionHandlerExceptionResolver
下一篇: 前端培训工作后如何提高自己