merveotesi
merveotesi

Reputation: 2183

URL encoding and JSF REDIRECT

I must have utf-8 characters in url.

For example there is a string that is to be put in url:

"Hayranlık"

I thought to encode it:

try{
        selected=URLEncoder.encode(selected,"UTF-8");
    }catch(Exception e){
        e.printStackTrace();
    }
    try {
        FacesContext.getCurrentInstance().getExternalContext().redirect("http://" + serverUrl +"/myjsfpage.jsf?param=" + selected );
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();

    }

I debug it and I see an expected string : Hayranl%C4%B1k%24

In another controller, I must handle it, so I get the url by

HttpServletRequest req = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();

        String selected = (String)req.getParameter("param");

        if(selected ==null){
            //show no result message
            return;
        }

After that i try to decode it, but "before" decoding, my string that I get from url is something like "Hayranlık$".

try{
        selected=URLDecoder.decode(selected,"UTF-8");
    }catch(Exception e){
        e.printStackTrace();
    }

Does JSF redirection cause the problem, or is the browser URL handling the problem?

Upvotes: 0

Views: 4679

Answers (1)

BalusC
BalusC

Reputation: 1108752

It's the servletcontainer itself who decodes HTTP request parameters. You don't and shouldn't need URLDecoder for this. The character encoding used for HTTP request parameter decoding needs for GET requests to be configured in the servletcontainer configuration.

It's unclear which one you're using, but based on your question history, it's Tomcat. In that case, you need to set the URIEncoding attribute of <Connector> element in Tomcat's /conf/server.xml to UTF-8.

<Connector ... URIEncoding="UTF-8">

See also:


Unrelated to the concrete problem, the way how you pulled the request parameter in JSF is somewhat clumsy. The following is simpler and doesn't introduce a Servlet API dependency in your JSF managed bean:

String selected = externalContext.getRequestParameterMap().get("param");

Or, if you're in a request scoped bean, just inject it by @ManagedProperty.

@ManagedProperty("#{param.param}")
private String param;

(note that #{param} is an implicit EL object referring the request parameter map and that #{param.param} merely returns map.get("param"); you might want to change the parameter name to make it more clear, e.g. "?selected=" + selected and then #{param.selected})

Or if you're in a view scoped bean, just set it by <f:viewParam>.

<f:viewParam name="param" value="#{bean.param}" />

See also:

Upvotes: 3

Related Questions