Filter练习-自动登录
成都创新互联公司凭借在网站建设、网站推广领域领先的技术能力和多年的行业经验,为客户提供超值的营销型网站建设服务,我们始终认为:好的营销型网站就是好的业务员。我们已成功为企业单位、个人等客户提供了成都网站制作、成都网站建设、外贸营销网站建设服务,以良好的商业信誉,完善的服务及深厚的技术力量处于同行领先地位。
本篇来做一个Filter的练习题,就是网站自动登录的,这个自动登录,我们在学习cookies的时候做过,这次使用Filter来做一遍。
数据库表准备
首先,我们需要准备一个表,用户表,如果没有可以参考以下SQL去创建。
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")
创建一个java web项目
拷贝相关jar和数据库连接配置文件。以下全部文件都可以从前面图书管理系统中拷贝过来,Dao和Service和servlet代码我们接下来会重写写。
写一个用户登录的jsp页面
写一个登录的jsp页面,有用户名和密码和登录,以及自动登录这个checkbox。
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
浏览器打开这个login.jsp效果如下
Dao层代码
一个接口和一个实现类文件代码。
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;
}
具体实现类代码
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层代码
一个接口和一个实现类文件代码。
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 {
// 创建一个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);
}
}
创建home.jsp
这个页面用来显示 欢迎你,用户名
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
欢迎你,${user.username }
部署测试
部署代码,浏览器访问/login.jsp,测试以下登录看看。
添加Filter
前面已经实现了登录功能,下面开始使用Filter相关代码来实现自动登录。到这里,Filter主要做这几件事
• 从cookies中取出用户账户相关信息
• 执行登录操作
• 放行,直接跳转到/home.jsp页面。
先把LoginServlet中代码添加cookie相关代码。
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); // 设置有效期为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);
}
}
创建一个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 转换两个对象 HttpServletRequest HttpServletResponse
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
// 2.处理业务, 这里是得到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,出现登录界面,输入tom/123,记得勾选自动登录,然后可以看到欢迎用户的打印内容。关闭浏览器,再次打开浏览器,访问/home.jsp, 如果直接显示欢迎xxx用户,说明实现自动登录。