很多网站目前有这样一种功能,在客户首次登录页面时,会提醒客户是否在一段时间内自动登录,设为自动登录,待客户下次登录改页面时,不要求用户再次输入用户名和密码,而是直接登录到,这样方便了用户访问此网站。在学完Filter后,可以利用Filter加cookie来完成全网站自动登录功能。
数据层需要定义一个用户对象,其中包括用户名和密码
public class User {
private String name;
private String password;
public User(){
}
public User(String name, String password){
super();
this.name = name;
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
对应的数据增加一张User表,如下:
create table user(
id varchar(40) primary key,
name varchar(20) unique not null,
password varchar(20)
);
dao层,提供了一个add方法和一个find方法,分别如下:
public interface UserDao {
void add(User user) throws SQLException; //用户注册时,向数据库中添加一条记录
User find(String name) throws SQLException;//用户登录时,从数据库查找是否存在这条记录
}
dao实现,首先这里使用的apache的dbutils工具包来操作数据库,数据库连接池使用c3p0来创建。dao实现如下:这里使用UUID来生成一个随机ID;
public class UserDaoImpl implements UserDao {
public void add(User user) throws SQLException{
QueryRunner qr = new QueryRunner();
String sql = "insert into user(id, name, password) values(?,?,?)";
Object[] params = {JdbcDbutils.makeUUID(), user.getName(), user.getPassword()};
qr.update(JdbcDbutils.getConnection(), sql, params);
}
public User find(String name) throws SQLException{
QueryRunner qr = new QueryRunner();
String sql = "select * from user where name=?";
Object[] params = {name};
return (User)qr.query(JdbcDbutils.getConnection(), sql, new BeanHandler(User.class), params);
}
}
到这里数据层已经准备好了,service层主要涉及到注册和登录,登录分为自动登录和手动登录(自动登录失效后).当用户手动时,要是用户选择了下次自动登录,则在登录时,将会生成一个cookie文件,将用户的姓名和密码存入到cookie中,带下次用户访问此网站时,将自动从cookie中获取用户名和密码,实现自动登录。当然这里存入到cookie中密码,原则上是要进行加密的,示例中就不进行加密了,存的是明文。下面是自动登录工具类:
package cn.itcast.utils;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.itcast.domain.User;
import cn.itcast.exceptions.UserOperException;
import cn.itcast.service.UserService;
import cn.itcast.service.impl.UserServiceImpl;
public class AutoLoginUtils {
public static void saveLoginInfoToCookie(User user, HttpServletRequest request, HttpServletResponse response) throws UserOperException{
UserService service = new UserServiceImpl();
User user1 = service.find(user.getName());
if(user1.getPassword().equals(user.getPassword())){
Cookie cookie = new Cookie("autologin", user.getName()+"#"+user.getPassword());
cookie.setMaxAge(3600); //必须设置值,否则此cookie只会存在浏览器内存中,浏览器关闭,此cookie将会删除
cookie.setPath("/"); //设置在根目录下,这样在此web应用下,都可以访问
response.addCookie(cookie);
request.getSession().setAttribute("user", user); //将user存到到session中
}
}
public static void readCookieAndLogin(HttpServletRequest request, HttpServletResponse response,
FilterChain chain) throws IOException, ServletException{
User user = (User) request.getSession().getAttribute("user");
if(user!=null){
chain.doFilter(request, response);
return;
}
Cookie[] cookies = request.getCookies();
String cookieValue = null;
for (int i=0; cookies!=null && i<cookies.length; i++) {
Cookie ck = cookies[i];
if (ck.getName().equals("autologin")) {
cookieValue = ck.getValue();
break;
}
}
if(cookieValue==null){
chain.doFilter(request, response);
return;
}
String name = cookieValue.substring(0, cookieValue.lastIndexOf("*"));
String password = cookieValue
.substring(cookieValue.lastIndexOf("#") + 1);
UserService service = new UserServiceImpl();
try {
user = service.find(name);
if (user!=null && user.getPassword().equals(password)) {
request.getSession().setAttribute("user", user);
} else {
request.setAttribute("message", "您还未登录,请先登录");
}
} catch (UserOperException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
chain.doFilter(request, response);
}
}
过滤器
public class AutoLoginFilter implements Filter {
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
AutoLoginUtils.readCookieAndLogin(request, response, chain);
}
@Override
public void init(FilterConfig config) throws ServletException {
// TODO Auto-generated method stub
}
}
登录servlet
public class LoginServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name = request.getParameter("name");
String password = request.getParameter("logPwd");
String checkCode = request.getParameter("checkcode");
String imageCode = (String) request.getSession().getAttribute("checkcode");
String autoLogin = request.getParameter("autologin");
if (!checkCode.equals(imageCode)){
request.setAttribute("message", "校验码输入错误<meta http-equiv='refresh' content='3,url=/AutoLogin/index.jsp'");
request.getRequestDispatcher("/jsp/message.jsp").forward(request, response);
return;
}
try {
UserService service = new UserServiceImpl();
User user = service.find(name);
if(user!=null && user.getPassword().equals(password)){
/*
if(autoLogin.equals("on")){
Cookie cookie = new Cookie("autologin", name+"*"+password);
cookie.setMaxAge(3600);
cookie.setPath("/");
response.addCookie(cookie);
}
*/
AutoLoginUtils.saveLoginInfoToCookie(user, request, response);
request.getSession().setAttribute("user", user);
request.getRequestDispatcher("/index.jsp").forward(request, response);
return;
}else{
request.setAttribute("message", "用户名或密码输入错误<meta http-equiv='refresh' content='3,url=/AutoLogin/index.jsp'");
request.getRequestDispatcher("/jsp/message.jsp").forward(request, response);
return;
}
} catch (UserOperException e) {
// TODO Auto-generated catch block
e.printStackTrace();
request.setAttribute("message", "登录失败<meta http-equiv='refresh' content='3,url=/AutoLogin/index.jsp'");
request.getRequestDispatcher("/jsp/message.jsp").forward(request, response);
return;
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}