第一个页面,填写一个姓名
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'test1.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<form action="session2.jsp">
姓名<input type="text" name="username">
<input type="submit" value="提交">
</form>
</body>
</html>
第二个页面,将第一个页面用户输入的姓名保存到session里面。
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<body>
<%
String name=request.getParameter("username");
session.setAttribute("logname", name);
%>
你的名字"<%=name%>"已经写入session<br>
<a href="check_session.jsp">check</a>
</body>
</html>
第三个页面,如果已经登陆,显示“用户名”已经登陆,如果没有登陆显示没有登陆
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'check_session.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<%
String yourname=(String)session.getAttribute("logname");
if(yourname==null){
%>
您还未登陆
<%}else{ %>
"<%=yourname %>"已经登陆
<%} %>
</body>
</html>
session.setAttribute(“logname”, name);
将name和logname绑定在一起,然后
String yourname=(String)session.getAttribute(“logname”);
就是定义一个字符串,将logname的所绑定的东西赋值给yourname
通常先用setAttribute把信息放入session里面,然后在使用getAttribut通过名字将对象的名字取出
setAttribute(“logname”, name);前面的对象时一个string类型,后面的是object对象。
(String)session.getAttribute(“logname”)取出对象必须进行转换,记得放进去的是什么类型,取出要转换成什么类型
session是一个会话,是跟某一个客户端的交互,和其他的客户端不会产生干扰