07020170907
1、cookie是浏览器保存数据的一种形式,数据由服务端产生,通过响应头(setCookie)把数据写入cookie中,浏览器接受到数据后,浏览器将服务器发来的数据存在本地的cookie中
2、cookie的使用步骤:
1)、新创一个Cookie对象:Cookie cookie_username = new Cookie("username", username);
2)、设置Cookie存活时间:cookie_username.setMaxAge(7*24*60*60);[一周]
3)、添加Cookie:response.addCookie(cookie_username);
4)、读取Cookie[]:for (Cookie c : request.getCookies()) { c.getName() + c.getValue() }
3、代码如下:
package com.tiger.servlet;
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.*;
/**
* 利用cookie实现自动登陆
* @author tiger
* @Date 2017年9月9日
*/
@WebServlet("/createCookie")
public class CreateCookie extends HttpServlet {
private static final long serialVersionUID = 1L;
public CreateCookie() { }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
String checkbox = request.getParameter("checkbox");
if (checkbox != null && checkbox.equals("checkbox")) {
Cookie cookie_username = new Cookie("username", username);
cookie_username.setMaxAge(7*24*60*60);
response.addCookie(cookie_username);
Cookie cookie_password = new Cookie("password", password);
cookie_password.setMaxAge(7*24*60*60);
response.addCookie(cookie_password);
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
package com.tiger.servlet;
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.*;
/**
* 利用cookie实现自动登陆
* @author tiger
* @Date 2017年9月9日
*/
@WebServlet("/login")
public class Login extends HttpServlet {
private static final long serialVersionUID = 1L;
public Login() { }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("");
out.println("");
out.println("");
out.println("");
out.println("---登陆---");
out.println("");
out.println("");
out.println("");
out.println("
");
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("username")) {
out.println("姓名:
");
}
if (cookie.getName().equals("password")) {
out.println("密码:
");
}
}
out.println("记住登陆密码:
");
}else {
out.println("姓名:
");
out.println("密码:
");
out.println("记住登陆密码:
");
}
out.println("
");
out.println("");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}