ResponseStatusExceptionResolver
- 在异常及异常父类中找到@ResponseStatus注解,然后使用这个注解的属性进行处理。
- 顶一个@ResponseStatus注解修饰的异常类
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public class UnauthorizedException extends RuntimeException{}
- 若在处理器方法中抛出了上述异常:若ExceptionHandlerExceptionResolver不解析异常。由于触发的异常UnauthorizedExceptiuon带有@ResponseStatus注解。因此会被ResponseStatusExceptionResolver解析到。最后响应HttpStatus.UNAYTHORIZED代码给客户端。HttpStatus.UNAUTHORIZED代表响应码401,无权限。关于其他的响应码请参考HttpStatus枚举类型源码。
例子程序:
第一步:在index.jsp写上< a>标签
<br><br>
<a href="testResponseStatusExceptionResolver?i=10">Test ResponseStatusExceptionResolver</a>
第二步:新建一个类UserNameNotMatchPasswordException继承RuntimeException 注意声明@ResponseStatus
UserNameNotMatchPasswordException.java
package com.springmvc.test;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value=HttpStatus.FORBIDDEN,reason = "用户名和密码不匹配!")
public class UserNameNotMatchPasswordException extends RuntimeException{
private static final long serialVersionUID = 1L;
}
第三步:写handler方法
@RequestMapping("/testResponseStatusExceptionResolver")
public String testResponseStatusExceptionResolver(@RequestParam("i") int i){
if(i==13){
throw new UserNameNotMatchPasswordException();
}
System.out.println("testResponseStatusExceptionResolver...");
return "success";
}
我们来看效果,url在i==13的情况下
若handler方法就有@ResponseStatus声明
@ResponseStatus(reason = "测试",value = HttpStatus.NOT_FOUND)
@RequestMapping("/testResponseStatusExceptionResolver")
public String testResponseStatusExceptionResolver(@RequestParam("i") int i){
if(i==13){
throw new UserNameNotMatchPasswordException();
}
System.out.println("testResponseStatusExceptionResolver...");
return "success";
}
DefaultHandlerExceptionResovler
index.jsp
<a href="testDefaultHandlerExceptionResolver?i=10">Test DefaultHandlerExceptionResolver</a>
@RequestMapping(value = "/testDefaultHandlerExceptionResolver",method = RequestMethod.POST)
public String testDefaultHandlerExceptionResolver(){
System.out.println("testDefaultHandlerExceptionResolver...");
return "success";
}
也就是说,因为< a>提交方法是get,不是post,所以会报错。