Spring 春季定制过滤器
我对自己的Spring过滤器进行了编码,以便在UTF-8中对除图像以外的所有响应进行编码:Spring 春季定制过滤器,spring,spring-mvc,filter,Spring,Spring Mvc,Filter,我对自己的Spring过滤器进行了编码,以便在UTF-8中对除图像以外的所有响应进行编码: package my.local.package.filter; public class CharacterEncodingFilter extends org.springframework.web.filter.CharacterEncodingFilter { protected void doFilterInternal(HttpServletRequest request, Htt
package my.local.package.filter;
public class CharacterEncodingFilter extends org.springframework.web.filter.CharacterEncodingFilter
{
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException
{
if(!request.getRequestURI().endsWith("jpg") &&
!request.getRequestURI().endsWith("png") &&
!request.getRequestURI().endsWith("gif") &&
!request.getRequestURI().endsWith("ico"))
{
super.doFilterInternal(request, response, filterChain);
}
filterChain.doFilter(request, response);
}
}
我在web.xml中引用它:
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>my.local.package.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
但是,当请求/images/52x52/1.jpg时,我会得到一个包含以下错误的页面:
java.lang.IllegalStateException:提交响应后无法调用sendError()
我认为我用错误的方式编码了过滤器(我对Spring没有经验),因为如果我在web.xml文件中指定org.springframework.web.filter.CharacterEncodingFilter
,而不是my.local.package.filter.CharacterEncodingFilter
,它就可以完美地工作
有人能帮我吗
谢谢。您正在呼叫
filterChain.doFilter(请求、响应)代码>两次。一次在代码中,一次在super.doFilterInternal中(请求、响应、过滤链)代码>
要解决这个问题,只需将doFilter
放在else
子句的if
中即可
@Controller
public class Avatar
{
@RequestMapping("/images/{width}x{height}/{subject}.jpg")
public void avatar(HttpServletResponse response,
@PathVariable("width") String width,
@PathVariable("height") String height,
@PathVariable("subject") String subject) throws IOException
{
...
// if(error)
// {
response.sendError(HttpServletResponse.SC_NOT_FOUND, "Not found");
return;
// }
...
}
}