how to redirect to a Servlet from a commandButton in xhtml

12,678

First of all, the navigation rule is for JSF only. They can't help you to navigate to a servlet.

The navigation rules in faces-config are redundant in JSF2.0. They are implicitly handled by JSF, based on the value (outcome) returned by an action method. "?faces-redirect=true" can be attached to the end of the outcome for redirection.

I don't know what your functional requirement is. You are trying to mix JSF and servelts, which is not a very good idea.

<h:commandButton id="reportButton"  action="reportPdf"

The value of the action attribute must be a method expression that resolves to a method in some JSF managed bean. e.g. action="#{controllerBean.axnMethod()}".

When the axnMethod() is called, one option is to redirect from there to the servlet. The is something as follows:

FacesContext.getCurrentInstance().getExternalContext().redirect("url");

Or, requirement is just to invoke the servlet then on the view, just put a link with the url that invokes the servlet.

Share:
12,678
Myy
Author by

Myy

I'm a Software developer that is barely scratching the surface of the Programing environment. I'm a very nice person and expect the same respect and niceness towards me. I'm mostly posting questions on here, but hopefuly one day I can help more people, just like the people here are helping me out. =)

Updated on June 29, 2022

Comments

  • Myy
    Myy almost 2 years

    I've been having this trouble for a couple of days. hopefully this is cleaner and someone who's done this before can help me out!

    I'm building a webApp with JSF 2.0 in Eclipse running on a tomcat 7.0 server. and have made a servlet I want to go to, but I don't know how to thandle the navigation rules to take me there:

    In my project the path is src/com/servlets/PdfServlet so when I run the project on the server this servlet can be accessed through the url localhost:8080/miloWeb/PdfServlet. the servlet actualy creates a Pdf file for me and displays it.

    anyway my xhtml has this:

    <h:commandButton id="reportButton"  action="reportPdf" styleClass="button" value="get Report" ></h:commandButton>
    

    my faces-config navigation rules look like this:

    <navigation-rule>
        <navigation-case>
            <from-outcome>reportPdf</from-outcome>      
            <to-view-id>/miloWeb/PdfServlet</to-view-id>
            <redirect />
        </navigation-case>
    </navigation-rule>
    

    but it takes me to miloWeb/faces/miloWeb/PdfServlet, and I need it to take me to miloWeb/PdfServlet.

    Any ideas on how to accomplish this, or another route or doing this ?