Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to configure URIEncoding for a certain web application?

If I need to set the same encoding for all applications deployed in a tomcat instance, I can edit server.xml and add a section like this:

<Connector port="8081" protocol="HTTP/1.1" 
   connectionTimeout="20000" 
   redirectPort="8443" 
   URIEncoding="UTF-8"/>

Is there a way to specify encoding for a certain application? (maybe in its web.xml or somewhere else)?

like image 754
Roman Avatar asked Jan 18 '12 11:01

Roman


2 Answers

If you use Spring MVC, you can use CharacterEncodingFilter in web.xml like this:

<filter> 
    <filter-name>encodingFilter</filter-name> 
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> 
    <init-param> 
        <param-name>encoding</param-name> 
        <param-value>UTF-8</param-value> 
    </init-param> 
</filter> 
<filter-mapping> 
    <filter-name>encodingFilter</filter-name> 
    <servlet-name>my-spring-dispatcher-servlet</servlet-name> 
</filter-mapping>

If not, you need to write a filter that does something like:

httpRequest.setCharacterEncoding("UTF-8")

EDIT:

You do need to specify useBodyEncodingForURI="true" in Tomcat 5+ for this filter to be effective:

<Connector port="8081" protocol="HTTP/1.1" 
   connectionTimeout="20000" 
   redirectPort="8443" 
   useBodyEncodingForURI="true" />
like image 119
rustyx Avatar answered Nov 14 '22 16:11

rustyx


As far as I know web.xml does not allow what you want, so I'd suggest the following ways.

  1. set it per page (e.g. for JSP <%@page pageEncoding="UTF-8" %>)
  2. Use HTTP filter to set encoding. In this case you do not have to set it for each page separately.
  3. If you are using web framework try to use tools it provides. For example for Struts you can define encoding in template definition.
like image 2
AlexR Avatar answered Nov 14 '22 16:11

AlexR