用cookie实现自动登录

今天学习了cookie小功能,这个主要应用在登录时,在你第一次登陆后,下次就可以自动登录等;
首先是登录页面:

<%@ 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>
    <%//获取用户名和密码cookie,判断cookie是否为空,为空的情况就是第一次登录,跳到登录页面,不为空就直接跳转到登陆后的页面。
        String name=null;
        String password=null;
        Cookie[] cookies=request.getCookies();
        if(cookies!=null){
            for(Cookie cookie:cookies){
                if(cookie.getName().equals("username")){
                    name=cookie.getValue();
                }
                if(cookie.getName().equals("pwd")){
                    password=cookie.getValue();
                }
            }
            if(name!=null&&password!=null){
                response.sendRedirect("LoginServlet?username="+name+"&pwd="+password);
            }
        }

    %>
    <h1>欢迎来到动物园</h1>
    <form action="<%=request.getContextPath()%>/LoginServlet" method="get">
        <p>请输入口令:<input type="text" name="username"></p>
        <p>请输入密码:<input type="password" name="pwd"></p>
         <p><input type="checkbox" name="box" value="ck">自动登录</p>
        <p><input type="submit" value="欢迎进入"></p>
    </form>
</body>
</html>

下面是servlet

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        接收请求参数的值
        String username=request.getParameter("username");
        String password=request.getParameter("pwd");
                if(username.equals("yyy")&&password.equals("123")) {
                    //如果没有选中自动登录,则要输入账号登录,否则就会执行cookie,实现自动登录
                    if(request.getParameter("box")==null) {
                        request.getRequestDispatcher("SearchAllServlet").forward(request, response);
                    }else {

                    Cookie name=new Cookie("username", username);
                    Cookie pwd=new Cookie("pwd", password);
                    response.addCookie(name);
                    response.addCookie(pwd);
                    name.setMaxAge(60*60);
                    pwd.setMaxAge(60*60);
                    request.getRequestDispatcher("SearchAllServlet").forward(request, response);
                }
                }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章