应用session对象实现用户登录
session在網羅中被稱為會話,由于HTTP協議是一種無狀態協議,也就是當一個客戶向服務器發出請求時,服務器接受請求并返回響應后,該連接結束,而服務器并不保存相關的信息。所以HTTP提供了session。通過session可以在應用程序的web頁間進行跳轉,并保存用戶的狀態,使會話存在下去,直到關閉瀏覽器。
通過session對象可以存儲或讀取客戶相關的信息,如用戶名,購物信息。這些可以通過session對象的setAttribute()和getAttribute()方法實現
setAttribute()方法
該方法用于將信息保存在session范圍內
session.setAttribute(String name,Object obj)
例如,將用戶名“路明非”保存到session范圍內的username變量中
session.setAttribute(“username”,“路明非”);
getAttribute()方法
該方法用于獲取保存在session范圍內的信息
getAttribute(String name)
例如,讀取保存到session范圍內的username變量的值
session.getAttribute(“username”)
創建index.jsp文件,添加用于收集用戶登錄信息的表單
編寫deal.jsp文件,模擬用戶登錄,如登錄成功,將用戶名保存到session范圍內的變量中,并將頁面重定向到main.jsp頁面,否則,重定向index.jsp頁面,重新登錄
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><%@page import="java.util.*" %> <!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> <% String[][] userList={{"mr","mrsoft"},{"wgh","111"},{"zj","loe"}}; //定義一個保存用戶列表的二維數組 boolean flag=false; //登錄狀態 request.setCharacterEncoding("UTF-8"); //設置編碼 String username=request.getParameter("name"); //獲取用戶名 String password=request.getParameter("pwd"); //獲取密碼 for(int i=0;i<userList.length;i++){ //遍歷二維數組if(userList[i][0].equals(username)){ //判斷用戶名if(userList[i][1].equals(password)){ //判斷密碼flag=true; //登錄成功break; //跳出循環}} } if(flag){ //如果值為true,表示登錄成功session.setAttribute("username",username); //保存用戶名到session范圍的變量中response.sendRedirect("main.jsp"); //跳轉到主頁 }else{ response.sendRedirect("index.jsp"); //跳轉到用戶登錄頁面 } %> </body> </html>編寫main.jsp文件,首先獲取并顯示保存到session范圍內的變量,然后添加一個退出超鏈接
<%@ 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> <% String username=(String)session.getAttribute("username"); //獲取保存在session范圍內的用戶名 %> 您好!<%=username %>歡迎訪問!!!<br> <a href="exit.jsp">[退出]</a> </body> </html>編寫exit.jsp文件,銷毀session,并重定向頁面到index.jsp頁面
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><%session.invalidate(); //銷毀sessionresponse.sendRedirect("index.jsp"); //重定向頁面到index.jsp%> <!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></body> </html>總結
以上是生活随笔為你收集整理的应用session对象实现用户登录的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 统计用户在某一页停留的时间
- 下一篇: 判断用户是否在线