Search code examples
jsfservletsprettyfaces

Redirect/Forward from a servlet with PrettyFaces


i am using PrettyFaces 3.3.0 and i want to make custom redirect and forward from a servlet

i found the following code on their documentation:

public class CustomRedirector 
{
    public void redirect(HttpServletRequest request, HttpServletResponse response, 
                            String mappingId, Map<String, String[]>params)
    {
        PrettyContext context = PrettyContext.getCurrentInstance(request);
        PrettyURLBuilder builder = new PrettyURLBuilder();

        URLMapping mapping = context.getConfig().getMappingById(mappingId);
        String targetURL = builder.build(mapping, params);

        targetURL = response.encodeRedirectURL(targetURL);
        response.sendRedirect(targetURL);
    }       
}

and i was wondering how to call the redirect method from the servlet, what will be the mappingId (the requestURI ?) and what will be the value of Map<String, String[]>params, i need a small example please of calling above method from a servlet?

and how to do forwarding from servlet with prettyfaces too, please advise.


Solution

  • The "String mappingId" is the ID of the url-mapping in your PrettyFaces configuration. Each url-mapping should have an ID (either in the XML, or the Annotations configuration.)

    The Map params is a list of parameters in name-value pairs that is used to generate the outbound link based on the URL-mapping pattern specified by the id.

    For example:

    <url-mapping id="foo">
        <pattern value="/#{cat}/#{item}" />
        <view-id value="/bar.xhtml" />
    </url-mapping>
    

    So you would call your method like so:

    Map<String, String[]> map = new HashMap<>();
    map.put("cat", "blah");
    map.put("item", "45");
    new CustomRedirector.redirect(request, response, "foo", map);
    

    And you will be redirected to:

    /blah/45