How to enable page encoding on the whole jsp page
I included <%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> on one jsp page and correctly displayed French characters. But I want to enable page encoding on all jsp pages. In web.xml I have included
<jsp-config> <jsp-property-group> <url-pattern>*.jsp</url-pattern> <page-encoding>UTF-8</page-encoding> </jsp-property-group> </jsp-config> but it will work for tomcat7, I am using tomcat6.
Is there any other solution for this?
You can define a new filter in your web.xml and change your answers there.
For example, you can put this in your web.xml:
<filter> <filter-name>encoding</filter-name> <filter-class>com.example.EncodingFilter</filter-class> </filter> <filter-mapping> <filter-name>encoding</filter-name> <url-pattern>/*.jsp</url-pattern> <!-- or any pattern you like to excluse non-jsp resources --> </filter-mapping> And create the class com.example.EncodingFilter as follows:
public class EncodingFilter implements javax.servlet.Filter { // init, destroy, etc. implementation public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { response.setCharacterEncoding("utf-8"); chain.doFilter(request, response); // pass request to next filter } } Alternatively, you could add tests around your setCharacterEncoding() call to filter only a specific URI or exception, such as non-HTML jsp or a specific parameter, such as PDF JSP output if the URL format=PDF parameter is specified:
if (!request.getQueryString().contains("format=PDF") { response.setCharacterEncoding("utf-8"); } chain.doFilter(request, response); // pass request to next filter If your settings are not UTF-8 encoded when using Tomcat, try configuring the connector in Tomcat server.xml as follows:<Connector port="8080" maxHttpHeaderSize="8192" maxThreads="150" minSpareThreads="25" maxSpareThreads="75" enableLookups="false" redirectPort="8443" acceptCount="100" connectionTimeout="20000" disableUploadTimeout="true" URIEncoding="UTF-8" />
Another way to apply encoding to all pages is to use a filter.
public void doFilter(ServletRequest request,ServletResponse response, FilterChain filterChain) throws IOException, ServletException { request.setCharacterEncoding(encoding); // response.setContentType("text/html;charset=UTF-8"); response.setCharacterEncoding(encoding); filterChain.doFilter(request, response); } public void init(FilterConfig filterConfig) throws ServletException { String encodingParam = filterConfig.getInitParameter("encoding"); if (encodingParam != null) { encoding = encodingParam; } } Register this filter in web.xml