Muhammad Hewedy Muhammad Hewedy - 1 year ago 62
Java Question

Does a servlet know the encoding of the sent form that specified using http-equiv?

Does a servlet knows the encoding of the sent form that specified using http-equiv?

When I specify an encoding of a POSTed form using http-equiv like that:

<meta http-equiv='Content-Type' content='text/html; charset=gb2312'/>
<form name="form" method="post" >
<input type="text" name="v_rcvname" value="相宜本草">

And then at the servlet I use the method,
I got
So, Is there a way that I can tell the server that I am encoding the data in some char encoding??

Answer Source

This will indeed return null from most webbrowsers. But usually you can safely assume that the webbrowser has actually used the encoding as specified in the original response header, which is in this case gb2312. A common approach is to create a Filter which checks the request encoding and then uses ServletRequest#setCharacterEncoding() to force the desired value (which you should of course use consistently throughout your webapplication).

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
    if (request.getCharacterEncoding() == null) {
    chain.doFilter(request, response);

Map this Filter on an url-pattern covering all servlet requests, e.g. /*.

If you didn't do this and let it go, then the servletcontainer will use its default encoding to parse the parameters, which is usually ISO-8859-1, which in turn is wrong. Your input of 相宜本草 would end up like ÏàÒ˱¾²Ý.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download