Search code examples
javaspring-bootcontrollerboilerplate

Spring Boot add if statement in every action in controller


I need to redirect every action in the controller depending on some condition from the service.

Example:

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

In code above both action1 and action2 have some specific code, but part of code if(myService.checkIfError())return "redirect:/error";} is same to all actions.

Can someone tell me how to remove this boilerplate code so that code specific to actions remains?


Solution

  • You can use a filter for this:

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

    Spring Boot will autowire this filter, and it will intercept all requests.