@WebServlet("/del") public class DelCookieServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //通过访问该servlet,将cookie信息删除 Cookie[] cookies = request.getCookies(); if(cookies != null){ for (Cookie cookie : cookies) { if("username".equals(cookie.getName())){ cookie.setMaxAge(0); //需要把这个告诉给浏览器 response.addCookie(cookie); } } } } }
cookie.setMaxAge(0); cookie.setPath(request.getContextPath() + "/info"); response.addCookie(cookie);
@WebServlet("/cookieTest") public class CookieTest extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //设置响应的消息体的数据格式以及编码 response.setContentType("text/html;charset=utf-8"); //1.获取所有Cookie Cookie[] cookies = request.getCookies(); boolean flag = false;//没有cookie为lastTime //2.遍历cookie数组 if(cookies != null && cookies.length > 0){ for (Cookie cookie : cookies) { //3.获取cookie的名称 String name = cookie.getName(); //4.判断名称是否是:lastTime if("lastTime".equals(name)){ //有该Cookie,不是第一次访问 flag = true;//有lastTime的cookie //设置Cookie的value //获取当前时间的字符串,重新设置Cookie的值,重新发送cookie Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss"); String str_date = sdf.format(date); System.out.println("编码前:"+str_date); //URL编码 str_date = URLEncoder.encode(str_date,"utf-8"); System.out.println("编码后:"+str_date); cookie.setValue(str_date); //设置cookie的存活时间 cookie.setMaxAge(60 * 60 * 24 * 30);//一个月 response.addCookie(cookie);//响应数据 //获取Cookie的value,时间 String value = cookie.getValue(); System.out.println("解码前:"+value); //URL解码: value = URLDecoder.decode(value,"utf-8"); System.out.println("解码后:"+value); response.getWriter().write("<h1>欢迎回来,您上次访问时间为:"+value+"</h1>"); break; } } } if(cookies == null || cookies.length == 0 || flag == false){ //没有,第一次访问 //设置Cookie的value //获取当前时间的字符串,重新设置Cookie的值,重新发送cookie Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss"); String str_date = sdf.format(date); System.out.println("编码前:"+str_date); //URL编码 str_date = URLEncoder.encode(str_date,"utf-8"); System.out.println("编码后:"+str_date); Cookie cookie = new Cookie("lastTime",str_date); //设置cookie的存活时间 cookie.setMaxAge(60 * 60 * 24 * 30);//一个月 response.addCookie(cookie); response.getWriter().write("<h1>您好,欢迎您首次访问</h1>"); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }
@WebServlet("/login") public class LoginServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); String username = request.getParameter("username"); String password = request.getParameter("password"); //不做任何校验,只要输入就当作登录成功 request.getSession().setAttribute("username", username); response.getWriter().println("登录成功,即将跳转至个人主页...."); response.setHeader("refresh", "2;url=" + request.getContextPath() + "/info"); //Context域不可以 } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } } @WebServlet("/info") public class InfoServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // String username = (String) request.getSession().getAttribute("username"); if(username == null){ username = ""; } response.setContentType("text/html;charset=utf-8"); response.getWriter().println("<!DOCTYPE html>\n" + "<html lang=\"en\">\n" + "<head>\n" + " <meta charset=\"UTF-8\">\n" + " <title>Title</title>\n" + "</head>\n" + "<body>"); response.getWriter().println("欢迎您," + username); response.getWriter().println("</body>\n" + "</html>"); } }
Cookie c = new Cookie("JSESSIONID",session.getId()); c.setMaxAge(60*60); response.addCookie(c);
可以理解为JSESSIONID及其数据内容是灵魂,寄居在一个新的对象上(全新的内存地址)
<session-config> <session-timeout>30</session-timeout> </session-config>
我们通过一个管理系统来验证应用的卸载。
本地安装的tomcat的webapps有manager应用
本地安装的tomcat的conf/tomcat-users.xml文件配置如下
//商品类 public class Product { private String id; private String name; private Double price; private String description; public String getName() { return name; } public void setName(String name) { this.name = name; } public Double getPrice() { return price; } public void setPrice(Double price) { this.price = price; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public void setId(String id) { this.id = id; } public String getId() { return id; } public Product(String id, String name, Double price, String description) { this.id = id; this.name = name; this.price = price; this.description = description; } @Override public String toString() { return "Product{" + "id=" + id + ", name='" + name + '\'' + ", price=" + price + ", description='" + description + '\'' + '}'; } } //网站首页 import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.ArrayList; import java.util.List; @WebServlet(value = "/index",loadOnStartup = 1) public class IndexServlet extends HttpServlet { @Override public void init() throws ServletException { List<Product> products = new ArrayList<>(); Product model3 = new Product("1", "Tesla Model 3", 240000.0, "国产Tesla model3"); Product nio = new Product("2", "Nio ES6", 450000.0, "国产电动车"); Product xpeng = new Product("3", "Xpeng P7", 230000.0, "国产电动"); Product li = new Product("4", "Li one", 250000.0, "国产电动三"); products.add(model3); products.add(nio); products.add(xpeng); products.add(li); getServletContext().setAttribute("products", products); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //显示出来 List<Product> products = (List<Product>) getServletContext().getAttribute("products"); response.getWriter().println("<!DOCTYPE html>\n" + "<html lang=\"en\">\n" + "<head>\n" + " <meta charset=\"UTF-8\">\n" + " <title>Title</title>\n" + "</head>\n" + "<body>"); for (Product product : products) { String detail = response.encodeURL(request.getContextPath() + "/detail?id=" + product.getId()); response.getWriter().println("<div><a href='" + detail + "'>" + product.getName() + "</a></div>"); } response.getWriter().println("\n" + "</body>\n" + "</html>"); } } //商品详情 import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; @WebServlet("/detail") public class DetailServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); String id = request.getParameter("id"); //判断是否为空 List<Product> products = (List<Product>) getServletContext().getAttribute("products"); for (Product product : products) { if(product.getId().equals(id)){ response.getWriter().println(product); } } String index = response.encodeURL(request.getContextPath() + "/index"); String addCart = response.encodeURL(request.getContextPath() + "/addCart?id=" + id); String viewCart = response.encodeURL(request.getContextPath() + "/viewCart"); response.getWriter().println("<a href='" + index + "'>返回首页</a>"); response.getWriter().println("<a href='" + addCart + "'>加入购物车</a>"); response.getWriter().println("<a href='" + viewCart + "'>查看购物车</a>"); } } //添加购物车 import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.util.ArrayList; import java.util.List; @WebServlet("/addCart") public class AddCartServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); String id = request.getParameter("id"); HttpSession session = request.getSession(); //判断是否为空 学有余力的同学可以晚上加上数量 // list //要先取出来,再塞进去 List<String> cart = (List<String>) session.getAttribute("cart"); if(cart == null){ cart = new ArrayList<>(); session.setAttribute("cart", cart); } cart.add(id); response.getWriter().println("加入购物车成功,即将跳转回首页"); String index = response.encodeURL(request.getContextPath() + "/index"); response.setHeader("refresh", "2;url=" + index ); } } //查看购物车 import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.util.List; @WebServlet("/viewCart") public class ViewCartServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); HttpSession session = request.getSession(); List<String> cart = (List<String>) session.getAttribute("cart"); if(cart == null){ response.getWriter().println("购物车为空"); return; } List<Product> products = (List<Product>) getServletContext().getAttribute("products"); for (Product product : products) { for (String id : cart) { if(id.equals(product.getId())){ response.getWriter().println(product); } } } String index = response.encodeURL(request.getContextPath() + "/index"); response.getWriter().println("<a href='" + index + "'>返回首页</a>"); } }