JSP+Servlet實現使用者登入狀態的儲存
阿新 • • 發佈:2019-02-01
題目:編寫一個使用者登入頁面(如果是ip地址為“192”開頭的客戶訪問,則在頁面顯示該使用者的ip地址),輸入賬號和密碼,讓使用者選擇“是否儲存登入狀態”,如果賬號密碼相等,則登陸成功,進入歡迎頁面。
在登入時,如果儲存了登入狀態,下次登入時,如果訪問登入頁面,則進入歡迎頁面。但是,客戶如果沒有經過登入就訪問歡迎頁面,則跳轉到登入頁面。
以下為思路分析,其中,前端用Bootstrap框架實現,後臺基於JSP+Servlet+Mysql實現。程式碼下載(網盤,永久有效):http://pan.baidu.com/s/1bo9qwIb,後臺資料庫需自己建立和修改。
頁面展示及資料庫設計如下:
登陸成功顯示:
工程檔案主目錄:
資料庫設計:
思路分析:
1.當訪客訪問登陸頁面welcome.jsp,先判斷是否存在儲存的cookie,如果是則跳轉到歡迎頁面bootstrap.jsp,如果不存在cookie則輸入登陸資訊;以下為登陸頁面程式碼:welcome.jsp
<%@page language="java"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html >
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- 引入 Bootstrap -->
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<title>歡迎登入</title>
</head>
<body>
<%
//首先進入登陸頁面先判斷是否存在cookie,如果是跳轉到歡迎介面
Cookie[] cookies=request .getCookies();
if(cookies!=null){
for(int i=0;i<cookies.length;i++) {
if(cookies[i].getName().equals("name")){
//如果cookie與儲存的相等,即找到cookie
response.sendRedirect("bootstrap.jsp");
}
}
}
%>
<br><br><br><br><br>
<div class="jumbotron">
<div class="container">
<form action="servlet/servlet_login" method="post" class="form-horizontal" role="form"><br><br>
<div class="form-group">
<label class="col-sm-2 col-md-offset-4 control-label" ><span class="glyphicon glyphicon-user"></span>資料庫賬戶:</label>
<div class="col-sm-6">
<input type="text" class="form-control" style="width:30%" name="name" value="" placeholder="請輸入賬戶名"><br><br>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 col-md-offset-4 control-label"><span class="glyphicon glyphicon-ok-circle"></span>資料庫密碼:</label>
<div class="col-sm-6">
<input type="text" class="form-control" style="width:30%" name="password" value="" placeholder="請輸入密碼"><br><br>
</div>
<!--打勾-->
<div class="checkbox col-sm-2 col-md-offset-6">
<label>
<input type="checkbox" name="save">儲存密碼
</label>
</div>
</div>
<input type="submit" class="col-sm-1 col-md-offset-5 btn btn-primary" value="登陸">
<input type="reset" class="col-sm-1 col-md-offset-1 btn btn-primary" value="重置">
</form>
<%!public String getIpAddr(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
if(ip.startsWith("192")){}
else{ip="";}
return ip;
}%>
<label class="col-sm-4 col-md-offset-5 control-label">
<span class="glyphicon glyphicon-ok-circle" style="color: rgb(255, 0, 28); font-size: 14px;">你的IP地址為:</span>
<%=getIpAddr(request)%></label>;
</div>
</div>
</body>
</html>
2.當用戶輸入登陸使用者名稱及密碼時,提交到後臺的servlet_login,servlet此時從web.xml中讀取資料庫使用者名稱及密碼進入資料庫,從中查詢使用者名稱及密碼是否正確,如果正確則判斷使用者是否勾選了儲存密碼;
3.如果使用者勾選了儲存密碼,則設定cookie存活時間為1天(60*60*24),如果沒有勾選儲存密碼的話就設定cookie存活時間為19s(為了便於驗證,當然也可以設定更久);以下為servlet_login程式碼:servlet_login.java
package servlet;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class servlet_login
*/
@WebServlet("/servlet_login")
public class servlet_login extends HttpServlet {
private static final long serialVersionUID = 1L;
Connection conn = null;
Statement stmt = null;
public void init(ServletConfig config) throws ServletException {
//載入連線資料庫的資訊
//ServletContext application=this.getServletContext();
String driverClass =config.getInitParameter("driverClass");
String url=config.getInitParameter("url");
String username = config.getInitParameter("username");
String password = config.getInitParameter("password");
System.out.println(username+"\n"+password);
//連線資料庫MySQL,進行驗證
try {
Class.forName(driverClass);
conn = DriverManager.getConnection(url,username,password);//得到連線
System.out.println("資料庫連線成功");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}//載入驅動
catch (SQLException e) {
e.printStackTrace();
}
}
/**
* @see HttpServlet#HttpServlet()
*/
public servlet_login() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(request, response);
//response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//先判斷cookie是否存在
Cookie[] cookies=request.getCookies();
if(cookies!=null){
for(int i=0;i<cookies.length;i++) {
if(cookies[i].getName().equals("name")){
//如果cookie與儲存的相等,即找到cookie
response.sendRedirect("/Test666/bootstrap.jsp");break;
}
}
}
System.out.println("即將進行資料庫查詢");
//比較賬號及密碼是否正確
try {
stmt = conn.createStatement();
String name=request.getParameter("name");
String password=request.getParameter("password");
System.out.println(name+" "+password+"\n");
String sql="select * from count where name='"+name+"' and password='"+password+"'";
ResultSet rs=stmt.executeQuery(sql);
if(rs.next()==true) {//存在這個賬戶,密碼
System.out.println("賬戶,密碼正確");
//如果使用者勾選了儲存密碼,則保留使用者登陸資訊,將使用者名稱name存入Cookie
//此處判斷是否勾選儲存密碼
//response.getWriter().append(request.getParameter("save"));
if(request.getParameter("save")!=null) {//如果勾選了儲存密碼
response.getWriter().append(request.getParameter("save"));
Cookie cookie=new Cookie("name",request.getParameter("name"));
cookie.setPath("/");//保證cookie存放的根目錄相同
//設定cookie存活時間為1天
cookie.setMaxAge(60*60*24);
//將cookie儲存在客戶端
response.addCookie(cookie);
}
else {//如果沒有勾選儲存密碼
Cookie cookie=new Cookie("name",request.getParameter("name"));
cookie.setPath("/");//保證cookie存放的根目錄相同
//設定cookie存活時間為19s
cookie.setMaxAge(19);
//將cookie儲存在客戶端
response.addCookie(cookie);
}
//response.getWriter().append("歡迎登陸");
response.sendRedirect("/Test666/bootstrap.jsp");
System.out.println("測試,已跳轉");
return ;
}
else {
System.out.println("賬戶及密碼錯誤");
//如果賬戶,密碼錯誤,則返回登陸介面
response.sendRedirect("/Test666/welcome.jsp");return ;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}//Ending
}
}
4.新增cookie後,重定向到bootstrap.jsp歡迎頁面,在歡迎頁面先判斷cookie是否存在,如果符合則顯示歡迎頁面內容,如果不符合則跳轉到登陸頁面。以下為歡迎頁面程式碼:bootstrap.jsp
<%@ page language="java"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- 引入 Bootstrap -->
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<title>Insert title here</title>
</head>
<body>
<%
Cookie[] cookies=request.getCookies();
boolean flag=false;
if(cookies!=null){
System.out.println("cookie的長度為:"+cookies.length);
for(int i=0;i<cookies.length;i++) {
if(cookies[i].getName().equals("name")){
//如果cookie與儲存的相等,即找到cookie
flag=true;break;
//response.sendRedirect("bootstrap.jsp");
}
}
}
if(flag==false){response.sendRedirect("welcome.jsp");}//如果沒找到cookie,就返回登陸介面
%>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<nav class="navbar navbar-default" role="navigation">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span><span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span></button> <a class="navbar-brand" href="#">導航1</a>
</div>
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li class="active">
<a href="#">導航2</a>
</li>
<li>
<a href="#">導航3</a>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">導航4<strong class="caret"></strong></a>
<ul class="dropdown-menu">
<li>
<a href="#">Action</a>
</li>
<li>
<a href="#">Another action</a>
</li>
<li>
<a href="#">Something else here</a>
</li>
<li class="divider">
</li>
<li>
<a href="#">Separated link</a>
</li>
<li class="divider">
</li>
<li>
<a href="#">One more separated link</a>
</li>
</ul>
</li>
</ul>
<form class="navbar-form navbar-left" role="search">
<div class="form-group">
<input type="text" class="form-control" />
</div> <button type="submit" class="btn btn-default">Submit</button>
</form>
<ul class="nav navbar-nav navbar-right">
<li>
<a href="#"></a>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown<strong class="caret"></strong></a>
<ul class="dropdown-menu">
<li>
<a href="#">Action</a>
</li>
<li>
<a href="#">Another action</a>
</li>
<li>
<a href="#">Something else here</a>
</li>
<li class="divider">
</li>
<li>
<a href="#">Separated link</a>
</li>
</ul>
</li>
</ul>
</div>
</nav>
<div class="jumbotron">
<h1>
歡迎登入!
</h1>
<p>
歡迎來到登入介面!
</p>
<p>
<a class="btn btn-primary btn-large" href="#">Learn more</a>
</p>
</div>
</div>
</div>
</div>
</body>
</html>
5.當然,如果訪客沒經過登陸,直接訪問歡迎頁面bootstrap.jsp也會由於判斷cookie不存在而跳轉到登陸頁面,最後,web.xml設定如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>Test666</display-name>
<servlet>
<servlet-name>servlet_login</servlet-name>
<servlet-class>servlet.servlet_login</servlet-class>
<init-param>
<param-name>driverClass</param-name>
<param-value>com.mysql.jdbc.Driver</param-value>
</init-param>
<init-param>
<param-name>url</param-name>
<param-value>jdbc:mysql://localhost:3306/count?useUnicode=true&characterEncoding=utf-8</param-value>
</init-param>
<init-param>
<param-name>username</param-name>
<param-value>root</param-value>
</init-param>
<init-param>
<param-name>password</param-name>
<param-value>160337</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>servlet_login</servlet-name>
<url-pattern>/servlet/servlet_login</url-pattern>
</servlet-mapping>
<filter>
<filter-name>EncodingFilter</filter-name>
<filter-class>Filter.EncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>EncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>welcome.jsp</welcome-file>
</welcome-file-list>
</web-app>