JavaWeb練習(xí)之使用filter實現(xiàn)自動登陸

Filter練習(xí)-自動登錄

成都創(chuàng)新互聯(lián)公司憑借在網(wǎng)站建設(shè)、網(wǎng)站推廣領(lǐng)域領(lǐng)先的技術(shù)能力和多年的行業(yè)經(jīng)驗,為客戶提供超值的營銷型網(wǎng)站建設(shè)服務(wù),我們始終認(rèn)為:好的營銷型網(wǎng)站就是好的業(yè)務(wù)員。我們已成功為企業(yè)單位、個人等客戶提供了成都網(wǎng)站制作、成都網(wǎng)站建設(shè)、外貿(mào)營銷網(wǎng)站建設(shè)服務(wù),以良好的商業(yè)信譽,完善的服務(wù)及深厚的技術(shù)力量處于同行領(lǐng)先地位。

本篇來做一個Filter的練習(xí)題,就是網(wǎng)站自動登錄的,這個自動登錄,我們在學(xué)習(xí)cookies的時候做過,這次使用Filter來做一遍。

數(shù)據(jù)庫表準(zhǔn)備

首先,我們需要準(zhǔn)備一個表,用戶表,如果沒有可以參考以下SQL去創(chuàng)建。

CREATE DATABASE javaweb

USE javaweb

CREATE TABLE users(

id INT PRIMARYKEY AUTO_INCREMENT,

username VARCHAR(100),

password VARCHAR(100),

email VARCHAR(150)

)

INSERT INTO USER VALUES(NULL, "tom", "123","tom@163.com")

JavaWeb練習(xí)之使用filter實現(xiàn)自動登陸

創(chuàng)建一個java web項目

拷貝相關(guān)jar和數(shù)據(jù)庫連接配置文件。以下全部文件都可以從前面圖書管理系統(tǒng)中拷貝過來,Dao和Service和servlet代碼我們接下來會重寫寫。

JavaWeb練習(xí)之使用filter實現(xiàn)自動登陸

寫一個用戶登錄的jsp頁面

寫一個登錄的jsp頁面,有用戶名和密碼和登錄,以及自動登錄這個checkbox。

<%@?page?language="java"?contentType="text/html; charset=UTF-8"

? ?pageEncoding="UTF-8"%>

<!DOCTYPE?html?PUBLIC?"-//W3C//DTD HTML 4.01 Transitional//EN"?"https://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta?http-equiv="Content-Type"?content="text/html; charset=ISO-8859-1">

<title>Insert title here</title>

</head>

<body>

????<form?action="">

????????用戶名:<input?type="text"?name="username"?/><br/>

????????密碼:<input?type="password"?name="password"?/><br/>

????????<input?type="checkbox"?name="autoLogin"/>自動登錄<br/>

????????<input?type="submit"?value="登錄"/><br/>

????</form>

</body>

</html>

瀏覽器打開這個login.jsp效果如下

JavaWeb練習(xí)之使用filter實現(xiàn)自動登陸

Dao層代碼

一個接口和一個實現(xiàn)類文件代碼。

package?com.kaigejava.dao;

import?java.sql.SQLException;

import?com.kaigejava.domain.User;

public?interface?UserDao?{? ??

????public?User?findUser(String?username, String?password)?throws?SQLException;

}

具體實現(xiàn)類代碼

package?com.kaigejava.dao;

import?java.sql.SQLException;

import?org.apache.commons.dbutils.QueryRunner;

import?org.apache.commons.dbutils.handlers.BeanHandler;

import?com.kaigejava.datasource.C3P0Utils;

import?com.kaigejava.domain.User;

public?class?UserDaoImpl?implements?UserDao?{

????@Override

????public?User?findUser(String?username, String?password)?throws?SQLException?{

????????QueryRunner?qr?=?new?QueryRunner(C3P0Utils.getDataSource());

????????User?user?=?qr.query("select * from users where username=? and password=?",?new?BeanHandler<User>(User.class),?username,?password);

????????return?user;

????}

}

Service層代碼

一個接口和一個實現(xiàn)類文件代碼。

package?com.kaigejava.service;

import?com.kaigejava.domain.User;

public?interface?UserService?{? ??

????public?User?findUser(String?username, String?password);

}

package com.kaigejava.service;

import java.sql.SQLException;

import com.kaigejava.dao.UserDao;

import com.kaigejava.dao.UserDaoImpl;

import com.kaigejava.domain.User;

public class UserServiceImpl implements UserService {? ??

????// 創(chuàng)建一個Dao層對象

????UserDao ud = new UserDaoImpl();

????@Override

????public User findUser(String username, String password) {

????????try {

????????????return ud.findUser(username, password);

????????} catch (SQLException e) {

????????????e.printStackTrace();

????????}

????????return null;

????}

}

Servlet代碼

新建一個LoginServlet.java的servlet,url映射為/loginServlet

package com.kaigejava.web.servlet;

import java.io.IOException;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import com.kaigejava.domain.User;

import com.kaigejava.service.UserService;

import com.kaigejava.service.UserServiceImpl;

public class LoginServlet extends HttpServlet {

????public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

????????String username = request.getParameter("username");

????????String password = request.getParameter("password");? ? ? ? ? ? ? UserService us = new UserServiceImpl();

????????User user = us.findUser(username, password);? ? ? ??

????????if(user != null) {

????????????request.getSession().setAttribute("user", user);

????????????request.getRequestDispatcher("/home.jsp").forward(request, response);

????????}else {

????????????request.setAttribute("msg", "用戶名或密碼錯誤,請重新登錄。");

????????????request.getRequestDispatcher("/login.jsp").forward(request, response);

????????}

????}? ??

????public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

????????doGet(request, response);

????}

}

創(chuàng)建home.jsp

這個頁面用來顯示 歡迎你,用戶名

<%@?page?language="java"?contentType="text/html; charset=UTF-8"

? ?pageEncoding="UTF-8"%>

<!DOCTYPE?html?PUBLIC?"-//W3C//DTD HTML 4.01 Transitional//EN"?"https://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta?http-equiv="Content-Type"?content="text/html; charset=ISO-8859-1">

<title>Insert title here</title>

</head>

<body>

????歡迎你,${user.username?}

</body>

</html>

部署測試

部署代碼,瀏覽器訪問/login.jsp,測試以下登錄看看。

JavaWeb練習(xí)之使用filter實現(xiàn)自動登陸

添加Filter

前面已經(jīng)實現(xiàn)了登錄功能,下面開始使用Filter相關(guān)代碼來實現(xiàn)自動登錄。到這里,F(xiàn)ilter主要做這幾件事

??從cookies中取出用戶賬戶相關(guān)信息

??執(zhí)行登錄操作

??放行,直接跳轉(zhuǎn)到/home.jsp頁面。

先把LoginServlet中代碼添加cookie相關(guān)代碼。

package?com.kaigejava.web.servlet;

import?java.io.IOException;

import?javax.servlet.ServletException;

import?javax.servlet.http.Cookie;

import?javax.servlet.http.HttpServlet;

import?javax.servlet.http.HttpServletRequest;

import?javax.servlet.http.HttpServletResponse;

import?com.kaigejava.domain.User;

import?com.kaigejava.service.UserService;

import?com.kaigejava.service.UserServiceImpl;

public?class?LoginServlet?extends?HttpServlet?{? ??

????public?void?doGet(HttpServletRequest?request,?HttpServletResponse?response)?throws?ServletException,?IOException?{

????????String?username?=?request.getParameter("username");

????????String?password?=?request.getParameter("password");

? ? ? ? ? ? ? ??UserService?us?=?new?UserServiceImpl();

????????User?user?=?us.findUser(username,?password);

????????if(user?!=?null) {

????????????String?autoLogin?=?request.getParameter("autoLogin");

????????????//?拿到這個cookie,可以通過&切割拿到用戶名和密碼

????????????Cookie?cookie?=?new?Cookie("user",?user.getUsername()+"&"+user.getPassword());

????????????cookie.setPath("/");

????????????if(autoLogin?!=?null) {

????????????????cookie.setMaxAge(60*60*24*7);?//?設(shè)置有效期為7天

????????????}else?{

????????????????cookie.setMaxAge(0);

????????????}

????????????response.addCookie(cookie);?//把cookie保存到客戶端

????????????request.getSession().setAttribute("user",?user);

????????????request.getRequestDispatcher("/home.jsp").forward(request,?response);

????????????

????????}else?{

????????????request.setAttribute("msg",?"用戶名或密碼錯誤,請重新登錄。");

????????????request.getRequestDispatcher("/login.jsp").forward(request,?response);

????????}

????}

????

????public?void?doPost(HttpServletRequest?request,?HttpServletResponse?response)?throws?ServletException,?IOException?{

????????doGet(request,?response);

????}

}

創(chuàng)建一個Filter,代碼如下。

package com.kaigejava.web.filter;

import java.io.IOException;

import javax.servlet.Filter;

import javax.servlet.FilterChain;

import javax.servlet.FilterConfig;

import javax.servlet.ServletException;

import javax.servlet.ServletRequest;

import javax.servlet.ServletResponse;

import javax.servlet.http.Cookie;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import com.kaigejava.domain.User;

import com.kaigejava.service.UserService;

import com.kaigejava.service.UserServiceImpl;

public class AutoLoginFilter implements Filter {

????public void destroy() {

????}

? ? public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {? ? ? ??

????????// 1 轉(zhuǎn)換兩個對象 HttpServletRequest HttpServletResponse

????????HttpServletRequest req = (HttpServletRequest) request;

????????HttpServletResponse resp = (HttpServletResponse) response;? ? ? ??

????????// 2.處理業(yè)務(wù), 這里是得到cookies

????????Cookie[] cookies = req.getCookies();

????????String username = "";

????????String password = "";

????????for (int i = 0; cookies != null && i < cookies.length; i++) {

????????????if("user".equals(cookies[i].getName())) {

????????????????String value = cookies[i].getValue(); // username&password這樣一個格式字符串

????????????????// 得到用戶名和密碼

????????????????String[] values = value.split("&");

????????????????username = values[0];

????????????????password = values[1];

????????????}

????????}

????????UserService us = new UserServiceImpl();

????????User u = us.findUser(username, password);

????????

????????if(u != null) { // 如果登錄成功,把用戶信息存到session中

????????????req.getSession().setAttribute("user", u);

????????}

????????// 3.放行

????????chain.doFilter(request, response);

????}

????public void init(FilterConfig fConfig) throws ServletException {

????

????}

}

部署測試

部署tomcat之后,打開瀏覽器先訪問/login.jsp,出現(xiàn)登錄界面,輸入tom/123,記得勾選自動登錄,然后可以看到歡迎用戶的打印內(nèi)容。關(guān)閉瀏覽器,再次打開瀏覽器,訪問/home.jsp, 如果直接顯示歡迎xxx用戶,說明實現(xiàn)自動登錄。

標(biāo)題名稱:JavaWeb練習(xí)之使用filter實現(xiàn)自動登陸
文章位置:http://bm7419.com/article18/gigpdp.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站導(dǎo)航網(wǎng)站維護(hù)、云服務(wù)器、面包屑導(dǎo)航、網(wǎng)站營銷、外貿(mào)建站

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

網(wǎng)站建設(shè)網(wǎng)站維護(hù)公司