简体   繁体   中英

how to retain utf-8 character encoding in tomcat with GET request

From my JSP, I am sending a GET request with a parameter called jobDetails which contains some Chinese characters [encoded with URLEncoder.encode()]. Now in the doGET() of my servlet, I need to write the data to a file. When I do

request.getParameter("jobDetails"); // this one retrieves wrong characters

There is a solution for this setting the URIEncoding="UTF-8" in

 <Connector port="8009" protocol="AJP/1.3" redirectPort="8443"/>

tag of Tomcat but our architect is hell bend on not to change the existing tomcat settings. I tried with setting a filter for setting the characterEncoding() for request inside doFilter() as mentioned in BalusC's blog . But this one works for POST requests only. Is there any other solution to this other than changing the Tomcat settings? I am using Tomcat 6 and jdk 1.6.

Sorry, you're going to have to tell your architect that sometimes, changing configuration is the only option and this is one of those times. To support UTF-8 characters in URL parameters in Tomcat, you need to add that setting to the connector.

If arguing with the architect doesn't sound like fun (and it doesn't), the parse of URLEncodedUtils should do what you need.

public static void main( String[] args ) {
    List<NameValuePair> foo = null;
    List<String> encodings = Arrays.asList( "ISO-8859-1", "UTF-8" );

    for ( String e : encodings ) {
        System.out.println( String.format( "Interpreting as %s", e ) );
        foo = new ArrayList<NameValuePair>();
        URLEncodedUtils.parse( foo, new Scanner( "jobdetails=%C2%A2" ), e );

        for ( NameValuePair i : foo ) {
            System.out.println( String.format( "%s had value %s", i.getName(), i.getValue() ) );
        }
    }
}

You would still need to get the raw request string to pass to this method, but that shouldn't be too difficult. Since it's URL encoded you shouldn't need to worry about encoding as all non-ASCII characters will have been escaped.

You don't need external libraries. Just use String.getBytes():

String jobDetails = new String(request.getParameter("jobDetails").getBytes("ISO-8859-1"), "UTF-8"));

我找到了某种方式......我从org.springframework.web-3.0.0.RELEASE.jar导入了org.springframework.web.bind.ServletRequestUtils类,并使用以下方法从'request'对象解析参数'jobDetails' :

String jobDetails = new String((ServletRequestUtils.getStringParameter(request, "jobDetails")).getBytes("ISO-8859-1"), "UTF-8");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM