sql表
username password字段
User类
有 id username password等字段
Service有一函数
@Override public User findUser(String username)
{
return userDao.findUser(username);
}
实现
@Override
public User findUser(String username) {
try {
return qr.query("select * from user where username=?", new BeanHandler<User>(User.class),username);
} catch (SQLException e) {
throw new DaoException(e);
}
}
Utils
WEBUtils.java
package cn.itcast.util; import java.lang.reflect.InvocationTargetException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException; import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.apache.commons.beanutils.BeanUtils; import sun.misc.BASE64Encoder; public class WebUtils { public static <T> T fillBean(HttpServletRequest request,
Class<T> clazz) {
try {
T t=clazz.newInstance();
BeanUtils.populate(t,request.getParameterMap());
return t;
} catch(Exception e) {
throw new RuntimeException(e);
}
} public static void addAutoLoginFunction(HttpServletRequest request,
HttpServletResponse response) { String username=request.getParameter("username");
String password=request.getParameter("password");
//把帐号BASE64加密 _ 密码双次md5加密, 所以比较的时候 数据库中密码取出md5加密再和这个比较 String encodeUsername=new BASE64Encoder().encode(username.getBytes());
String encodePassword=Md5Util.md5(password);
System.out.println("存入数据库 帐号:"+username);
System.out.println("存入数据库 密码:"+password);
System.out.println("存入Cookie 帐号:"+encodeUsername);
System.out.println("存入Cookie密码:"+encodePassword);
Cookie c=new Cookie("loginInfo",encodeUsername+"_"+encodePassword);
c.setMaxAge(10000);
c.setPath(request.getContextPath());
response.addCookie(c);
}
//删除Cookie
public static void removeAutoLoginCookie(HttpServletRequest request,
HttpServletResponse response) {
Cookie cs[]=request.getCookies();
if(cs!=null)
{
for(Cookie c:cs)
{
if(c.getName().equals("loginInfo"))
{
Cookie cookie=new Cookie("loginInfo",null);
cookie.setMaxAge(0);
cookie.setPath(request.getContextPath());
response.addCookie(cookie);
// c.setMaxAge(0);
// c.setPath(request.getContextPath());
System.out.println("删除Cookie");
return;
}
}
}
} }
MD5Util.java
package cn.itcast.util; import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException; import sun.misc.BASE64Encoder; public class Md5Util {
public static String md5(String message){
try{
MessageDigest md = MessageDigest.getInstance("md5");
byte b[] = md.digest(message.getBytes());
return new BASE64Encoder().encode(b);
}catch(Exception e){
throw new RuntimeException(e);
}
}
}
Servlet中 由doGet()引出以下两个方法 operation=login operation=logout
private void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
//移除Cookie 去除自动登录功能
WebUtils.removeAutoLoginCookie(request,response);
request.getSession().invalidate();
response.sendRedirect(request.getContextPath());
} private void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username=request.getParameter("username");
String password=request.getParameter("password");
BusinessService serviceDao=new BusinessServiceImpl();
password=Md5Util.md5(password);
User user=serviceDao.login(username,password);
if(null==user)
{
request.setAttribute("message", "用户名或者密码错误");
request.getRequestDispatcher("/client/message.jsp").forward(request, response);
}
else
{
request.getSession().setAttribute("user", user);
String autoLogin=request.getParameter("autologin");
if(null!=autoLogin)
{
//添加自动登录功能
WebUtils.addAutoLoginFunction(request,response);
}
response.sendRedirect(request.getContextPath());
}
}
filter过滤器中配置
package cn.itcast.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 javax.servlet.http.HttpSession; import sun.misc.BASE64Decoder; import cn.itcast.domain.User;
import cn.itcast.service.BusinessService;
import cn.itcast.service.impl.BusinessServiceImpl;
import cn.itcast.util.Md5Util; public class AutoLoginFilter implements Filter { @Override
public void init(FilterConfig filterConfig) throws ServletException { } @Override
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest)req;
HttpServletResponse response = (HttpServletResponse)resp;
BusinessService bService=new BusinessServiceImpl();
HttpSession session = request.getSession();
User u = (User)session.getAttribute("user");
if(null==u)////只有没有登录时才自动登录,已经登录了就不需要了
{
System.out.println("自动登录开始执行");
//1、获取名称为loginInfo的cookie
Cookie loginInfoCookie=null;
Cookie cs[]=request.getCookies();
if(null!=cs)
{
for(Cookie c:cs)
{
if("loginInfo".equals(c.getName()))
{
loginInfoCookie=c;
break;
}
}
}
//2、有:取出cookie的值:用户名_加密的密码
if(null!=loginInfoCookie)
{
String usernamePassword=loginInfoCookie.getValue();
System.out.println("帐号密码整串:"+usernamePassword);
//3、拆出用户名和密码
String username=usernamePassword.split("\\_")[0];
String password=usernamePassword.split("\\_")[1];
//根据登录的时候 username password放入Cookie的原理
//username BASE64解密
username=new String(new BASE64Decoder().decodeBuffer(username));
System.out.println("Cookie的用户:"+username);
System.out.println("Cookie的密码:"+password);
User user=bService.findUser(username);
if(null!=user)
{
System.out.println("Cookie的用户:"+user.getUsername());
System.out.println("Cookie的密码:"+Md5Util.md5(user.getPassword()));
//4、再次验证用户名和密码是否正确(根据用户名查出密码,加密后再与cookie中的那个密码进行比对)
//将数据库查出的密码 md5加密和cookie中的密码相比
if(Md5Util.md5(user.getPassword()).equals(password))
{
//5、正确:得到用户对象,放到HttpSession中(自动登录)
session.setAttribute("user", user);
//自动登录搞定
System.out.println("自动登录完成");
}
}
}
}
//放行
chain.doFilter(request, response);
} @Override
public void destroy() { } }
web.xml中可以配置对指定的页面进行 自动登录的过滤器, 因为放到session中,所以不需要每个页面都过滤
url-pattern 配置 过滤地址