开发者

How to submit a form programmatically in Java servlet?

I have a java servlet which get the form request from one webpage in domain A, and it would deal with the form, and would send the result i开发者_Python百科n another form as a request to another webpage in domain B.

I'm wondering how to submit the form programmatically in Java servlet? I tried to use

javax.servlet.RequestDispatcher.forward(request, response)

but it doesn't work because it can only forward to a resource in the same domain.


Try using Apache HttpClient for that

From the tutorial the code looks like:

HttpClient client = new HttpClient();
GetMethod method = new PostMethod(url);
int statusCode = client.executeMethod(method);
... etc 

There are ton's of options to customize it.


Try a javascript auto submit form returned by Servlet on domain A.

Servlet on domain A:

public void doPost(HttpServletRequest req, HttpServletResponse resp) {
  PrintWriter p = resp.getPrintWriter();
  p.print("<form id='f' action=[URL on domain B to login]><input type='secret' name='username' value='" + username+ "'/><input type='secret' name='password' value='" + password + "'/></form>");
  p.print("<script type='text/javascript'>document.getElementById('f').submit()");
}

This will not be the most elegant solution, but if you are looking for something more enterprisy, try SSO solution such as OpenSSO or CAS.


You need to do an auto-post to the new domain. Just forward the request to a JSP like this,

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<body onload="document.forms[0].submit()">
<noscript>
<p>
<strong>Note:</strong> Since your browser does not support JavaScript,
you must press the Continue button once to proceed.
</p>
</noscript>

<jsp:useBean id="myBean" scope="request" class="example.myBean" />

<form action="<jsp:getProperty name="myBean" property="url"/>" method="post">
<div>
<input type="hidden" name="field1" value="<jsp:getProperty name="myBean" property="field1"/>"/>
...
</div>
<noscript>
<div>
<input type="submit" value="Continue"/>
</div>
</noscript>
</form>
</body>
</html>

The "myBean" contains the redirect URL and the field value needs to be posted to the other domain.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜