您好,登录后才能下订单哦!
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"%>
<!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层代码
一个接口和一个实现类文件代码。
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<User>(User.class), username, password);
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"%>
<!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
前面已经实现了登录功能,下面开始使用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用户,说明实现自动登录。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。