用cookie实现自动登录
2017-07-13 18:23
676 查看
今天学习了cookie小功能,这个主要应用在登录时,在你第一次登陆后,下次就可以自动登录等;
首先是登录页面:
下面是servlet
首先是登录页面:
<%@ 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); } }
相关文章推荐
- 通过COOKIE实现自动登录
- struts2与cookie实现自动登录
- j2ee cookie 实现自动登录
- cookie、session及实现记住密码,自动登录
- 利用Cookie实现自动登录,尽量做到安全
- 利用cookie+session实现自动登录
- Struts2.0中的Cookie(实现自动登录)
- cookie保存user数据及cookie实现自动登录
- struts2结合过滤器和cookie实现自动登录
- 通过COOKIE实现自动登录
- 使用cookie,session,filter等技术实现用户自动登录
- C# 设置IE Cookie 从而实现自动打开需要登录的页面
- symfony使用cookie来实现自动登录
- struts2结合过滤器和cookie实现自动登录
- 实现自动登录Cookie
- struts2与cookie实现自动登录
- jsp通过Cookie实现自动登录
- Jsp 操作 Cookie 实现自动登录
- cookie、session及实现记住密码,自动登录
- asp.net cookie 实现 记录用户登录状态,下次自动登录