Cookie简单实例

1、创建CookieServlet

 package com.servlet.study;

 import java.io.IOException;
import java.io.PrintWriter; import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/cookieServlet.do")
public class CookieServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//设置服务器端以UTF-8编码进行输出
response.setCharacterEncoding("UTF-8");
//设置浏览器以UTF-8编码进行接收,解决中文乱码问题
response.setContentType("text/html;charset = UTF-8");
PrintWriter out = response.getWriter(); //获取cookie
String username = "";
String check = "";
Cookie[] cookies = request.getCookies();
for(int i = 0; cookies != null && i < cookies.length; i++){
Cookie c = cookies[i];
if("username".equals(c.getName())){
username = c.getValue();
check = "checked = 'checked'";
break;
}
} //登录页面
out.write("<form action = '" + request.getContextPath() + "/loginCookieServlet.do' method = 'post'>");
out.write("用户名:<input type = 'text' name = 'username' value = '" + username + "'><br />");
out.write("密码:<input type = 'password' name = 'password' value = ''><br />");
out.write("记住用户名:<input type = 'checkbox' name = 'remember'" + check + "'><br />");
out.write("<input type = 'submit' name = 'submit' value = '登录'><br />");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}

2、创建LoginCookieServlet

 package com.servlet.study;

 import java.io.IOException;
import java.io.PrintWriter; import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; @WebServlet("/loginCookieServlet.do")
public class LoginCookieServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");
String remember = request.getParameter("remember");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset = UTF-8");
PrintWriter out = response.getWriter(); //创建一个新的Cookie
Cookie cookie = new Cookie("username", username);
cookie.setPath(request.getContextPath());
if(remember != null){
//如果选择了记住用户名,则设置Cookie的有效期为一个不为0的整数
cookie.setMaxAge(Integer.MAX_VALUE);
}else{
//否则则把有效期设置为0,即命令浏览器删除该cookie
cookie.setMaxAge(0);
}
//将cookie对象添加到response对象中,这样服务器在输出response对象中的内容时就会把cookie也输出到客户端服务器
response.addCookie(cookie);
out.write("登录成功!");
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}

3、访问,结果

Cookie简单实例-LMLPHP

Cookie简单实例-LMLPHP

Cookie简单实例-LMLPHP

04-30 02:57