我想创建一个抽象控制器,它将为扩展控制器的实际映射添加额外的请求映射。
例如,对于以下控制器
@Controller
public class MyController extends VariableResolvingController {
@RequestMapping("page.htm")
public void handlerMethod() {
}
}
我希望它扩展VariableResolvingController
,它将使用“page.htm.context”URI为其resolveContextVariable(...)
方法添加映射。
public abstract class VariableResolvingController {
public final @ResponseBody Object resolveContextVariable(String variableName) {
return "{}";
}
protected final void registerVariableResolver(String variableName, VariableResolver resolver) {
//...
}
}
这种方法增加了使用例如解决自定义变量的可能性。 AJAX请求对客户端代码几乎是透明的。
您知道在这种情况下适合的任何现有解决方案吗?
解决方案:我通过编写自定义HandlerMapping实现(实质上是RequestMappingHandlerMapping的装饰器)实现了我的目标。
答案 0 :(得分:2)
一种方法是在spring mvc中添加简单的Servlet过滤器
public class RequestCheckFilter implements Filter {
@Override
public void destroy() {
// ...
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
//
}
@Override
public void doFilter(ServletRequest request,
ServletResponse response, FilterChain chain)
throws IOException, ServletException {
try {
HttpServletRequest httpServletRequest = ((HttpServletRequest) request);
String requestURI = httpServletRequest.getRequestURI();
if (requestURI.endsWith(".context")) {
request.getRequestDispatcher(requestURI.concat(".htm"))
.forward(request,response);
} else {
chain.doFilter(httpServletRequest, response);
}
} catch (Exception ex) {
request.setAttribute("errorMessage", ex);
request.getRequestDispatcher("/WEB-INF/views/jsp/error.jsp")
.forward(request, response);
}
}
添加
public class MyWebInitializer extends
AbstractAnnotationConfigDispatcherServletInitializer {
//...
@Override
protected Filter[] getServletFilters() {
return new Filter[]{new RequestCheckFilter()};
}
}
或在web.xml中
<filter>
<filter-name>reqHandlerFilter</filter-name>
<filter-class>RequestCheckFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>reqHandlerFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>