栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在Spring中处理404错误?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在Spring中处理404错误?

我找到了处理404(未映射链接)的解决方案,我使用了SimpleUrlHandlerMapping来做到这一点。

我将以下代码添加到 调度程序servlet .xml中

<!-- Here all your resources like css,js will be mapped first -->    <mvc:resources mapping="/resources/**" location="/WEB-INF/web-resources/" />     <context:annotation-config /><!-- Next is your request mappings from controllers -->    <context:component-scan base-package="com.xyz" />     <mvc:annotation-driven /><!-- Atlast your error mapping -->    <bean id="errorUrlBean" >       <property name="mappings">        <props><prop key="/**">errorController</prop>         </props>       </property>    </bean>    <bean id="errorController" >    </bean>

com.xyz.controller.ErrorController类

public class ErrorController extends AbstractController  {    @Override    protected ModelAndView handleRequestInternal(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception {        // TODO Auto-generated method stub        ModelAndView mv = new ModelAndView();        mv.setViewName("errorPage");     return mv;    }}

我发现以下原因

@RequestMapping("/**")
使用 RequestHandlerMapping

<mvc:resources mapping="/resources/**" location="/WEB-INF/web-resources/" />

使用 SimpleUrlHandlerMapping

RequestHandlerMapping优先于SimpleUrlHandlerMapping,因此在我的情况下,这就是所有资源请求都进入重定向方法的原因。

因此

@RequestMapping("/**")
,通过将其配置为如上在我的dipatcher
servlet中指定的bean并最后将其映射,我将请求更改为SimpleUrlHandlerMapping。

还将以下代码添加到您的 web.xml中

  <error-page>    <error-pre>404</error-pre>    <location>/WEB-INF/jsp/error.jsp</location>  </error-page>

现在,可以使用此简单的解决方案将所有未映射的请求重定向到404错误到错误页面:)



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/417143.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号