以下是我将未映射的请求重定向到404页面的代码
@RequestMapping("/**")
public ModelAndView redirect() {
ModelAndView mv = new ModelAndView();
mv.setViewName("errorPage");
return mv;
}
上面的代码工作正常,但问题在于css和js文件等网络资源 也进入这个重定向方法,它没有加载任何文件。但我已经在我的调度程序servlet中有这个代码,但是spring控制器没有识别这个资源映射。
<mvc:resources mapping="/resources/**" location="/WEB-INF/web-resources/" />
所以我在请求映射中尝试了一些正则表达式来否定资源url这样的事情
@RequestMapping("/{^(?!.*resources/**)}**")
public ModelAndView redirect() {
ModelAndView mv = new ModelAndView();
mv.setViewName("errorPage");
return mv;
}
但这并不像预期的那样有效。所以,如果有人能提供帮助,那就太好了。)
答案 0 :(得分:1)
我找到了处理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,所以这就是我的情况下所有资源请求进入redirect方法的原因。
所以我刚刚将@RequestMapping("/**")
请求更改为SimpleUrlHandlerMapping,方法是将其配置为我的dipatcher servlet中的bean,并将其映射到最后,它解决了问题。
同时将以下代码添加到 web.xml
<error-page>
<error-code>404</error-code>
<location>/WEB-INF/jsp/error.jsp</location>
</error-page>
现在这个简单的解决方案可用于将所有未映射的请求重定向,即404错误到错误页面:)