p10 session共享问题
session:
a. session存储在服务端
b. session是在 同一个用户(客户) 请求时共享
c. 实现机制: 第一次客户请求时, 产生一个sessionID, 并复制给cookie的jessionid,然后发给客户端
session方法:
String getId(): 获取sessionId
boolean isNew(): 判断是否是新用户(第一次访问)
void invalidate(): 使session失效 (退出登录,注销)
setAttribute();
getAttribute();
void setMaxInactiveInterval(秒):设置最大有效 非活动时间
int getMaxInactiveInterval(): 获取最大有效 非活动时间
p11 session 与cookie问题,及application
a.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
out.print(session.getAttribute("uname"));
Cookie[] cookies = request.getCookies();
for(Cookie cookie:cookies){
if(cookie.getName().equals("JSESSIONID")){
System.out.print("JSESSIONID :"+cookie.getValue());
}
}
%>
</body>
</html>
check.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
request.setCharacterEncoding("utf-8");
String name = request.getParameter("uname");
String pwd = request.getParameter("upwd");
if(name.equals("zs") && pwd.equals("abc") ){
//只有登陆成功,session中才会存在uname/upwd
session.setAttribute("uname",name);
session.setAttribute("upwd",pwd);
System.out.println("sessionID"+session.getId());
Cookie cookie = new Cookie("uname",name);
response.addCookie(cookie);
request.getRequestDispatcher("welcome.jsp").forward(request,response);
}else{
//登陆失败
response.sendRedirect("login.jsp");
}
%>
</body>
</html>
invalidate.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
session.invalidate();//session失效
//session.removeAttribute("uname");
response.sendRedirect("login.jsp");
%>
</body>
</html>
login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="check.jsp" method="post">
用户名:<input type="text" name="uname"><br/>
密码:<input type="password" name="upwd"><br/>
<input type="submit" name="登陆"><br/>
</form>
</body>
</html>
welcome.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
欢迎您:
<%
String name = (String) session.getAttribute("uname");
//如果用户没有登陆,而直接采用地址栏登陆welcome.jsp。那么获取到的name必然会是null
//如果没有登陆,那么应该跳转登录页面
if(name != null){
out.print(name);
System.out.println();
%>
<a href="invalidate.jsp">注销</a>
<%
}else{
response.sendRedirect("login.jsp");
}
%>
</body>
</html>
另外,谈一下这个application
<%="当前项目的虚拟路径:"+application.getContextPath()+"<br/>" %>
<%="虚拟路径对应的绝对路径:"+application.getRealPath("MyJspProject")+"<br/>" %>