javaspringspring-mvcspring-jersey

Always call function before @RequestMapping function


I'm creating a API spring service using spring framework.

I've several @RequestMapping function for each endpoint that i define. In every @RequestMapping function, i have a function to check several authorization variables before continue.

Can I put this authorization function to a specific function before I forward to the related @RequestMapping function?


Solution

  • A HandlerInterceptor implementation as suggested elsewhere is what you want. From your comments in response to that answer however you misunderstand the API:

    I have read method preHandle in documentation link that you gave.. but it return boolean.. can i return JSON output using this method?

    As the API Docs note the boolean only signals (to the framework) whether processing should continue:

    https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/HandlerInterceptor.html#preHandle-javax.servlet.http.HttpServletRequest-javax.servlet.http.HttpServletResponse-java.lang.Object-

    returns true if the execution chain should proceed with the next interceptor or the handler itself. Else, DispatcherServlet assumes that this interceptor has already dealt with the response itself.

    So to return JSON:

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
     Object handler) throws Exception{
    
        if(someCondition){
          return true; //continue processing
        }else{
          response.getOutputStream().write("{\"message\" : \"some text\"}");
          response.setContentType("text/json");
          response.setStatus(...); //some http error code?
          response.getoutputStream().flush();
          return false; //i have written some JSON to the response. Processing stops here
        }
    }