我正在运行Spring 4.3.7与Spring Security 4.2.2的组合,并使用Java配置进行配置,因此没有web.xml。现在我想获得一个自定义的404页面,如果无法解析页面,那么前面的方法似乎是覆盖了描述here和here的createDispatcherServlet方法。我想使用SimpleMappingExceptionResolver来处理它并返回我的自定义404页面,但抛出异常对我来说甚至都不起作用。我希望下面给出的配置足够了。
MvcWebApplicationInitializer.java
public class MvcWebApplicationInitializer
extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { AppConfig.class };
}
@Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
super.onStartup(servletContext);
FilterRegistration.Dynamic filterRegistration = servletContext.addFilter("resourceUrlEncodingFilter",
new ResourceUrlEncodingFilter());
filterRegistration.setInitParameter("encoding", "UTF-8");
filterRegistration.setInitParameter("forceEncoding", "true");
filterRegistration.addMappingForUrlPatterns(null, true, "/*");
}
@Override
protected DispatcherServlet createDispatcherServlet(WebApplicationContext servletAppContext)
{
DispatcherServlet dispatcherServlet = (DispatcherServlet) super.createDispatcherServlet(servletAppContext);
dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);
return dispatcherServlet;
}
}
AppConfig.java
@EnableWebMvc
@Configuration
@ComponentScan(...)
@EnableTransactionManagement
public class AppConfig extends WebMvcConfigurerAdapter {
@Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver viewResolver
= new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
[...]
}
@Autowired
private RequestMappingHandlerAdapter requestMappingHandlerAdapter;
@PostConstruct
public void init() {
requestMappingHandlerAdapter.setIgnoreDefaultModelOnRedirect(true);
}
@Bean(name = "simpleMappingExceptionResolver")
public SimpleMappingExceptionResolver createSimpleMappingExceptionResolver() {
SimpleMappingExceptionResolver exceptionResolver = new MappingExceptionResolver();
Properties mappings = new Properties();
mappings.setProperty("UserNotAccessibleException", "access");
mappings.setProperty("VersionsModelCreationException", "versions");
exceptionResolver.setExceptionMappings(mappings);
exceptionResolver.setDefaultErrorView("index");
exceptionResolver.setExceptionAttribute("exception");
return exceptionResolver;
}
[...]
}
我仍然只得到一个
WARN in DispatcherServlet.java:noHandlerFound:1172: No mapping found for HTTP request with URI [/root/notexisting] in DispatcherServlet with name 'dispatcher'
而不是我可能使用SimpleMappingExceptionResolver处理的异常。有什么建议吗?