自动登录Cookie与Session问题 10C

** 第一次登录后,关闭浏览器,再重新打开浏览器,第二次进入之前登录后的页面,要重新登录,无法保存之前的用户数据。 **

连接的数据表 user:

图片说明

需要的jar包:
c3p0-0.9.1.2.jar
commons-beanutils-1.8.3.jar
commons-dbutils-1.4.jar
commons-logging-1.1.1.jar
jstl.jar
mysql-connector-java-5.1.7-bin.jar
standard.jar

// (login.jsp)页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
  <form method="post" action="LoginServlet">
    账号:<input type="text" name="username"><br>
    密码:<input type="password" name="password"><br>
          <!-- 可以让自动登录的 on 做判断! -->
          <input type="checkbox" name="auto_login"> 自动登录<br>
          <input type="submit" value="登录">
  </form>
</body>
</html>

//(index.jsp)页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

 <%@ taglib  prefix="c"  uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    这是首页 , 
    <!-- 判断域中有没有username的值 -->
    <c:if test="${not empty  userBean}">
        欢迎您, ${userBean.username }!
    </c:if>

    <c:if test="${ empty  userBean}">
        您好,请登录!
    </c:if>

</body>
</html>

//(UserBrean.java)页面

package com.bean.demo;

public class UserBean {
private int id ; 
private String username;
private String password;
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public String getUsername() {
    return username;
}
public void setUsername(String username) {
    this.username = username;
}
public String getPassword() {
    return password;
}
public void setPassword(String password) {
    this.password = password;
}
}

//(UserDao.java)页面

package com.dao.demo;
import java.sql.SQLException;
import com.bean.demo.UserBean;

public interface UserDao {

    /**
     * 执行登录,并且返回该用户的所有信息(Bean的数据)
     * @param user 执行登录的用户信息
     * @return 
     */
    UserBean login(UserBean user) throws SQLException;
}


//(UserDaoImpl.java)页面

package com.dao.impl;

import java.sql.SQLException;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import com.bean.demo.UserBean;
import com.dao.demo.UserDao;
import com.util.demo.C3P0Util;

public class UserDaoImpl implements UserDao {

    @Override
    public UserBean login(UserBean user) throws SQLException {

        QueryRunner runner = new QueryRunner(C3P0Util.getDateSource());
        String sql = "select * from user where username = ? and password = ?";
        //把sql数据返回到Bean类
        return runner.query(sql, new BeanHandler<UserBean>(UserBean.class) , user.getUsername() , user.getPassword());
    }
}


(C3P0Util.java)页面

package com.util.demo;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;


public class C3P0Util {

    /* public static void main(String[] args) {

                    getConn();
    }*/

    static ComboPooledDataSource dataSource = null;
    static {
                dataSource = new ComboPooledDataSource();
            }


/**
 * 获取 dataSource变量
 * @return dataSource
 */ 


public static DataSource getDateSource() {
            return dataSource;
    }  

/**
 * 获取C3P0连接池的连接
 * @throws SQLException
 */ 
 public static Connection getConn() throws SQLException {
    return dataSource.getConnection();
    }


 /**
    * 释放资源方法
    */
 public static void close(ResultSet rs,Statement stmt,Connection conn) {
    if(rs != null) {     
            try {
            rs.close();
            } catch (SQLException e) {
            e.printStackTrace();
                throw new RuntimeException(e);
            }
            } 

    if(stmt != null) {
        try {
            stmt.close();
                } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
            }
        }

    if(conn != null) {
        try {
                conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
            }
        }
    }
}


   //(c3p0-config.xml)页面,连接数据库工具的配置文件
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
    <default-config>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/conn</property>
        <property name="user">root</property>
        <property name="password">root</property>
        <property name="driverClass">com.mysql.jdbc.Driver</property>
  </default-config>
</c3p0-config> 



      //(CookieUtil.java)页面,Cookie工具类
package com.util.demo;
import javax.servlet.http.Cookie;

public class CookieUtil {
public static Cookie findCookie(Cookie [] cookies , String name){
    if(cookies != null){
     for (Cookie cookie : cookies) {
       if(name.equals(cookie.getName())){
            return cookie;
     }
    }
   }
        return null;
  }
}



  //(LoginServlet.java)页面
package com.servlet.demo;
import java.io.IOException;
import java.sql.SQLException;
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 com.bean.demo.UserBean;
import com.dao.demo.UserDao;
import com.dao.impl.UserDaoImpl;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

try {

        String userName = request.getParameter("username");
        String password = request.getParameter("password");
//如果提交的时等于null,说明没选定自动登录,等于on时就是选择自动登录
        String autoLogin = request.getParameter("auto_login");

            UserBean user = new UserBean();
            user.setUsername(userName);
            user.setPassword(password);

            UserDao dao = new UserDaoImpl();
            UserBean userBean = dao.login(user);

            if(userBean != null){

            //页面提交上来的时候,判断on,是否选择了自动登录
            if("on".equals(autoLogin)){

                //发送cookie给客户端,cookie的值是账号和密码,#号为分割符          
                Cookie cookie = new Cookie("auto_login", userName+"#aa#"+password);
                cookie.setMaxAge(60*60*24*7);//7天有效期
                cookie.setPath("/AutoLoginDemo");
                //cookie.setPath(request.getContextPath()); //得到的是localhoust后面的目录名字
                response.addCookie(cookie);

            }

                /*用户再一次访问登录过后的首页,不需要从新登录*/
                    //成功了,创建Session对象,保存数据,发送到首页
                                request.getSession().setAttribute("userBean", userBean);
                                response.sendRedirect("index.jsp");
            }else{

                //不成功...
                request.getRequestDispatcher("login.jsp").forward(request, response);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
}

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        doGet(request, response);
    }
}



   //(AutoLoginFilter.java)页面
package com.filter.demo;
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.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import com.bean.demo.UserBean;
import com.dao.demo.UserDao;
import com.dao.impl.UserDaoImpl;
import com.util.demo.CookieUtil;

@WebFilter("/AutoLoginFilter")
public class AutoLoginFilter implements Filter {

    public void destroy() {

    }

    public void doFilter(ServletRequest req, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        try {
            HttpServletRequest request = (HttpServletRequest) req;

            //先判断,现在session中还有没有那个userBean.
            UserBean userBean = (UserBean) request.getSession().getAttribute("userBean");
            //session还有效。
            if(userBean != null){
                chain.doFilter(request, response);
            }else{
                //代表session失效了, 需要找cookie。                

                //1. 来请求的时候,先从请求里面取出cookie , 但是cookie有很多的key-value
                Cookie[] cookies = request.getCookies();
                //2. 从一堆的cookie里面找出我们以前给浏览器发的那个cookie
                Cookie cookie = CookieUtil.findCookie(cookies, "auto_login");

                //等于null代表第一次来
                if(cookie  == null){
                    chain.doFilter(request, response);
                }else{

                    //不是第一次登录, 表明用户现在已经登录过,取出Cookie的值帮用户登录          

                    String value = cookie.getValue();
                    String username = value.split("#aa#")[0];
                    String password = value.split("#aa#")[1];

                    //完成登录
                    UserBean user = new UserBean();
                    user.setUsername(username);
                    user.setPassword(password);

                    UserDao dao = new UserDaoImpl();
                    userBean = dao.login(user);

                    //使用session存这个值到域中,方便下一次未过期前还可以用。
                    request.getSession().setAttribute("userBean", userBean);

                    chain.doFilter(request, response);
                }
            }
        } catch (Exception e) {
        //异常这里也需要放行,不然出现异常会导致用户的界面出现空白
            e.printStackTrace();
            chain.doFilter(req, response);
        }
    }


    public void init(FilterConfig fConfig) throws ServletException {
//      有可能在这里面执行10分钟的耗时
    }

}


   //(web.xml)页面
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
    <display-name>AutoLoginDemo</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>
    <servlet>
        <description></description>
        <display-name>LoginServlet</display-name>
        <servlet-name>LoginServlet</servlet-name>
        <servlet-class>com.servlet.demo.LoginServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>LoginServlet</servlet-name>
        <url-pattern>/LoginServlet</url-pattern>
    </servlet-mapping>
    <filter>
        <display-name>AutoLoginFilter</display-name>
        <filter-name>AutoLoginFilter</filter-name>
        <filter-class>com.filter.demo.AutoLoginFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>AutoLoginFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

1个回答

cookie.setPath("/AutoLoginDemo");

你确定你的WebApp的名字叫做AutoLoginDemo吗?

package com.bean.demo;

这里看起来是 demo

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问