使用处理程序Intercptor跳过调用rest控制器类

时间:2018-10-17 18:42:54

标签: spring rest spring-boot interceptor spring-restcontroller

我已经使用Spring Boot编写了一个小的rest api。

url-http://localhost:8080/REST/api/testservice

测试控制器类

@RestController
@Scope("request")
@RequestMapping("/api")
public class TestRestController {
    private final Log logger = LogFactory.getLog(getClass());

    @Autowired
    Common common;

    @Autowired
    CommonVarList commonVarList;


    @CrossOrigin
    @RequestMapping(value = "/testservice", method = RequestMethod.GET)
    public ResponseEntity<ResponseBean> getCheckUser() {
        return new ResponseEntity<ResponseBean>(new ResponseBean(Boolean.parseBoolean(commonVarList.BOOLEAN_DEFAULT_TRUE),common.getLocaleMessage(MessageVarList.IB_SERVICE_RUNNING)), HttpStatus.OK);
    }
}

我也写了一个拦截器类。

侦听器类

public class TestRestInterceptor implements HandlerInterceptor {
    final static Logger logger = Logger.getLogger(IbRestInterceptor.class);

    @Autowired
    Common common;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        //check request time out here
        boolean isRequestTimeOut = common.checkUserTimeOut();
        if(isRequestTimeOut){
            httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/api/request/timeout");
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        //TODO
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {}
}

TimeOut Rest Controller类

@RestController
@Scope("request")
@RequestMapping(path = "/api/request")
public class ResponseRestController {

    @Autowired
    RequestHandlerService requestHandlerService;

    @CrossOrigin
    @RequestMapping(value = "/timeout", method = RequestMethod.GET)
    public ResponseEntity<ResponseBean> postUserTimeOut(){
        ResponseBean responseBean=requestHandlerService.handleRequestTimeOut();
        return new ResponseEntity<ResponseBean>(responseBean,HttpStatus.REQUEST_TIMEOUT);
    }
}

我已经使用 httpServletResponse.sendRedirect 在用户请求超时时跳过调用 / api / testservice 休息控制器类。

但是它会调用 / api / testservice 休息控制器类,然后再调用 / api / request / timeout 休息控制器类。

我只想在用户请求超时时跳过调用 / api / testservice rest控制器类。

任何人都可以描述如何解决此问题。这将非常有帮助。预先感谢

1 个答案:

答案 0 :(得分:1)

文档说

  

DispatcherServlet处理执行链中的处理程序,   由任意数量的拦截器组成,处理程序本身位于   结束。使用此方法,每个拦截器都可以决定中止   执行链,通常发送HTTP错误或编写自定义   响应。

和说明preHandle方法

  

返回:       如果执行链应该继续下一个拦截器或处理程序本身,则返回true。否则,DispatcherServlet假设   该拦截器已经处理了响应本身。

因此,如果您在拦截器中引发异常或写入响应并返回false,则调用不会到达实际的处理程序(控制器)。