session 学习

来源:互联网 发布:2017年10月网络热词 编辑:程序博客网 时间:2024/06/10 15:00

初试session的使用!

依旧非常简单!!以前以为多难呢!!
这里说明网页中使用session 来记录用户ID,完成跟踪的目的。
使用步骤:
jsp页面中加入这样一句:<%@page session="true"%>就启动session 了;
然后就是吧用户输入用session来获得用户输入id ,传递给其他参数,显示出来。

使用示例:

Page1:maillogin.jsp

<%@ page language="java" contentType="text/html; charset=gb2312"
pageEncoding="gb2312"%>
<%@page session="true"%> ------启动session
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>mail login</title>
</head>
<body bgcolor=#ffffff onload="document.loginForm.username.focus()">
<%
String name = "";
if (!session.isNew()) {
name = (String) session.getAttribute("username"); //获得session,传个参数name
if (name == null)
  name = "";
}
%>
<p>欢迎/p>
<p>
session id:
<%=session.getId()%></p> -----返回给session 获得的ID,显示在页面上
<table width=500 border=0 cellspacing=0 cellpadding=0>
<tr>
<td>
<table width=500 border=0 cellspacing=0 cellpadding=0>
<form name=loginForm method=post action=<%=response.encodeURL("mailcheck.jsp")%>>//此处使用保证用户的浏览器设置为不支持cookie是依旧有session 的保留功能
<td width=401><div align=right>User name:&nbsp;</div></td>
<td width=399><input type=text name=username value=<%=name%>> //session 或取的用户的输入,可保留在文本域中,这样起到session 的作用
</td>
<td width=401><div align=right>password:&nbsp;</div> //没有保留哦!
</td>
<td width=399><input type=password name=password>
</td>
<td width=401>&nbsp;</td>
<td width=399><br> <input type=submit name=submit
vaule="提交"></td>
</form>
</table>
</td>
</tr>
</table>
</body>
</html>

page2:mailcheck.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@page session="true" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>mail check</title>
</head>
<body>
<%
String name = null;
name = request.getParameter("username");
if (name != null)
  session.setAttribute("username", name);       //此处获得session 中得username

%>
<a href=<%=response.encodeURL("maillogin.jsp")%>>login</a>&nbsp;&nbsp;&nbsp;
<a href=<%=response.encodeURL("maillogout.jsp")%>>logout</a>&nbsp;&nbsp;&nbsp;
<p>
current user ;<%=name%></p>  ----返回session 中的username
<p>100 mails in your mailbox</p>
</body>
</html>


page3:maillogout.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@page session="true"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>mail logout</title>
</head>
<body>
<%
String name = (String) session.getAttribute("username");
  session.invalidate();  //session 不可用
%>
<%=name%>
bye!
<p>
<p>
<a href=<%=response.encodeURL("maillogin.jsp")%>>login </a>&nbsp;&nbsp;&nbsp;
</body>
</html>

虽然很简单,还是怕忘了,写下来以备以后查阅使用


原创粉丝点击