在spring Controller中返回自定义的Http code

本文介绍在Spring MVC框架中如何使Controller返回404状态码,包括自定义异常结合@ResponseStatus注解、利用内置异常及直接设置HttpServletResponse状态码三种方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

怎么在Spring Controller里面返回404

SEP 27TH2014 6:02 PM

由于大多的客户端和服务端是独立的(可能用不同语言编写),客户端无法获知服务端的异常,所以普通的异常处理并不足以提示客户端。而基于HTTP协议的服务,我们则需要按照服务端的异常而返回特定的状态码给客户端。

以返回404状态码为例,在Spring 的Controller里面我们可以有以下3种方式处理:

  1. 自定义异常+@ResponseStatus注解:

     //定义一个自定义异常,抛出时返回状态码404
     @ResponseStatus(value = HttpStatus.NOT_FOUND)
     public class ResourceNotFoundException extends RuntimeException {
         ...
     }
    
     //在Controller里面直接抛出这个异常
     @Controller
     public class SomeController {
         @RequestMapping(value="/video/{id}",method=RequestMethod.GET)
         public @ResponseBody Video getVidoeById(@PathVariable long id){
             if (isFound()) {
                 // 做该做的逻辑
             }
             else {
                 throw new ResourceNotFoundException();//把这个异常抛出 
             }
         }
     }
    
  2. 使用Spring的内置异常

    默认情况下,Spring 的DispatcherServlet注册了DefaultHandlerExceptionResolver,这个resolver会处理标准的Spring MVC异常来表示特定的状态码

      Exception                                   HTTP Status Code
      ConversionNotSupportedException             500 (Internal Server Error)
      HttpMediaTypeNotAcceptableException         406 (Not Acceptable)
      HttpMediaTypeNotSupportedException          415 (Unsupported Media Type)
      HttpMessageNotReadableException             400 (Bad Request)
      HttpMessageNotWritableException             500 (Internal Server Error)
      HttpRequestMethodNotSupportedException      405 (Method Not Allowed)
      MissingServletRequestParameterException     400 (Bad Request)
      NoSuchRequestHandlingMethodException        404 (Not Found)
      TypeMismatchException                       400 (Bad Request)
    
  3. 在Controller方法中通过HttpServletResponse参数直接设值

     //任何一个RequestMapping 的函数都可以接受一个HttpServletResponse类型的参数
     @Controller
     public class SomeController {
         @RequestMapping(value="/video/{id}",method=RequestMethod.GET)
         public @ResponseBody Video getVidoeById(@PathVariable long id ,HttpServletResponse response){
             if (isFound()) {
                 // 做该做的逻辑
             }
             else {
                 response.setStatus(HttpServletResponse.SC_NOT_FOUND);//设置状态码
             }
             return ....
         }
     }

转载地址:http://jaskey.github.io/blog/2014/09/27/how-to-return-404-in-spring-controller/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值