Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include page encoding to all the jsp page

I have included <%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> in one jsp page and it displayed french characters properly. But i want to include the page encoding to all the jsp pages. In web.xml i 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?

like image 235
Alén Avatar asked Apr 29 '15 13:04

Alén


People also ask

What is <%@ in JSP?

The page directive is used to provide instructions to the container that pertain to the current JSP page. You may code the page directives anywhere in your JSP page. By convention, page directives are coded at the top of the JSP page. Following is the basic syntax of page directive − <%@ page attribute = "value" %>

How to display Error message on same JSP page?

To create a JSP error page, we need to set page directive attribute isErrorPage value to true, then we can access exception jsp implicit object in the JSP and use it to send customized error message to the client.

What is pageEncoding?

The pageEncoding and contentType attributes determine the page character encoding of only the file that physically contains the page directive. A web container raises a translation-time error if an unsupported page encoding is specified.


1 Answers

You could define a new Filter in your web.xml and modify your answers there.

For example, you could 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 a com.example.EncodingFilter class like this :

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
    }
}

You could furthermore add tests around your setCharacterEncoding() call to filter only specific URI or exclude for example a non-HTML jsp or specific parameter, like a JSP outputing PDF if URL paramter format=PDF is provided :

if (!request.getQueryString().contains("format=PDF") {
        response.setCharacterEncoding("utf-8");
}
chain.doFilter(request, response); // pass request to next filter
like image 173
Preuk Avatar answered Nov 04 '22 20:11

Preuk