当前位置: 移动技术网 > IT编程>开发语言>Java > spring boot下 500 404 错误页面处理的方法

spring boot下 500 404 错误页面处理的方法

2019年07月22日  | 移动技术网IT编程  | 我要评论

spring boot 作为微服务的便捷框架,在错误页面处理上也有一些新的处理,不同于之前的spring mvc 500的页面处理是比较简单的,用java config或者xml的形式,定义如下的bean即可

<bean 
 class="org.springframework.web.servlet.handler.simplemappingexceptionresolver"> 
 <property name="exceptionmappings"> 
  <props> 
  <prop key="org.apache.shiro.authz.unauthenticatedexception">pages/403</prop> 
  <prop key="org.apache.shiro.authz.unauthorizedexception">pages/403</prop> 
  <prop key="org.apache.shiro.authc.lockedaccountexception">pages/locked</prop> 
  <prop key="java.lang.throwable">pages/500</prop> 
  </props> 
 </property> 
 </bean>

 404就比较特殊了,有2种方法可以参考:

1. 先设置dispatcherservlet

@bean 
public servletregistrationbean dispatcherregistration(dispatcherservlet dispatcherservlet) { 
  servletregistrationbean registration = new servletregistrationbean( 
      dispatcherservlet); 
  dispatcherservlet.setthrowexceptionifnohandlerfound(true); 
  return registration; 
} 

再增加处理错误页面的handler,加上@controlleradvice 注解

@controlleradvice 
public class globalcontrollerexceptionhandler { 
 public static final string default_error_view = "pages/404"; 
 
  @exceptionhandler(value = nohandlerfoundexception.class) 
  public modelandview defaulterrorhandler(httpservletrequest req, exception e) throws exception { 
    modelandview mav = new modelandview(); 
    mav.addobject("exception", e); 
    mav.addobject("url", req.getrequesturl()); 
    mav.setviewname(default_error_view); 
    return mav; 
  } 
} 

不过上面这种处理方法,会造成对js,css等资源的过滤,最好使用第二种方法

2. 集成errorcontroller

@controller 
public class mainsiteerrorcontroller implements errorcontroller { 
 
 private static final string error_path = "/error"; 
  
 @requestmapping(value=error_path) 
  public string handleerror(){ 
    return "pages/404"; 
  } 
  
 @override 
 public string geterrorpath() { 
 // todo auto-generated method stub 
 return error_path; 
 } 
 
} 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网