如何使用 java 在 JSF 页面中登录

How to Login in a JSF page using java

我正在尝试登录 .jsf 内网页面,这是其中的一部分:

1
2
3
4
5
6
     <form method="POST" action="j_security_check" name="loginForm" id="loginForm">
                <input name="j_username" type="text" class="textbox" maxlength="30"/>
                <input name="j_password" type="password" class="textbox" maxlength="30"/>
                <input type=submit value="Enter" class="button">
                <input type=submit value="Exit" class="button">
    </form>

我已经在 java 中搜索并尝试过类似的东西,但没有成功,我得到了与结果相同的页面:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
            HttpPost post = new HttpPost("http://xxxx/login.jsf");  

            List <NameValuePair> parameters = new ArrayList <NameValuePair>();  
            parameters.add(new BasicNameValuePair("j_username","92232776"));  
            parameters.add(new BasicNameValuePair("j_password","(7110oi14)"));

            UrlEncodedFormEntity sendentity;

            sendentity = new UrlEncodedFormEntity(parameters, HTTP.UTF_8);

            post.setEntity(sendentity);    
            HttpClient client = new DefaultHttpClient();  
            HttpResponse response = client.execute(post, httpContext);  

            System.out.print(convertInputStreamToString(response.getEntity().getContent()));

(我正在使用 httpcomponents-client-4.2)

我需要做什么才能登录这个页面?我需要对代码按钮"发送"做些什么吗?

谢谢你们。


登录信息存储在会话中。会话由 cookie 支持。您需要跨请求维护 cookie。基本上,只要 cookie 有效,您就需要在同一会话中的每个后续 HTTP 请求中将检索到的 Set-Cookie 响应标头传回。

在 HttpClient 中,您需要准备一个 CookieStore,您在 HttpContext 中设置它,然后您依次传递每个 HttpClient#execute() 调用。

1
2
3
4
5
6
7
8
9
10
11
HttpClient httpClient = new DefaultHttpClient();
CookieStore cookieStore = new BasicCookieStore();
HttpContext httpContext = new BasicHttpContext();
httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
// ...

HttpResponse response1 = httpClient.execute(method1, httpContext);
// ...

HttpResponse response2 = httpClient.execute(method2, httpContext);
// ...

请注意,此j_security_check 登录步骤与JSF 无关,它也适用于所有其他基于Java Servlet 的登录表单。一旦您打算提交由 <h:form> 创建的真实 JSF 表单,您就需要考虑更多。然后前往这个更详细的答案:我如何以编程方式将文件上传到网站?虽然这处理通过 JSF 表单以编程方式上传文件,但提交 JSF 表单的基本原则是相同的(必须考虑某些隐藏的输入字段等等)。