spring boot add if语句在控制器中的每个操作中

k10s72fa  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(259)

我需要重定向控制器中的每个操作,这取决于服务的某些条件。
例子:

@RestController
public class MyController{

    @Autowired
    private MyService myService;

    @GetMapping("/action1")
    public String action1() {
        if(myService.checkIfError()) {
            return "redirect:/error";
        } else {
            // specific code of action1
        }
    }

    @GetMapping("/action2")
    public String action2() {
        if(myService.checkIfError()) {
            return "redirect:/error";
        } else {
            // specific code of action2
        }
    }
}

在以上代码中 action1 以及 action2 有一些特定的代码,但部分代码 if(myService.checkIfError())return "redirect:/error";} 所有动作都一样。
有人能告诉我如何删除这个样板代码,以便保留特定于操作的代码吗?

wljmcqd8

wljmcqd81#

您可以为此使用筛选器:

@Component
public class YourFilter implements Filter {

    @Autowired
    private MyService myService;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {

        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;

        if (myService.checkIfError()) {
            httpServletResponse.sendRedirect("/error");
            return;
        }

        filterChain.doFilter(servletRequest, servletResponse);
    }
}

springboot将自动连接这个过滤器,它将拦截所有请求。

相关问题