[英]Set custom response in Spring interceptor
Here is my interceptor method where i want to set custom response to tell the UI what happened 这是我的拦截器方法,我想在其中设置自定义响应以告诉UI发生了什么
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
HttpSession session = request.getSession(false);
if (session != null)
return true;
else{
response.sendError(HttpServletResponse.SC_REQUEST_TIMEOUT)
return false;
}
}
And in web.xml 并在web.xml中
<error-page>
<error-code>408</error-code>
<location>/error.html</location>
</error-page>
spring-servlet.xml spring-servlet.xml
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**" />
<mvc:exclude-mapping path="/login" />
<bean class="com.example.CustomInterceptor" />
</mvc:interceptor>
</mvc:interceptors>
When the session is timed out its not sending any response after return false. 当会话超时时,返回false后不发送任何响应。 Even the below is not working 甚至以下都不起作用
response.sendRedirect("http://localhost:8080/home");
You can try very simple thing. 您可以尝试非常简单的事情。 Change your mvc:interceptros
structure to 将您的mvc:interceptros
结构更改为
<mvc:interceptors>
<bean class="com.example.CustomInterceptor" />
</mvc:interceptors>
This essentially mean apply the interceptor to all applicable requests. 这实质上意味着将拦截器应用于所有适用的请求。 I will come in a moment to why I say applicable in a moment. 我将稍后解释为什么我说适用。 If above works then the issue is with your mapping. 如果上述方法可行,则问题出在映射上。
Now as you know interceptors are configured at the level of HandlerMapping
and it will be RequestMappingHandlerMapping
(Spring 3.1+ with mvc:annotation-driven
) or DefaultAnnotationHandlerMapping
in your case. 现在,您知道拦截器是在HandlerMapping
级别配置的,在您的情况下,它将是RequestMappingHandlerMapping
(带有mvc:annotation-driven
Spring 3.1+)或DefaultAnnotationHandlerMapping
。
Now as you have use <mvc:mapping path="/**" />
will map to all requests (including subpaths) as long as they are valid mappings . 现在,只要您使用<mvc:mapping path="/**" />
就会映射到所有请求(包括子路径),只要它们是有效的映射即可 。 So lets say you have controller 假设您有控制器
@RequestMapping(value="/home", method = RequestMethod.GET)
public String welcome() {
return "welcome";
}
you cannot hit http://localhost:8080/yourProjectName/home/test
and expect it to hit the interceptor. 您无法击中http://localhost:8080/yourProjectName/home/test
并期望它击中拦截器。 So you have to hit http://localhost:8080/yourProjectName/home
as that is a valid HandlerMapping. 因此,您必须点击http://localhost:8080/yourProjectName/home
因为这是有效的HandlerMapping。
As to to response first debug if your interceptor is getting hit for any requests. 至于响应第一次调试,如果您的拦截器遇到任何请求。 If it does work then 如果可以的话
response.sendError(HttpServletResponse.SC_REQUEST_TIMEOUT);
should redirect you to error.html
as you have used 应该像以前一样将您重定向到error.html
<error-page>
<error-code>408</error-code>
<location>/error.html</location>
</error-page>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.