I coded my own Spring filter in order to encode in UTF-8 all the responses except for images:
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);
}
}
I’m referencing it in the 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>
Everything works as expected, jpg/png/gif/ico files are not encoded in UTF-8 while all the other files are.
I’m now trying to code a simple controller which has to return a 404 error under certain conditions:
@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;
// }
...
}
}
But when requesting, for example, /images/52×52/1.jpg i get a page containing this error:
java.lang.IllegalStateException: Cannot call sendError() after the response has been committed
I think I coded the filter in a wrong way (I’m not experienced with Spring), because if I specify org.springframework.web.filter.CharacterEncodingFilter instead of my.local.package.filter.CharacterEncodingFilter in the web.xml file, it works perfectly.
Can someone help me?
Thank you.
You are calling
filterChain.doFilter(request, response);twice. Once in your code and once insuper.doFilterInternal(request, response, filterChain);To fix this, simply put your
doFilterin theelseclause to yourif.