<form>
将to和其他 HTML 组件更改<h:form>
为 JSF 组件,将它们的值与托管 bean 绑定并让用户提交数据。然后,在您的action
方法中评估数据,然后使用Apache HttpClient之类的库向您想要/需要的 URL 发送 POST 请求。
这可能是一个原始示例(基于您的示例)。
JSF 代码
<h:form >
<h:inputHidden value="#{bean.aField}" />
<h:commandButton value="Submit" action="#{bean.anAction}" />
</h:form>
托管 bean 代码
@ManagedBean
@RequestScoped
public class Bean {
private String aField;
//constructor, getter and setter...
public void anAction() {
//do your form processing...
HttpRequestHandler httpRequestHandler = new HttpRequestHandler();
httpRequestHandler.handlePost(...); //send the arguments here
}
}
public class HttpRequestHandler {
public void handlePost(String ... parameters) {
//you do the Apache HttpClient POST handling here
//always create a class between your application and your third party libraries
//code adapted from HttpClient examples: http://hc.apache.org/httpcomponents-client-ga/examples.html
HttpClient httpclient = new DefaultHttpClient();
try {
HttpPost httpPost = new HttpPost(...);// your URL goes here
//do as you please with the HttpPost request
} finally {
httpclient.getConnectionManager().shutdown();
}
}
}
如果您不想为此作业添加 Apache HttpClient 库,则可以使用本机 Java 类URLConnection
,如下所示:Using java.net.URLConnection to fire and handle HTTP requests