cookie的使用
Posted cc101
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了cookie的使用相关的知识,希望对你有一定的参考价值。
使用cookie,如果用户在登录时选择保存登录信息,30天内,用户无需输入,直接登录成功。
package servlet; import javax.servlet.http.Cookie; import java.io.IOException; 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; /** * Servlet implementation class MyServlet */ @WebServlet("/MyServlet") public class MyServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public MyServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.getWriter().append("Served at: ").append(request.getContextPath()); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub // 判断是否拥有cookie Cookie[] cookies = request.getCookies(); //String value = ""; if (cookies != null) { for (int i=0;i<cookies.length;i++) { if (cookies[i].getName().equals("remember")) { response.sendRedirect("After.html"); return; } } } String username = request.getParameter("username"); String password = request.getParameter("password"); String remember = request.getParameter("remember"); // 判断账号密码是否正确,默认账号密码为:tom 123 if (username != null && password != null) { if (!username.isEmpty() && !password.isEmpty() ) { if (username.equals("tom") && password.equals("123")&&remember!=null) { Cookie newCookie = new Cookie("remember", "1"); newCookie.setMaxAge(30*24*60*60); response.addCookie(newCookie); response.sendRedirect("After.html"); return; } else if(username.equals("tom") && password.equals("123")){ response.sendRedirect("After.html"); return; } } } response.sendRedirect("Login.html"); } }
以上是关于cookie的使用的主要内容,如果未能解决你的问题,请参考以下文章
Django cookie 横幅:window.wpcc 未定义