Proper way to call servlet from Facelets?

余生颓废 提交于 2020-01-01 11:48:21

问题


What is the proper way to call a servlet from a facelets file using a form with submit button? Is there a particular form required?


回答1:


Just use a plain HTML <form> instead of a JSF <h:form>. The JSF <h:form> sends by default a POST request to the URL of the current view ID and invokes by default the FacesServlet. It does not allow you to change the form action URL or method. A plain HTML <form> allows you to specify a different URL and, if necessary, also the method.

The following kickoff example sends a search request to Google:

<form action="http://google.com/search">
    <input type="text" name="q" />
    <input type="submit" />
</form>

Note that you do not need to use JSF components for the inputs/buttons as well. It is possible to use <h:inputText> and so on, but the values won't be set in the associated backing bean. The JSF component overhead is then unnecessary.

When you want, for example, to send a POST request to a servlet which is mapped to a URL pattern of /foo/* and you need to send a request parameter with the name bar, then you need to create the form as follows:

<form action="#{request.contextPath}/foo" method="post">
    <input type="text" name="bar" />
    <input type="submit" />
</form>

This way the servlet's doPost() method will be invoked:

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String bar = request.getParameter("bar");
    // ...
}



回答2:


You can call in below way from jsf:

        <h:outputText value="Download" />
        <h:outputLink value="#{request.contextPath}/files" id="btnDownload1" styleClass="redButton">
        <h:outputText value="FILESDOWNLOAD" />
        </h:outputLink>
    </h:panelGrid>

Then in web.xml:

<servlet>
  <servlet-name>files</servlet-name>
  <servlet-class>com.Download</servlet-class>



来源:https://stackoverflow.com/questions/10175963/proper-way-to-call-servlet-from-facelets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!