@ResponseStatus注解的使用

带有@ResponseStatus注解的异常类会被ResponseStatusExceptionResolver 解析。可以实现自定义的一些异常,同时在页面上进行显示。具体的使用方法如下:

 

1.首先定义一个异常类:

 

@ResponseStatus(value = HttpStatus.FORBIDDEN,reason = "用户名和密码不匹配!")
public class UserNameNotMatchPasswordException extends RuntimeException{
        
}


2.人为抛出一个异常:

 

 

  @RequestMapping("/testResponseStatusExceptionResolver")
    public String testResponseStatusExceptionResolver(@RequestParam("i") int i){
        if (i==13){
            throw new UserNameNotMatchPasswordException();
        }
        System.out.println("testResponseStatusExceptionResolver....");
        return "success";
    }


3.输入如下额路径:

 

http://localhost:8090/testResponseStatusExceptionResolver?i=13

@ResponseStatus注解的使用_第1张图片

当然,也可以在方法上进行修饰:

 

@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";
    }


这时所有的请求都会报错。

 

@ResponseStatus注解的使用_第2张图片

你可能感兴趣的:(spring,mvc)