JSF to receive POST parameters

天大地大妈咪最大 提交于 2019-12-17 19:16:50

问题


Today I'm using a servlet to receive a POST from a HTML page and then redirecting to my JSF page.

This is my actual Servlet:

   public class CommInServlet extends HttpServlet {

   private String reportKey;

      protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
         req.getSession(true).setAttribute("reportKey", req.getParameter("reportkey"));
         req.getRequestDispatcher("main.xhtml").forward(req, resp);
       }

    }

HTML post page:

<html>
<head />
<body>
<form action="Filtro" method="post">
<input type="text" size="120" name="reportkey" value="XXXXXXXXXXXX" />
<input type="submit" value="doPost" />
</form>
</body>
</html>

Is it possible to post directly to my JSF page (ManagedBean)? How? I want to replace the Servlet for something... better.


回答1:


Sure you can. Most JSF requests are POSTs anyway, so if you use the path to the JSF page you're intending to handle the POST request, you can then get the parameter within a managed bean that is backed by that page OR get the parameter within the page itself.

Within a managed bean:

     @PostConstruct
      public void initMyBean(){
      /**This map contains all the params you submitted from the html form */
      Map<String,String> requestParams = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
      requestParams.get("reportKey");
                       }

OR within the managed bean have

     @ManagedProperty(value="#{param.reportKey}")
     String reportKey;
     //getter and setter of course!

The method you've annotated with @PostConstruct will be executed after the managed bean has been instantiated. The above will give you access within your managed bean.

If you need the value within your page first however, you can have this in your page (preferably at the top)

     <f:metadata>
      <f:viewParam name="reportKey" value="#{backingBean.reportKey}" required="true"/>
     </f:metadata>

Notice how you can perform validations on the parameter from within your view. Pretty cool feature.

Just be sure and set your html form action attribute to the path of the JSF view.



来源:https://stackoverflow.com/questions/12750794/jsf-to-receive-post-parameters

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