Saturday, January 18, 2014

JSF 2.x Tip of the Day: Redirecting to the context path with parameters

This is just a quick code example that demonstrates how to do a redirect to the Servlet context path with parameters.

1
2
3
4
5
6
7
public String redirect(Map<String, List<string>> parameters) throws IOException {
    FacesContext fc = FacesContext.getCurrentInstance();
    ExternalContext ec = fc.getExternalContext();
    ec.redirect(ec.encodeRedirectURL(ec.getRequestContextPath(), parameters));
    fc.responseComplete();
    return null;
}
The code above will correctly format parameters to be passed as part of the redirection.

Here is an example using bogus parameters.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public Map<String, List<string>> getParameters() {
    Map<String, List<string>> map = new HashMap<>();
 
    map.put("Alpha", new ArrayList<string>() {
        {
            add("A");
        }
    });
 
    map.put("Beta", new ArrayList<string>() {
        {
            add("B");
        }
    });
    map.put("Gamma", new ArrayList<string>() {
        {
            add("G");
        }
    });
    map.put("Delta", new ArrayList<string>() {
        {
            add("D");
        }
    });
    map.put("Epsilon", new ArrayList<string>() {
        {
            add("E");
        }
    });
 
    return map;
}


Here is the JSF Form I used to generate the output below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
      xmlns:h="http://xmlns.jcp.org/jsf/html">
    <h:head>
        <title>Redirect</title>
    </h:head>
    <h:body>
        <h1>Redirect</h1>
        <h:form>
            <h:commandButton action="#{utils.redirect(utils.parameters)}" value="Redirect with Parameters"/>
        </h:form>
    </h:body>
</html>

0 comments :

Popular Posts