AOP for Spring Controllers

Spring The capabilities of AOP are quite large, and this makes it easy to add cool and useful annotations to the controllers. For example, I wrote an @Authenticated annotation, which either allows authenticated users to go to the controller method, or redirects to the login page. Interesting stuff.

However, Spring controllers can return all kinds of types. They can return String, ModelAndView, or even void objects. My code base has methods that use all three types. However, I would like to modify the @Authenticated annotation to render and return the specific page I was hoping to do by returning a ModelAndView object. The only way to achieve this is by requiring all my controller methods to return a ModelAndView?

An example of a controller that I would like to have:

@Controller public class MyController() { @Authenticated @RequestMapping("/myscore") public String myScorePage(ModelMap model) { return "myScorePage"; } @Authenticated @RequestMapping("/anotherPage") public ModelAndView something() { return new ModelAndView("anotherPage",someModelStuff()); } } @Aspect public class NotVeryUsefulAspect { @Around("@annotation(Authenticate)") public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable { if( isAuthenticated() ) { return pjp.proceed(); } else { return /* Oh no what goes here, I want to render a FAILURE page without redirecting */ } } } 
+4
source share
2 answers

Ha, got it!

I decided to use the ProceedingJoinPoint method passed to the method to find out the return type of the original method. Then I made a set of possible โ€œunsuccessfulโ€ results for the aspect method, based on what type of return was passed. For example, if the method originally returned String, I return an "error page", and if the method returns ModelAndView, I return a new ModelAndView ("fail_page").

It works well! Unfortunately, I may not be able to set the model object if it returns a string and does not accept ModelMap as a parameter, but I can handle the fact that the error page is just fine.

0
source

Yes, that means you're right.

  • You need to change your methods so that everyone returns a ModelAndView.
  • Or you need two aspects: one for the return type of ModelAndView and one for String - and then all your controller methods must match

But authorization is already built into Spring Security , and you don't need to implement it yourself.

0
source

All Articles