思路
如上图,如果勾选了自动登录,在登录时,就将用户名和密码存储到cookie中,当下次访问首页时,过滤器先拦截请求,获取下cookie中的账号密码,然后如果cookie中的账号密码有效就将登录信息存储到session中。这就是自动登录了。
AutoLoginFilter
package com.yyy.filter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
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.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.yyy.util.DbHelper;
/**
* Servlet Filter implementation class AutoLoginFilter
*/
@WebFilter("/AutoLoginFilter")
public class AutoLoginFilter implements Filter {
/**
* Default constructor.
*/
public AutoLoginFilter() {
// TODO Auto-generated constructor stub
}
/**
* @see Filter#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
}
/**
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
public void doFilter(ServletRequest request1, ServletResponse response1, FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
//过滤的操作放在此方法中
HttpServletRequest request=(HttpServletRequest)request1;
HttpServletResponse response=(HttpServletResponse)response1;
//判断cookie中是否有用户信息
Cookie[] cookies= request.getCookies();
String uname=null;
String pwd=null;
if(cookies!=null)
{
//遍历每一个cookie对象
for(Cookie cookie:cookies)
{
if(cookie.getName().equals("login_uname"))
uname= cookie.getValue();
if(cookie.getName().equals("login_pwd"))
pwd=cookie.getValue();
}
//如果有 则获取cookie中的用户信息 连接数据库查询是否能登录
if(uname!=null && pwd!=null)
{
String sql="select * from user where uname=? and upwd=?";
List<Object> paralist=new ArrayList<Object>();
paralist.add(uname);
paralist.add(pwd);
DbHelper dbHelper=new DbHelper();
List<Map<String, Object>> map= dbHelper.executeQuery(sql, paralist);
//如果能登录 则存入session
if(map.size()>0 && map!=null)
{
HttpSession session= request.getSession();
session.setAttribute("uname", uname);
}
}
}
//放行
chain.doFilter(request, response);
}
/**
* @see Filter#init(FilterConfig)
*/
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
}
}
ExitServlet
package com.yyy.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class ExitServlet
*/
@WebServlet("/ExitServlet")
public class ExitServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ExitServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//response.getWriter().append("Served at: ").append(request.getContextPath());
//销毁session
HttpSession session=request.getSession();
session.invalidate();
//销毁cookie
Cookie cookie=new Cookie("login_uname", null);
cookie.setPath("/");
cookie.setMaxAge(0);
Cookie cookie2=new Cookie("login_pwd", null);
cookie2.setPath("/");
cookie2.setMaxAge(0);
response.addCookie(cookie);
response.addCookie(cookie2);
response.sendRedirect("guanwang.jsp");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
LoginServlet
package com.yyy.servlet;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.yyy.util.DbHelper;
/**
* Servlet implementation class LoginServlet
*/
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public LoginServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//response.getWriter().append("Served at: ").append(request.getContextPath());
//获得用户信息
String uname=request.getParameter("uname");
String pwd=request.getParameter("pwd");
//判断是否登录成功
String sql="select * from user where uname=? && upwd=?";
List<Object> paramList=new ArrayList<Object>();
paramList.add(uname);
paramList.add(pwd);
DbHelper dbHelper=new DbHelper();
List<Map<String, Object>> map= dbHelper.executeQuery(sql, paramList);
if(map!=null && map.size()>0)
{
//判断是否选择了自动登录
if(request.getParameter("ck")!=null)
{
//存入cookie
Cookie cookie=new Cookie("login_uname", uname);
cookie.setPath("/");
cookie.setMaxAge(3600);
response.addCookie(cookie);
Cookie cookie2=new Cookie("login_pwd", pwd);
cookie2.setPath("/");
cookie2.setMaxAge(3600);
response.addCookie(cookie2);
}
//登录成功 存session
HttpSession session=request.getSession();
session.setAttribute("uname", uname);
response.sendRedirect("guanwang.jsp");
}
else
response.getWriter().println("用户名或密码出错");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
DbHelper
package com.yyy.util;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.print.attribute.standard.RequestingUserName;
public class DbHelper {
private Connection connection;
private PreparedStatement preparedStatement;
private ResultSet resultSet;
public DbHelper()
{
getConnection();
}
//打开连接
public void getConnection()
{
try {
if(connection==null || connection.isClosed())
{
//将文件中的数据转到集合中 再从集合取数据
Properties properties=new Properties();
InputStream iStream=this.getClass().getResourceAsStream("/db2.properties");
properties.load(iStream);
//获得集合中数据
String driver=properties.getProperty("driver");
String url=properties.getProperty("url");
String uname=properties.getProperty("uname");
String pwd=properties.getProperty("pwd");
Class.forName(driver);
this.connection= DriverManager.getConnection(url, uname, pwd);
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//执行 增 删 改 语句 返回受影响的行数
public int executeUpdate(String sql,List<Object> paramList)
{
getConnection(); //打开连接
try {
this.preparedStatement=connection.prepareStatement(sql);
//给sql语句的参数赋值
if(paramList!=null)
{
for(int i=0;i<paramList.size();i++)
{
this.preparedStatement.setObject(i+1, paramList.get(i));
}
}
return this.preparedStatement.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
close();
}
return 0;
}
//执行查询
public List<Map<String, Object>> executeQuery(String sql,List<Object> paramList)
{
getConnection();
try {
this.preparedStatement=connection.prepareStatement(sql);
//给sql的参数赋值
if(paramList!=null)
{
for(int i=0;i<paramList.size();i++)
{
this.preparedStatement.setObject(i+1, paramList.get(i));
}
}
//执行查询
this.resultSet= this.preparedStatement.executeQuery();
//定义一个集合用来存放结果集中的数据
List<Map<String, Object>> resultList=new ArrayList<Map<String,Object>>();
//读取结果集中的数据存入到集合resultList中
//获得结果集中的列名
ResultSetMetaData resultSetMetaData= this.resultSet.getMetaData();
while(resultSet.next())
{
//存放结果集中的每一条记录 uid=1 uname="zhangsan" pwd="123"
Map<String, Object> map=new HashMap<String,Object>();
for(int i=1;i<=resultSetMetaData.getColumnCount();i++)
{
//获得第i列的名称
String columnname= resultSetMetaData.getColumnName(i);
//获得第i列的值
Object columnvalue=resultSet.getObject(columnname);
map.put(columnname, columnvalue);
}
//将map存入到list中
resultList.add(map);
}
return resultList;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
close();
}
return null;
}
//关闭连接
public void close()
{
if(resultSet!=null)
try {
resultSet.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(preparedStatement!=null)
try {
preparedStatement.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(connection!=null)
try {
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
db2.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/itstar?characterEncoding=utf-8
uname=itstar
pwd=yyy123456
guanwang.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
if(session.getAttribute("uname")!=null)
{
%>
<%=session.getAttribute("uname") %> 欢迎您,<a href="ExitServlet">退出</a>
<%
}
else
{
%>
亲,请<a href="login.jsp">登录</a>
<%
}
%>
</body>
</html>
login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="LoginServlet" method="post">
<pre>
用户名:<input type='text' name='uname' />
密码:<input type='password' name='pwd' />
<input type='checkbox' value='ck' name='ck' />自动登录
<input type='submit' name='sub' value='登录' />
</pre>
</form>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>web5</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<session-config>
<session-timeout>1</session-timeout>
</session-config>
<!-- 注册过滤器 -->
<filter>
<filter-name>AutoLoginFilter</filter-name>
<filter-class>com.yyy.filter.AutoLoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>AutoLoginFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
数据库驱动jar包
允许效果