Java 在Spring中处理404错误?
下面是我将未映射的请求重定向到404页面的代码Java 在Spring中处理404错误?,java,spring,spring-mvc,http-status-code-404,Java,Spring,Spring Mvc,Http Status Code 404,下面是我将未映射的请求重定向到404页面的代码 @RequestMapping("/**") public ModelAndView redirect() { ModelAndView mv = new ModelAndView(); mv.setViewName("errorPage"); return mv; } 上面的代码工作正常,但问题在于css和js文件等web资源 另外,进入这个重定向方法,它不会加载任何文件。但我的
@RequestMapping("/**")
public ModelAndView redirect() {
ModelAndView mv = new ModelAndView();
mv.setViewName("errorPage");
return mv;
}
上面的代码工作正常,但问题在于css和js文件等web资源
另外,进入这个重定向方法,它不会加载任何文件。但我的DispatcherServlet中已经有了这段代码,但SpringController并没有识别出这种资源映射
<mvc:resources mapping="/resources/**" location="/WEB-INF/web-resources/" />
但是,这并没有像预期的那样起作用。因此,如果有人能帮上忙,那就太好了:)我找到了处理404(未映射链接)的解决方案,我使用了SimpleUrlHandlerMapping来实现这一点 我将以下代码添加到我的dispatcher 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" 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>
<error-page>
<error-code>404</error-code>
<location>/WEB-INF/jsp/error.jsp</location>
</error-page>
我发现了以下原因
@RequestMapping(“/**”)使用RequestHandlerMapping和
<mvc:resources mapping="/resources/**" location="/WEB-INF/web-resources/" />
现在,这个简单的解决方案可以用来重定向所有未映射的请求,即)404错误到错误页面:)您正在使事情变得复杂,只需更改URL的处理顺序,/**始终是最后一个。你能添加你的配置吗?是的,我试图使/**成为最后一个,尽管/resources/**转到重定向方法,如前所述,请在问题中添加your配置。你是说dipatcher servlet.xml?web.xml,实际上还有你的servlet.xml。。。
<mvc:resources mapping="/resources/**" location="/WEB-INF/web-resources/" />
<error-page>
<error-code>404</error-code>
<location>/WEB-INF/jsp/error.jsp</location>
</error-page>