When fetching parameter values from a request object, processing must take into account the input form encoding. Therefore, uniform encoding in Web applications is recommended.
Set HTML, JSP, and servlet encoding as shown below.
Web Component | Setting Method | Coding Example |
---|---|---|
HTML | Specify using the meta tag Content-Type (charset) value. | <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" /> |
JSP | In the page directive contentType attribute, specify the HTTP header Content-Type (charset) value. | <%@ page language="java" contentType="text/html; charset= ISO-8859-1"%> |
Servlet | In the HttpServletResponse interface setContentType method, specify the HTTP header Content-Type (charset) value. | res.setContentType("text/html; charset= ISO-8859-1"); |
Point
With JSP, encoding for when the file is saved can be specified separately. Code this specification in the page directive pageEncoding attribute.
The HTML and JSP New wizards provide a method for embedding the encoding when a file is generated. Embedded encoding can be specified in Workspace units. Specify as follows in their respective preference dialog boxes:
HTML: [Web] > [HTML Files]
JSP: [Web] > [JSP Files]
If filtering takes the encoding into account, for example, when the class shown below is created, the filter mapping must be defined in web.xml.
In this example, the encoding is specified in the web.xml initial parameters and can be customized to suit the environment in which this filter class is used. Thus, the initial parameters also need to be defined.
Example of Taking Encoding into Account in a Filter
package filter; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class flt_request implements Filter { private FilterConfig config=null; public void init(FilterConfig conf){ this.config=conf; } public void destroy(){} public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException { request.setCharacterEncoding(config.getInitParameter("encoding")); chain.doFilter(request,response); } } |
Note
The encoding specification in setCharacterEncoding is enabled for the POST method, but is not enabled for the GET method because specification in setCharacterEncoding does not apply for the part of the URL for which the GET method passes the parameters.