Filter練習(xí)-自動(dòng)登錄
成都創(chuàng)新互聯(lián)公司憑借在網(wǎng)站建設(shè)、網(wǎng)站推廣領(lǐng)域領(lǐng)先的技術(shù)能力和多年的行業(yè)經(jīng)驗(yàn),為客戶提供超值的營(yíng)銷型網(wǎng)站建設(shè)服務(wù),我們始終認(rèn)為:好的營(yíng)銷型網(wǎng)站就是好的業(yè)務(wù)員。我們已成功為企業(yè)單位、個(gè)人等客戶提供了成都網(wǎng)站制作、成都網(wǎng)站建設(shè)、外貿(mào)營(yíng)銷網(wǎng)站建設(shè)服務(wù),以良好的商業(yè)信譽(yù),完善的服務(wù)及深厚的技術(shù)力量處于同行領(lǐng)先地位。
本篇來做一個(gè)Filter的練習(xí)題,就是網(wǎng)站自動(dòng)登錄的,這個(gè)自動(dòng)登錄,我們?cè)趯W(xué)習(xí)cookies的時(shí)候做過,這次使用Filter來做一遍。
數(shù)據(jù)庫(kù)表準(zhǔn)備
首先,我們需要準(zhǔn)備一個(gè)表,用戶表,如果沒有可以參考以下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)建一個(gè)java web項(xiàng)目
拷貝相關(guān)jar和數(shù)據(jù)庫(kù)連接配置文件。以下全部文件都可以從前面圖書管理系統(tǒng)中拷貝過來,Dao和Service和servlet代碼我們接下來會(huì)重寫寫。
寫一個(gè)用戶登錄的jsp頁(yè)面
寫一個(gè)登錄的jsp頁(yè)面,有用戶名和密碼和登錄,以及自動(dòng)登錄這個(gè)checkbox。
<%@?page?language="java"?contentType="text/html; charset=UTF-8"
? ?pageEncoding="UTF-8"%>
????
????????用戶名:
????????密碼:
????????自動(dòng)登錄
????????
????
瀏覽器打開這個(gè)login.jsp效果如下
Dao層代碼
一個(gè)接口和一個(gè)實(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
????????return?user;
????}
}
Service層代碼
一個(gè)接口和一個(gè)實(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)建一個(gè)Dao層對(duì)象
????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代碼
新建一個(gè)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", "用戶名或密碼錯(cuò)誤,請(qǐng)重新登錄。");
????????????request.getRequestDispatcher("/login.jsp").forward(request, response);
????????}
????}? ??
????public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
????????doGet(request, response);
????}
}
創(chuàng)建home.jsp
這個(gè)頁(yè)面用來顯示 歡迎你,用戶名
<%@?page?language="java"?contentType="text/html; charset=UTF-8"
? ?pageEncoding="UTF-8"%>
????歡迎你,${user.username?}
部署測(cè)試
部署代碼,瀏覽器訪問/login.jsp,測(cè)試以下登錄看看。
添加Filter
前面已經(jīng)實(shí)現(xiàn)了登錄功能,下面開始使用Filter相關(guān)代碼來實(shí)現(xiàn)自動(dòng)登錄。到這里,F(xiàn)ilter主要做這幾件事
??從cookies中取出用戶賬戶相關(guān)信息
??執(zhí)行登錄操作
??放行,直接跳轉(zhuǎn)到/home.jsp頁(yè)面。
先把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");
????????????//?拿到這個(gè)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",?"用戶名或密碼錯(cuò)誤,請(qǐng)重新登錄。");
????????????request.getRequestDispatcher("/login.jsp").forward(request,?response);
????????}
????}
????
????public?void?doPost(HttpServletRequest?request,?HttpServletResponse?response)?throws?ServletException,?IOException?{
????????doGet(request,?response);
????}
}
創(chuàng)建一個(gè)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)換兩個(gè)對(duì)象 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這樣一個(gè)格式字符串
????????????????// 得到用戶名和密碼
????????????????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 {
????
????}
}
部署測(cè)試
部署tomcat之后,打開瀏覽器先訪問/login.jsp,出現(xiàn)登錄界面,輸入tom/123,記得勾選自動(dòng)登錄,然后可以看到歡迎用戶的打印內(nèi)容。關(guān)閉瀏覽器,再次打開瀏覽器,訪問/home.jsp, 如果直接顯示歡迎xxx用戶,說明實(shí)現(xiàn)自動(dòng)登錄。