Spring的AOP功能非常强大,它使得向控制器添加有用的注解变得容易。例如,我编写了一个@Authenticated注解,它允许已认证的用户通过控制器方法或重定向到登录页面。很有趣。
然而,Spring的控制器可以返回各种不同的类型。它们可以返回字符串、ModelAndView对象,甚至是void。我的代码库中有使用所有三种类型的方法。然而,我想改变我的@Authenticated注解,以渲染并返回特定的页面,我希望通过返回一个ModelAndView对象来实现这一点。难道唯一的方法是要求所有的控制器方法都返回一个ModelAndView吗?
以下是我想要拥有的控制器示例:
@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 */
}
}
}