程序问答   发布时间:2022-06-01  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了在Spring中处理404错误?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决在Spring中处理404错误??

开发过程中遇到在Spring中处理404错误?的问题如何解决?下面主要结合日常开发的经验,给出你关于在Spring中处理404错误?的解决方法建议,希望对你解决在Spring中处理404错误?有所启发或帮助;

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

我将以下代码添加到

<!-- 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" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapPing">
       <property name="mapPings">
        <props>
           <prop key="/**">errorController</prop>
         </props>
       </property>
    </bean>

    <bean ID="errorController" class="com.xyz.controller.ErrorController">

    </bean>

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("/**") 使用 和

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

使用

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

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

还将以下代码添加到您的

  <error-page>
    <error-code>404</error-code>
    <location>/WEB-INF/Jsp/error.Jsp</location>
  </error-page>

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

解决方法

这是我用于将未映射的请求重定向到404页面的代码

@RequestMapping("/**")
    public ModelAndView redirect() {

    ModelAndView mv = new ModelAndView();
    mv.setViewName("errorPage");        
        return mv;
    }

上面的代码可以正常工作,但是问题在于Web资源(例如css和js文件)也位于此重定向方法内,并且未加载任何文件。但是我的调度程序servlet中已经有此代码,但是spring
controller无法识别此资源映射。

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

所以我在请求映射中尝试了一些 正则表达式 来否定资源url像这样

@RequestMapping("/{^(?!.*resources/**)}**")
    public ModelAndView redirect() {

    ModelAndView mv = new ModelAndView();
    mv.setViewName("errorPage");        
        return mv;
    }

但这不能按预期工作..因此,如果有人可以帮助,那就太好了:)

大佬总结

以上是大佬教程为你收集整理的在Spring中处理404错误?全部内容,希望文章能够帮你解决在Spring中处理404错误?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: