我有一个像这样的控制器:
@Controller
@RequestMapping("/page")
public class PageController {
@RequestMapping(value = "", method = RequestMethod.GET)
public String index() {
if (condition) {
return "default_page";
}
// some logic
return "index";
}
@RequestMapping(value = "page2", method = RequestMethod.GET)
public String page2() {
if (condition) {
return "default_page";
}
// some logic
return "page2";
}
@RequestMapping(value = "/page3", method = RequestMethod.GET)
public String page3() {
if (condition) {
return "default_page";
}
// some logic
return "page3";
}
}
正如您所看到的,所有方法都以:
开头if (condition) {
return "default_page";
}
是否有一种简单的方法(没有额外的类或方面)来提取此代码并指示应该为所有方法执行它?
答案 0 :(得分:2)
没有办法做你想用注释做的事情。在控制器方法之前需要一些逻辑。有两种选择:使用方面和使用拦截器。在这种情况下拦截器更合适。这种方法的好处是,控制器的其他方法对condition
一无所知,并且保持简单和干净。如果您决定更改或删除条件,则无需在其他方法中更改任何内容。
在控制器中添加默认方法:
@Controller
@RequestMapping("/page")
public class PageController {
....
@RequestMapping(value = "/defaultPage")
public String defaultPage() {
return "default_page";
}
}
创建新的拦截器类:
public class PageInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse, Object o) throws Exception {
if(condition){
httpServletRequest.getRequestDispatcher("/page/default_page")
.forward(httpServletRequest, httpServletResponse);
}
return true;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse,
Object o, ModelAndView modelAndView) throws Exception {}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse,
Object o, Exception e) throws Exception {}
}
在应用程序配置中注册拦截器。如果使用xml-file config,请添加:
<bean id="pageInterceptor" class="PageInterceptor"/>
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/page" />
<ref bean="pageInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
或者如果您使用基于Java的配置:
@EnableWebMvc
@Configuration
public class AppConfig extends WebMvcConfigurerAdapter{
@Bean
public PageInterceptor pageInterceptor(){
return new PageInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MappedInterceptor(new String[]{"/page"}, pageInterceptor()));
super.addInterceptors(registry);
}
}
注意,有一个到/page
url的映射,因为make拦截器仅适用于PageController
。此外,在少量代码更改后,您可以为其他控制器注册和使用此拦截器。