Java servlet sendRequest - getParameter encoding Problem

7k views Asked by At

I'm building a web app for my lesson using java servlets. At some point i want to redirect to a jsp page, sending also some info that want to use there (using the GET method). In my servlet i have the following code:

String link = new String("index.jsp?name="+metadata.getName()+"&title="+metadata.getTitle());

response.sendRedirect(response.encodeRedirectURL(link));

In the jsp, I get these parameters using

<%
request.getParameter("name");
request.getParameter("title");
%>

Everything works fine, except when the parameters do not contain only latin characters (in my case they can contain greek characters). For example if name=ΕΡΕΥΝΑΣ i get name=¡¥. How can i fix this encoding problem (setting it to UTF-8)? Isn't encodeRedirectURL() doing this job? Should I also use encodeURL() at some point? I tried the last one but problem still existed.

Thanks in advance :)

4

There are 4 answers

8
BalusC On BEST ANSWER

The HttpServletResponse#encodeRedirectURL() does not URL-encode the URL. It only appends the jsessionid attribute to the URL whenever there's a session and the client has cookies disabled. Admittedly, it's a confusing method name.

You need to encode the request parameters with help of URLEncoder#encode() yourself during composing the URL.

String charset = "UTF-8";
String link = String.format("index.jsp?name=%s&title=%s", 
    URLEncoder.encode(metadata.getName(), charset), 
    URLEncoder.encode(metadata.getTitle(), charset));

response.sendRedirect(response.encodeRedirectURL(link));

And create a filter which is mapped on /* and does basically the following in doFilter() method:

request.setCharacterEncoding("UTF-8");
chain.doFilter(request, response);

And add the following to top of your JSP:

<%@ page pageEncoding="UTF-8" %>

Finally you'll be able to display them as follows:

<p>Name: ${param.name}</p>
<p>Title: ${param.title}</p>

See also:

0
JB Nizet On

You should encode every request parameter with URLEncoder.encode() before putting it into the query string .

The encodeRedirectURL method is only used to include the session ID into the URL if necessary (URL rewriting if no cookie support by the browser)

0
Will On

How about the following instead?

  • Set the name and title as attributes on the request object;
  • Get a request dispatcher for the JSP from the request object or via the servlet context;
  • Use the request dispatcher to forward the request to the JSP;
  • Access these attributes in the request from the JSP.

This saves redirecting the browser from the first servlet to the JSP derived servlet and avoids the whole parameter encoding issue entirely.

Also ensure the JSP page directive sets the content encoding to UTF-8.

1
sstendal On

Use the java.net.URLEncoder to encode each parameter before adding them to the url. Think about it this way: if your name contained a "&", how would you know that this was not a parameter delimiter?