Car*_*pez 21 java spring spring-mvc
如您所知,在XML中,配置它的方法是:
<error-page>
<error-code>404</error-code>
<location>/my-custom-page-not-found.html</location>
</error-page>
Run Code Online (Sandbox Code Playgroud)
但我还没有找到一种方法在Java配置中执行此操作.我尝试的第一种方式是:
@RequestMapping(value = "/**")
public String Error(){
return "error";
}
Run Code Online (Sandbox Code Playgroud)
它似乎工作,但它检索资源有冲突.
有办法吗?
Eug*_*ene 20
在Spring Framework中,有许多处理异常的方法(尤其是404错误).这是一个文档链接.
error-page在web.xml中使用标记,并自定义错误页面.这是一个例子.其次,您可以@ExceptionHandler为所有控制器使用一个,如下所示:
@ControllerAdvice
public class ControllerAdvisor {
@ExceptionHandler(NoHandlerFoundException.class)
public String handle(Exception ex) {
return "404";//this is view name
}
}
Run Code Online (Sandbox Code Playgroud)
为此,请在web.xml 中将throwExceptionIfNoHandlerFound属性设置为true DispatcherServlet:
<init-param>
<param-name>throwExceptionIfNoHandlerFound</param-name>
<param-value>true</param-value>
</init-param>
Run Code Online (Sandbox Code Playgroud)
您还可以将一些对象传递给错误视图,请参阅javadoc.
Chr*_*lph 12
自Spring 4.2 RC3以来最干净的解决方案是createDispatcherServlet在类中使用新的钩子AbstractDispatcherServletInitializer(或间接通过扩展AbstractAnnotationConfigDispatcherServletInitializer),如下所示:
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
/* ... */
@Override
protected DispatcherServlet createDispatcherServlet(WebApplicationContext servletAppContext) {
final DispatcherServlet dispatcherServlet = super.createDispatcherServlet(servletAppContext);
dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);
return dispatcherServlet;
}
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用参考文档中描述的全局@ControllerAdvice(带注释的类@ControllerAdvice).在通知您可以处理与所描述这里.NoHandlerFoundException@ExceptionHandler
这看起来像这样:
@ControllerAdvice
public class NoHandlerFoundControllerAdvice {
@ExceptionHandler(NoHandlerFoundException.class)
public ResponseEntity<String> handleNoHandlerFoundException(NoHandlerFoundException ex) {
// prepare responseEntity
return responseEntity;
}
}
Run Code Online (Sandbox Code Playgroud)
使用doc和覆盖registerDispatcherServlet方法中描述的基于代码的Servlet容器初始化将throwExceptionIfNoHandlerFound属性设置为true:
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { WebConfig.class };
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
@Override
protected void registerDispatcherServlet(ServletContext servletContext) {
String servletName = getServletName();
Assert.hasLength(servletName, "getServletName() may not return empty or null");
WebApplicationContext servletAppContext = createServletApplicationContext();
Assert.notNull(servletAppContext,
"createServletApplicationContext() did not return an application " +
"context for servlet [" + servletName + "]");
DispatcherServlet dispatcherServlet = new DispatcherServlet(servletAppContext);
// throw NoHandlerFoundException to Controller
dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);
ServletRegistration.Dynamic registration = servletContext.addServlet(servletName, dispatcherServlet);
Assert.notNull(registration,
"Failed to register servlet with name '" + servletName + "'." +
"Check if there is another servlet registered under the same name.");
registration.setLoadOnStartup(1);
registration.addMapping(getServletMappings());
registration.setAsyncSupported(isAsyncSupported());
Filter[] filters = getServletFilters();
if (!ObjectUtils.isEmpty(filters)) {
for (Filter filter : filters) {
registerServletFilter(servletContext, filter);
}
}
customizeRegistration(registration);
}
}
Run Code Online (Sandbox Code Playgroud)
然后创建一个异常处理程序
@ControllerAdvice
public class ExceptionHandlerController {
@ExceptionHandler(Exception.class)
public String handleException(Exception e) {
return "404";// view name for 404 error
}
}
Run Code Online (Sandbox Code Playgroud)
不要忘记在Spring配置文件中使用@EnableWebMvc注释:
@Configuration
@EnableWebMvc
@ComponentScan(basePackages= {"org.project.etc"})
public class WebConfig extends WebMvcConfigurerAdapter {
...
}
Run Code Online (Sandbox Code Playgroud)
小智 5
100%免费xml的简单答案:
设置属性 DispatcherServlet
public class SpringMvcInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { RootConfig.class };
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] {AppConfig.class };
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
@Override
protected void customizeRegistration(ServletRegistration.Dynamic registration) {
boolean done = registration.setInitParameter("throwExceptionIfNoHandlerFound", "true"); // -> true
if(!done) throw new RuntimeException();
}
}
Run Code Online (Sandbox Code Playgroud)创建@ControllerAdvice:
@ControllerAdvice
public class AdviceController {
@ExceptionHandler(NoHandlerFoundException.class)
public String handle(Exception ex) {
return "redirect:/404";
}
@RequestMapping(value = {"/404"}, method = RequestMethod.GET)
public String NotFoudPage() {
return "404";
}
}
Run Code Online (Sandbox Code Playgroud)在您的Web配置类中,
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter
Run Code Online (Sandbox Code Playgroud)
声明一个bean如下,
@Bean
public EmbeddedServletContainerCustomizer containerCustomizer() {
return new EmbeddedServletContainerCustomizer() {
@Override
public void customize(ConfigurableEmbeddedServletContainer container)
{
ErrorPage error401Page = new ErrorPage(HttpStatus.UNAUTHORIZED, "/401.html");
ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/404.html");
ErrorPage error500Page = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/500.html");
container.addErrorPages(error401Page,error404Page,error500Page);
}
};
}
Run Code Online (Sandbox Code Playgroud)
将提到的html文件(401.html.etc)添加到/src/main/resources/static/文件夹.
希望这可以帮助
| 归档时间: |
|
| 查看次数: |
37847 次 |
| 最近记录: |