session共享问题
session存在服务端
session在同一个客户请求时共享(即第二次第三次第n次访问都可以使用)
login.jsp
<%@page import="org.apache.tomcat.util.http.Cookies"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="check.jsp" method="post">
<!--默认是get提交方式,method="get"-->
用户名:<input type="text" name="uname"><br>
密码:<input type="password" name="upwd"><br>
<input type="submit" value="登陆">
</form>
</body>
</html>
check.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; 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("abc") && pwd.equals("abc")){
session.setAttribute("uname", name);
session.setAttribute("upwd", pwd);
session.setMaxInactiveInterval(10);
request.getRequestDispatcher("welcome.jsp").forward(request, response);
}else{
response.sendRedirect("login.jsp");
}
%>
</body>
</html>
welcome.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
welcome:
<%
String name=(String)session.getAttribute("uname");
//如果用户没有登陆,而是直接通过地址直接访问welcome.jsp也能访问,
//但是得到的uname是null,因此这里需要加一个是否登陆的判断
if(name!=null){
out.print(name);
}else{
response.sendRedirect("login.jsp");
}
%>
</body>
</html>