這是講述如何通過DWR使用JAVA的Session的例子,想要通過DWR使用JAVA的Session,如果您還沒有引入DWR的JAR包到工程中,那麼首先引入DWR的JAR包到工程中,隨後就可以使用了.在編寫好正確的JAVA代碼后,應該在dwr.xml發布要使用的JAVA類,隨後重新啟動JAVA伺服器,下面是發布配置:
<!-- DwrSession - DwrSession -->
<create creator="new" javascript="DwrSession">
<param name="class" value="您完整的包名稱.DwrSession"/>
<include method="getSessionId"/>
<include method="setSession"/>
<include method="getSession"/>
</create>
JAVA類的代碼:
import uk.ltd.getahead.dwr.*;
public class DwrSession {
//得到session編號
public String getSessionId() {
WebContext webContext = WebContextFactory.get();
webContext.getSession();
webContext.getHttpServletRequest();
webContext.getHttpServletResponse();
return webContext.getSession().getId();
}
public void setSession(String value,String sessionName){
WebContext webContext = WebContextFactory.get();
//設定session值
webContext.getSession().setAttribute(sessionName, value);
}
public String getSession(String sessionName){
WebContext webContext = WebContextFactory.get();
//返回session值
return (String)webContext.getSession().getAttribute(sessionName);
}
}
JSP頁面代碼:
<%@ page contentType="text/html; charset=utf-8" language="java" import="java.sql.*" errorPage="" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>DWR使用session演示頁面</title>
<script type='text/javascript' src='/您的web工程/dwr/interface/DwrSession.js'></script>
<script type='text/javascript' src='/您的web工程/dwr/engine.js'></script>
<script type='text/javascript' src='/您的web工程/dwr/util.js'></script>
<script language="javascript">
//得到sesion編號
function getSessionId(){
//得到session編號
DwrSession.getSessionId(function getdata(data){
//在頁面顯示session編號
document.getElementById("sessionTd").innerHTML = data;
});
}
//設定session值,並同時顯示設定的session值
function setSession(){
//要設定的值
var temp = document.getElementById("txtSession").value;
//要使用的session名稱
var name = "test";
DwrSession.setSession(temp,name);
//得到設定的session值
DwrSession.getSession(name,function getData(data){
//在頁面顯示session值
document.getElementById("getSessionTd").innerHTML = data;
});
};
</script>
</head>
<body>
<form id="form1" name="form1" method="post" action="">
<table width="100%" border="1">
<tr>
<td><table width="100%" border="1">
<tr>
<td width="30%"><a href="#">getSessionId</a></td>
<td width="70%"><table width="100%" border="1">
<tr>
<td><%
out.println(session.getId());
%>
</td>
</tr>
<tr>
<td id="sessionTd"> </td>
</tr>
</table></td>
</tr>
</table></td>
</tr>
<tr>
<td><table width="100%" border="1">
<tr>
<td width="30%"><input name="txtSession" type="text" id="txtSession" size="15" />
<input type="button" name="Submit" value="設定Session值"/></td>
<td width="70%" id="getSessionTd"> </td>
</tr>
</table></td>
</tr>
</table>
</form>
</body>
</html>
[火星人 ] 通過DWR使用JAVA的Session已經有694次圍觀