Springmvc異常映射2種實現(xiàn)方法
更新時間:2020年05月06日 11:59:24 作者:第十八使徒
這篇文章主要介紹了Springmvc異常映射2種實現(xiàn)方法以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。,需要的朋友可以參考下
請求出現(xiàn) 想要跳轉(zhuǎn)到錯誤頁面
就需要對springmvc進行配置
方法1:基于xml的配置
springmvc.xml配置類
<!--配置基于xml的異常映射-->
<bean id="simpleMappingExceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<!--配置異常和對應(yīng)頁面的映射-->
<property name="exceptionMappings" >
<props>
<prop key="java.lang.Exception">erroe</prop>
</props>
</property>
</bean>
2.方法2:基于@ControllerAdvice
@ControllerAdvice
public class ExceptionResolver {
@ExceptionHandler(value = NullPointerException.class)
public ModelAndView nullPointerExceptionResovler(NullPointerException e, HttpServletRequest request, HttpServletResponse response) throws IOException {
String viewName="erroe";
return commonReslover(viewName,response,request,e);
}
private ModelAndView commonReslover(String viewName,HttpServletResponse response,HttpServletRequest request,Exception e) throws IOException {
boolean judgeResult = CrowdUtil.judgeRequestType(request);
if(judgeResult){
ResultEntity<Object> resultEntity=ResultEntity.failed(e.getMessage());
//轉(zhuǎn)成gson對象
Gson gson=new Gson();
response.getWriter().write(gson.toJson(resultEntity));
return null;
}
ModelAndView modelAndView=new ModelAndView();
modelAndView.addObject("exception",e);
modelAndView.setViewName(viewName);
return modelAndView;
}
}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
SpringBoot整合spring-data-jpa的方法
這篇文章主要介紹了SpringBoot整合spring-data-jpa的方法,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-06-06
java課程設(shè)計做一個多人聊天室(socket+多線程)
這篇文章主要介紹了我的java課程設(shè)計一個多人聊天室(socket+多線程)本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-08-08
IntelliJ?IDEA?2022.2.3最新激活圖文教程(親測有用永久激活)
今天給大家分享一個?IDEA?2022.2.3?的激活破解教程,全文通過文字+圖片的方式講解,手把手教你如何激活破解?IDEA,?只需要幾分鐘即可搞定,對idea2022.2.3激活碼感興趣的朋友跟隨小編一起看看吧2022-11-11

