案例11-自动登录功能的基本实现

1 login.jsp代码

2 web层LoginServlet

package www.test.web.servlet;

import java.io.IOException;
import java.sql.SQLException;

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 javax.servlet.http.HttpSession;

import www.test.domain.User;
import www.test.service.LoginService;

public class LoginServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // 解决乱码问题
        request.setCharacterEncoding("UTF-8");
        HttpSession session = request.getSession();

        // 获得页面输入的验证
        String checkCode_client = request.getParameter("checkCode");
        // 获得生成图片的文字的验证码
        String checkCode_session = (String) request.getSession().getAttribute("checkcode_session");
        // 比对页面的和生成图片的文字的验证码是否一致
        if (!checkCode_session.equals(checkCode_client)) {
            request.setAttribute("loginInfo", "您的验证码不正确");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
            return;
        }
        // 获取用户输入的数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        LoginService service = new LoginService();
        User user = null;
        try {
            user = service.login(username, password);
        } catch (SQLException e) {

            e.printStackTrace();
        }

        if (user != null) {
            // 登录成功
            // 判断用户是否勾选自动登录
            String autoLogin = request.getParameter("autoLogin");
            if (autoLogin != null) {
                Cookie cookie_username = new Cookie("cookie_username", user.getUsername());
                Cookie cookie_password = new Cookie("cookie_password", user.getPassword());
                // 设置 cookie 的持久化时间
                cookie_username.setMaxAge(60 * 60);
                cookie_password.setMaxAge(60 * 60);
                // 设置 cookie 的携带路径
                cookie_username.setPath(request.getContextPath());
                cookie_password.setPath(request.getContextPath());
                // 发送 cookie
                response.addCookie(cookie_username);
                response.addCookie(cookie_password);
            }
            
            //将登录的用户的 user 对象存到 session 中
            session.setAttribute("user", user);
            //重定向到首页
            response.sendRedirect(request.getContextPath());
        } else {
            request.setAttribute("loginInfo", "密码或者用户名不正确");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
        }
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

}

3 web层AutoLoginFilter

package www.test.web.filter;

import java.io.IOException;
import java.sql.SQLException;

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 www.test.domain.User;
import www.test.service.LoginService;

public class AutoLoginFilter implements Filter {

    public AutoLoginFilter() {
        super();
    }

    private FilterConfig filterConfig;

    public void init(FilterConfig filterConfig) throws ServletException {

        this.filterConfig = filterConfig;

    }

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain)
            throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;

        HttpServletResponse response = (HttpServletResponse) res;

        HttpSession session = request.getSession();

        // 获得 cookie 中用户名和密码 进行登录的操作
        // 定义 cookie_username
        String cookie_username = null;
        // 定义 cookie_password
        String cookie_password = null;
        // 获得 cookie
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {// 获得名字是 cookie_username 和
                                            // cookie_password
                if ("cookie_username".equals(cookie.getName())) {
                    cookie_username = cookie.getValue();
                }
                if ("cookie_password".equals(cookie.getName())) {
                    cookie_password = cookie.getValue();
                }
            }
        }
        // 判断 username 和 password 是否是 null
        if (cookie_username != null && cookie_password != null) {
            // 登录的代码
            LoginService service = new LoginService();
            
            User user = null;
            try {
                user = service.login(cookie_username, cookie_password);
            } catch (SQLException e) {
                e.printStackTrace();
            }
            // 将登录的用户的 user 对象存到 session 中
            session.setAttribute("user", user);
        }
//放行
        filterChain.doFilter(request, response);
    }

    public void destroy() {

    }
}

4 service层LoginService

package www.test.service;

import java.sql.SQLException;

import www.test.dao.LoginDao;
import www.test.domain.User;

public class LoginService {

    public User login(String username, String password) throws SQLException {
        LoginDao dao = new LoginDao();
        return dao.login(username,password);
    }

}

5 dao层LoginDao

package www.test.dao;

import java.sql.SQLException;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import www.test.domain.User;
import www.test.utils.C3P0Utils;

public class LoginDao {

    public User login(String username, String password) throws SQLException {
        QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
        String sql = "select * from user where username =? and password = ?";
        return qr.query(sql, new BeanHandler<User>(User.class), username,password);
        
    }

}

6 header.jsp代码

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<!-- 登录 注册 购物车... -->
<div class="container-fluid">
    <div class="col-md-4">
        <img src="img/logo2.png" />
    </div>
    <div class="col-md-5">
        <img src="img/header.png" />
    </div>
    <div class="col-md-3" style="padding-top: 20px">
        <ol class="list-inline">
            <c:if test="${empty user }">
                <li><a href="login.jsp">登录</a></li>
                <li><a href="register.jsp">注册</a></li>
            </c:if>
            <c:if test="${!empty user }">
                <li>欢迎您,${user.username }</li>
                <li><a href="#">退出</a></li>
            </c:if>
            
            <li><a href="cart.jsp">购物车</a></li>
            <li><a href="order_list.jsp">我的订单</a></li>
        </ol>
    </div>
</div>

<!-- 导航条 -->
<div class="container-fluid">
    <nav class="navbar navbar-inverse">
        <div class="container-fluid">
            <!-- Brand and toggle get grouped for better mobile display -->
            <div class="navbar-header">
                <button type="button" class="navbar-toggle collapsed"
                    data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"
                    aria-expanded="false">
                    <span class="sr-only">Toggle navigation</span> <span
                        class="icon-bar"></span> <span class="icon-bar"></span> <span
                        class="icon-bar"></span>
                </button>
                <a class="navbar-brand" href="#">首页</a>
            </div>

            <div class="collapse navbar-collapse"
                id="bs-example-navbar-collapse-1">
                <ul class="nav navbar-nav">
                    <li class="active"><a href="product_list.htm">手机数码<span
                            class="sr-only">(current)</span></a></li>
                    <li><a href="#">电脑办公</a></li>
                    <li><a href="#">电脑办公</a></li>
                    <li><a href="#">电脑办公</a></li>
                </ul>
                <form class="navbar-form navbar-right" role="search">
                    <div class="form-group" style="position: relative">
                        <input type="text" class="form-control" placeholder="Search"
                            onkeyup="searchWord(this)">
                        <div id="showDiv"
                            style="display: none; position: absolute; z-index: 1000; background: #fff; width: 179px; border: 1px solid #ccc;">
                        </div>
                    </div>
                    <button type="submit" class="btn btn-default">Submit</button>
                </form>

                <!-- 完成站内搜索 -->
                <script type="text/javascript">
                    function overFn(obj) {
                        $(obj).css("background", "#DBEAF9");
                    }
                    function outFn(obj) {
                        $(obj).css("background", "#fff");
                    }
                    function clickFn(obj) {
                        $("#search").val($(obj).html());
                        $("#showDiv").css("display", "none");
                    }

                    function searchWord(obj) {
                        //1、 获得输入框的输入的内容
                        var word = $(obj).val();
                        //2、 根据输入框的内容去数据库中模糊查询---List<Product>
                        var content = "";
                        $
                                .post(
                                        "${pageContext.request.contextPath}/searchWord",
                                        {
                                            "word" : word
                                        },
                                        function(data) {
                                            if (data.length > 0) {
                                                for (var i = 0; i < data.length; i++) {
                                                    content += "<div style='padding:5px;cursor:pointer'onclick='clickFn(this)' onmouseover='overFn(this)'onmouseout='outFn(this)'>"
                                                            + data[i]
                                                            + "</div>";
                                                }
                                                $("#showDiv").html(content);
                                                $("#showDiv").css("display",
                                                        "block");
                                            }
                                        }, "json");
                    }
                </script>
            </div>
        </div>
    </nav>
</div>

 7 filter配置文件

<filter>
    <filter-name>AutoLoginFilter</filter-name>
    <filter-class>www.test.web.filter.AutoLoginFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>AutoLoginFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

 

posted @ 2018-02-02 21:59  Jepson6669  阅读(746)  评论(0编辑  收藏  举报