编写cookie
1.创建cookie对象
//创建cookie对象
Cookie usernameCookie=new Cookie("username", username);
2.设置最长生命周期,单位毫秒,不设置,浏览器关闭就会消失
usernameCookie.setMaxAge(1000*60*60);
这里设置为1个小时,单位是1ms
3.设置路径
usernameCookie.setPath("/");
配置的路径是相对路径
4.通过响应对象,将cookie写入浏览器
resp.addCookie(usernameCookie);
ui段获取cookie
Cookie[] cookies = req.getCookies();
String username="";
String password="";
for (Cookie cookie : cookies) {
if (cookie!=null&&cookie.getName().equals("username")) {
username=cookie.getValue();
}
if (cookie!=null&&cookie.getName().equals("password")) {
password=cookie.getValue();
}
}
直接在静态网页的html加入定义的字符串就行了,例如:
writer.println("用户名:<input name=\"username\" value=\""+username+"\" type=\"text\"><br/>");
writer.println("密码:<input name=\"password\" value=\""+password+"\" type=\"password\"><br/>");
编写session
1.获得请求session的对象
HttpSession session=req.getSession();
session.setAttribute("username", username);
session.setAttribute("password", password);
2.调用session
HttpSession session=req.getSession();
String username=(String) session.getAttribute("username");
String password=(String) session.getAttribute("password");
注意:如果用eclipse编写的话,可能要去tomcat下载一个apache-tomcat-8.5.45-src.zip的压缩包。