作者joetsai (路人酒菜)
看板java
标题Re: [J2SE] jsp之间有没有办法互相沟通?
时间Sat Jul 28 23:11:43 2012
如果要达成效果 可以用 HttpURLConnection 解
不过这方法很多问题没有考虑 不建议使用~
test1.jsp
<%
String method = request.getParameter("targetMethod");
String param = request.getParameter("param");
if ("setX".equals(method)) {
int intParam = Integer.parseInt(param);
setX(intParam);
}
%>
<%!
int x=1;
public void setX(int x) {
this.x=x;
}
%>
X=<%=x %>
test2.jsp
<%@page import="java.io.InputStreamReader"%>
<%@page import="java.io.BufferedReader"%>
<%@page import="java.io.OutputStreamWriter"%>
<%@page import="java.net.HttpURLConnection"%>
<%@page import="java.net.URL"%>
<%
URL url = new
URL("
http://localhost:8080/Test/test1.jsp?targetMethod=setX¶m=5");
HttpURLConnection URLConn = (HttpURLConnection) url.openConnection();
URLConn.setRequestMethod("GET"); //for HttpUrlConnetion
URLConn.setDoInput(true);
URLConn.setDoOutput(true);
URLConn.setRequestProperty("Content-Type", "test/html");
URLConn.connect();
URLConn.getOutputStream().flush();
OutputStreamWriter wr = new OutputStreamWriter(URLConn.getOutputStream(),
"UTF-8");
BufferedReader in = new BufferedReader(new
InputStreamReader(URLConn.getInputStream(), "UTF-8"));
StringBuffer sbResult = new StringBuffer();
String strTempLine = "";
while ((strTempLine = in.readLine()) != null) {
sbResult.append(strTempLine + "\r\n");
}
in.close();
%>
Done!
Result: <%= sbResult.toString() %>
※ 引述《LaPass (LaPass)》之铭言:
: 如标题
: 在web伺服器运作的时候,jsp会被建立一个实体
: 并一直以这个实体处理各种请求,直到伺服器关闭为止
: 以我对java web的认知是这样....
: 那,在运行的时候,有没有可能取得其他jsp或是servlet的运行实体?
: 例如....
: test1.jsp
: <%!
: int x=1;
: public void setX(int x)
: {
: this.x=x;
: }
: %>
: X=<%=x %>
: test2.jsp
: <%
: //取得test1.jsp的运行实体,并命名为test1
: test1.setX(5);
: %>
: 那麽
: 在tomcat第一次执行test1.jsp时
: 会显示
: X=1
: 但如果执行过test2.jsp後再执行test1.jsp
: 则会显示
: X=5
: 我知道用application可以解决我上面问的问题
: 但我在考虑的是另一种状况
: 例如在test1.jsp有个物件,甚至是执行绪专门在处理某些事
: 在test2.jsp动用那些部份的东西时,可以去呼叫test1.jsp中的物件(或执行绪)去处理
: 之类的
: 请问有办法吗?
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 111.184.28.119
※ 编辑: joetsai 来自: 111.184.28.119 (07/28 23:15)
※ 编辑: joetsai 来自: 111.184.28.119 (07/28 23:16)
1F:推 LaPass:囧..... 07/29 00:11
2F:→ joetsai:这个做法果然很虾.... 07/29 00:28
3F:→ lovdkkkk:直接把 x 放 session scope 呢? 07/29 03:08
4F:推 iFEELing:直接用HTMLUNIT抓吧? 07/29 07:28