Reputation: 1031
I want to create an abstract controller that will add the additional request mapping basen on actual mappings for the extending controller.
As an example, for the following controller
@Controller
public class MyController extends VariableResolvingController {
@RequestMapping("page.htm")
public void handlerMethod() {
}
}
I want it to extend VariableResolvingController
that will add a mapping to it's resolveContextVariable(...)
method with the "page.htm.context" URI.
public abstract class VariableResolvingController {
public final @ResponseBody Object resolveContextVariable(String variableName) {
return "{}";
}
protected final void registerVariableResolver(String variableName, VariableResolver resolver) {
//...
}
}
This approach adds a possibility to resolve custom variables using eg. AJAX requests in a way almost transparent for a client code.
Do you know any existing solutions that would be appropriate in this case?
Solution: I achieved my goal by writing a custom HandlerMapping implementation (in essence a decorator for RequestMappingHandlerMapping).
Upvotes: 0
Views: 86
Reputation: 11017
One way of doing is add simple Servlet filter to your spring mvc
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);
}
}
add it
public class MyWebInitializer extends
AbstractAnnotationConfigDispatcherServletInitializer {
//...
@Override
protected Filter[] getServletFilters() {
return new Filter[]{new RequestCheckFilter()};
}
}
or in 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>
Upvotes: 2