您好,登錄后才能下訂單哦!
本文小編為大家詳細(xì)介紹“html中獲取session值的方法有哪些”,內(nèi)容詳細(xì),步驟清晰,細(xì)節(jié)處理妥當(dāng),希望這篇“html中獲取session值的方法有哪些”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學(xué)習(xí)新知識吧。
1.首先呢session的key-value都是存在server的,瀏覽器HTML頁面是沒有辦法直接取得session中的值,只有在html里能通過js拿到j(luò)esessionid之類的東西。
1.1、數(shù)據(jù)量如果小,可以考慮放到cookie里,傳到客戶端,html里用js就可以拿到。
1.2、如果數(shù)據(jù)量大,可以考慮單獨(dú)做一個(gè)jsp或servlet,根據(jù)傳來的session的key,返回序列化的session的值,比如json之類的。html里用js通過ajax獲取。這種方式復(fù)雜了點(diǎn),多一次遠(yuǎn)程訪問,但是靈活方便。
如:<input type="text" value='<%#Session["username"]%>'>
2.或者得通過后臺才能獲取,session是存在服務(wù)器端的,如果你用cookie的話,可以通過js獲取。
問題描述:session中保存著UserInfo對象,成功登錄后,在html中顯示“歡迎xxx”
解決方法:通過ajax,json獲取UserInfo數(shù)據(jù),再顯示
1.js
<script type="text/javascript" src="js/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(function() {
$.ajax({
type : "get",
url : "login!getLoginName.action",
dataType : "text",
success : function(result) {
document.getElementsByTagName('b')[0].innerHTML=result;
},
error : function() {
alert("請求失敗");
}
});
});
</script>
2.頁面:
<html>
<head>
<title>管理頁面</title>
</head>
<body>
<table>
<tr>
<td width="74%" height="38" class="admin_txt">管理員:<b></b>您好,感謝登陸使用!</td>
</tr>
</table>
</body>
</html>
3.實(shí)體:UserInfo
public class UserInfo {
private int UserInfoId;
private String userInfoName;
private String UserInfoPsw;
//省略get,set
4.LoginAction中:
public void getLoginName() {
System.out.println("getLoginUser");
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("text/plain;charset=UTF-8");
PrintWriter out;
try {
String userName = ((UserInfo) ActionContext.getContext()
.getSession().get("user")).getUserInfoName();
System.out.println(userName);
out = response.getWriter();
out.print(userName);
out.flush();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
3.用response.sendRedirect("a.html?param=hello");
用下面的JS方法
如:
var v=getUrlParameter('param');
function getUrlParameter( name ){
name = name.replace(/[
]/,"[").replace(/[
]/,"\]");
var regexS = "[\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec(window.parent.location.href );
if( results == null ) return ""; else {
return results[1];
}
}
以上幾種方法在html頁面中取得session中的值.
讀到這里,這篇“html中獲取session值的方法有哪些”文章已經(jīng)介紹完畢,想要掌握這篇文章的知識點(diǎn)還需要大家自己動手實(shí)踐使用過才能領(lǐng)會,如果想了解更多相關(guān)內(nèi)容的文章,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。