spring Aspect return and Controller method return, i don't understand

228 Views Asked by At

1. Controller

@Controller
public class myViewController{
    @RequestMapping("myMainPage") public void myMainPage(Model model){
        model.addAttribute("logoImg", "site_logo.png");
    }
}

2. Aspect

@Around("execution(* com.gas..controller.*Controller.*(..))")
public Object checkAuth(ProceedingJoinPoint joinPoint) throws Throwable{
    // this aspect is check "Auth Level" before view Controller running
    // if "User Auth Level" is lower then return error page(new ModelAndView("error");)
    // ... auth Level check

    Object resultObject = null;
    if (authLevel > 0){
        resultObject = joinPoint.proceed();
    } else {
        // permission denied
        resultObject = new ModelAndView("error");
    } 
}

3. Test

My expectation is that I should see an error page, but... it didn't work(I can see mainPage)
always show mainPage

why is not worked when return type is void?

is works, LOL... but I don't understand difference void and modelAndView

help teach me.

4. Solution

@Controller
public class myViewController{
    @RequestMapping("myMainPage") public ModelAndView myMainPage(Model model){
        model.addAttribute("logoImg", "site_logo.png");
        return new ModelAndView("myMainPage");
    }
}
1

There are 1 best solutions below

0
M. Deinum On

You return void from your controller method, which is something you cannot change with an Aspect. So you cannot suddenly return ModelAndView, as that will be simply ignored (in the end it will still be void aka nothing).

Instead of returning a ModelAndView you could throw an exception which you globally handle instead of returning a dedicated ModelAndView.

That being said I would strongly advice against what you are trying to do here as it seems like you are implementing your own security framework. Use an existing one like Apache Shiro or Spring Security instead.