我正在点击一个网址登录
public void hittingurl(){
String url = "http://test/login.jsp?username=hello&password=12345";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
}
成功点击后登录网址 当我点击另一个网址时
http://test/afterLogin.jsp
由于afterLogin.jsp无法获取,因此无法输出 用户名和密码的会话值 我还在login.jsp页面中的会话中设置了一个变量
session.setAttribute("someparamValue", "value");
有没有办法使用核心java在会话中点击第二个网址 第一个网址? 这样afterLogin.jsp能够获得我拥有的每个会话值 在login.jsp
中
答案 0 :(得分:0)
感谢BalusC指出CookieHandler。我知道使用scriptlet是一种罪过。但是,我将把它们用于这个演示代码。在发件人页面的页面指令中,我关闭了自动会话创建。这样我们就可以使用单个浏览器进行测试。请将这三个JSP放入ROOT的根文件夹(如果您使用的是Tomcat)Web应用程序。否则,您必须手动将上下文路径插入URL。
<%@page import="java.io.*,java.net.*" session="false"%>
<%!
public void jspInit() {
CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
}
public void hittingURL(JspWriter out, String url) throws Exception{
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
int responseCode = con.getResponseCode();
out.print("Sending 'GET' request to URL : " + url + "<br/>");
out.print("Response Code : " + responseCode + "<br/>");
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer responseBuffer = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
responseBuffer.append(inputLine);
}
in.close();
out.print(responseBuffer.toString() + "<br/>");
return;
}
%>
<%
hittingURL(out, "http://localhost:8080/target1.jsp");
hittingURL(out, "http://localhost:8080/target2.jsp");
%>
targer1.jsp
<%
session.setAttribute("someKey", "myValue");
%>
Hi from target1.jsp
someKey = ${someKey}
The session id is ${pageContext.session.id}
target2.jsp
Hi from target2.jsp
someKey = ${someKey}
The session id is ${pageContext.session.id}