How to use Spring AOP to run code before every call of service method in Servlet

659 views Asked by At

I have some common code must be injected into service method of any servlet .

Thus, i build a mother servlet SuperController :

public class SuperController extends HttpServlet{
     private HttpServletRequest lastRequest ; 
     //........
     public void service(HttpServletRequest req,HttpServletResponse res){
          setLastRequest(req); // example of common code
     }
}

Then, all other servlets extends from this servlet .

public GalleryServlet extends SuperController{

      public void service(HttpServletRequest req,HttpServletResponse res){
           //instead of running here the common code , use AOP. 
           // Then , the other code
      }

}

I want to execute the common code ( i.e: setLastRequest(req)) using AOP , since super.service(req,res) raised ERROR 405 .

com.ControllerAspect.java

@Before("* com.SuperController+.service(..)")
public void doStuffBeforeService(JoinPoint joinPoint) {
    // do stuff here
}

How to Use Spring AOP :

  • Does this pointcut * com.SuperController+.service(..) includes service methods in all classes inherits from com.SuperController .

  • How to access to arguments (req & res ) of service method inside doStuffBeforeService ?

1

There are 1 answers

0
Bond - Java Bond On BEST ANSWER

HTTP 405 means that the HTTP request method is not supported e.g. GET used for POST etc. Check your config / logs for supported method(s) and the one actually used.

To answer your other questions -

  • Yes the pointcut * com.SuperController+.service(..) should include service method(s) in com.SuperController class hierarchy. See here.
  • Use joinPoint.getArgs() to access the method arguments.