当前位置:首页 > Web开发 > 正文

name); 23 session.setAttribute("upwd"

2024-03-31 Web开发

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"><br> 暗码:<input 13 type="password"><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>

 

JSP学习-sessionDemo

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/web/30304.html