您好,登錄后才能下訂單哦!
Filter練習(xí)-自動登錄
本篇來做一個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")
創(chuàng)建一個java web項(xiàng)目
拷貝相關(guān)jar和數(shù)據(jù)庫連接配置文件。以下全部文件都可以從前面圖書管理系統(tǒng)中拷貝過來,Dao和Service和servlet代碼我們接下來會重寫寫。
寫一個用戶登錄的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效果如下
Dao層代碼
一個接口和一個實(shí)現(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;
}
具體實(shí)現(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層代碼
一個接口和一個實(shí)現(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,測試以下登錄看看。
添加Filter
前面已經(jīng)實(shí)現(xiàn)了登錄功能,下面開始使用Filter相關(guān)代碼來實(shí)現(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用戶,說明實(shí)現(xiàn)自動登錄。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。