JSF 接收 POST 参数 [英] JSF to receive POST parameters
问题描述
今天我使用 servlet 从 HTML 页面接收 POST,然后重定向到我的 JSF 页面.
Today I'm using a servlet to receive a POST from a HTML page and then redirecting to my JSF page.
这是我的实际 Servlet:
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 帖子页面:
<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>
是否可以直接发布到我的 JSF 页面 (ManagedBean)?如何?我想将 Servlet 替换为...更好的东西.
Is it possible to post directly to my JSF page (ManagedBean)? How? I want to replace the Servlet for something... better.
推荐答案
当然可以.无论如何,大多数 JSF 请求都是 POST
s,所以如果您使用 JSF 页面的路径,您打算处理 POST
请求,那么您可以在一个由该页面支持的托管 bean 或获取页面本身内的参数.
Sure you can. Most JSF requests are POST
s 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.
在托管 bean 中:
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");
}
或在托管 bean 中有
OR within the managed bean have
@ManagedProperty(value="#{param.reportKey}")
String reportKey;
//getter and setter of course!
您用 @PostConstruct
注释的方法将在托管 bean 实例化后执行.以上将允许您在托管 bean 中进行访问.
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.
请确保将您的 html 表单 action
属性设置为 JSF 视图的路径.
Just be sure and set your html form action
attribute to the path of the JSF view.
这篇关于JSF 接收 POST 参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!