在Spring中处理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;
}
但这不能按预期工作..因此,如果有人可以帮助,那就太好了:)
问题答案:
我找到了处理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" 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>
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-code>404</error-code>
<location>/WEB-INF/jsp/error.jsp</location>
</error-page>
现在,可以使用此简单的解决方案将所有未映射的请求重定向到404错误到错误页面:)