一个简单的Demo:
一个登陆页面login.jsp,跳转到check.jsp,登陆成功就跳转到welcome.jsp,失败就跳转回login.jsp
并且非活动时间大于10秒也自动跳转回login.jsp
login.jsp
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta charset="UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <form action="check.jsp" method="post"> 11 <!-- 登录后去哪里校验 --> 12 用户名:<input type="text" name="uname"><br> 密码:<input 13 type="password" name="upwd"><br> 提交:<input type="submit" 14 value="登录"><br> 15 </form> 16 </body> 17 </html>
check.jsp
1 <%@ page language="java" contentType="text/html; charset=UTF-8"
2 pageEncoding="UTF-8"%>
3 <!DOCTYPE html>
4 <html>
5 <head>
6 <meta charset="UTF-8">
7 <title>Insert title here</title>
8 </head>
9 <body>
10 <%
11 request.setCharacterEncoding("UTF-8"); //为了保险加上这句
12 //以下两句只能同一次request请求才有效
13 //假如你用 zs/abc 通过login.jsp登录一次【跳转到check.jsp】
14 //再在浏览器地址栏直接回车【再次访问check.jsp】【发出新的request请求】
15 //就不能通过request拿到用户数据了【仅同一次request请求可以拿到数据】
16
17 //但是通过F5刷新,浏览器会重复login.jsp中的行为【相当于你重新输入了 zs/abc】
18 String name = request.getParameter("uname");
19 String pwd = request.getParameter("upwd");
20 if (name.equals("zs") && pwd.equals("abc")) { //假设 zs abc
21 //设置为:只有登陆成功,session中才会有 [uname---upwd]
22 session.setAttribute("uname", name);
23 session.setAttribute("upwd", pwd);
24 //设置最大有效非活动时间【如果登录成功后不动网页,这段时间过后再次刷新welcome.jsp就会登陆失败,跳转到login.jsp重新登录】
25 session.setMaxInactiveInterval(10);
26 //并且跳转到一个欢迎页面
27 request.getRequestDispatcher("welcome.jsp").forward(request, response);
28
29 } else {
30 //登录失败,应该重新登录
31 response.sendRedirect("login.jsp");
32 }
33 %>
34 </body>
35 </html>
welcome.jsp
1 <%@ page language="java" contentType="text/html; charset=UTF-8"
2 pageEncoding="UTF-8"%>
3 <!DOCTYPE html>
4 <html>
5 <head>
6 <meta charset="UTF-8">
7 <title>Insert title here</title>
8 </head>
9 <body>
10
11 欢迎您!
12 <br>
13 <%
14 //通过session拿到用户数据【check.jsp中已经把用户数据写入session中】【没必要通过request.getParameter()来拿】
15 String name = (String) session.getAttribute("uname");
16 //如果用户没有登录,直接通过地址栏访问welcome.jsp,则获取的name必然是NULL
17 //所以如果没有登录,就应该跳转登录页面login.jsp
18 if (name != null) {
19 out.print(name);
20 } else {
21 response.sendRedirect("login.jsp");
22 }
23 %>
24 </body>
25 </html>


来源:https://www.cnblogs.com/gilgamesh-hjb/p/12283939.html