HttpServlet 会话管理(二) (Cookie Session 简单示例)

本文代码转载自

《Servlet、JSP和Spring MVC初学指南》



Cookie就是简单的键值传送方法,
并能设置其过期时间,这里唯一值得注意的是
如果要删除一个Cookie方法为设置同名Cookie(response.addCookie(cookie))
预先设置过期时间为0即可(cookie.setMaxAge(0))

下面是一个使用Cookie设置页面字体的简单示例
 
 
package main.ServletStudy;

/**
 * Created by ehang on 2017/2/9.
 */

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServlet;

@WebServlet(
        name = "PreferenceServlet",
        urlPatterns = {"/preference"}
)
public class PreferenceServlet extends HttpServlet {
        private static final long serialVersionUID = 888L;

        public static final String MENU =
                "<div style = 'background:#e8e8e8;padding:15px'>" +
                        "<a href = 'cookieClass'>Cookie Class</a>  " +
                        "<a href = 'cookieInfo'>Cookie Info</a>  " +
                        "<a href = 'preference'>Preference</a></div>";

        @Override
        public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
            response.setContentType("text/html");
            PrintWriter writer = response.getWriter();
            writer.println("<html><head><title>Preference</title>" +
                    "<style>table{font-size:small;background:NavajoWhite}</style>" +
                    "</head><body>" +
                    MENU +

                    "Please Select the values below:" +
                    "<form method = 'post'>"

                    + "<table>"
                    + "<tr><td>Title Font Size: </td><td><select name = 'titleFontSize'>" +
                    "<option>large</option>" +
                    "<option>x-large</option>" +
                    "<option>xx-large</option>" +
                    "</select></td></tr>" +

                    "<tr><td>Title Style & Weight: </td><td><select name = 'titleStyleAndWeight' multiple>" +
                    "<option>italic</option>" +
                    "<option>bold</option>" +
                    "</select></td></tr>" +

                    "<tr><td>Max, Records in Table: </td><td><select name = 'maxRecords'>" +
                    "<option>5</option>" +
                    "<option>10</option>" +
                    "</select></td></tr>" +
                    "<tr><td rowspan = '2'><input type = 'submit' value = 'Set'></td></tr>"

                    + "</table></form></body></html>");

        }

        @Override
        public void doPost(HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException{
            String maxRecords = request.getParameter("maxRecords");
            String[] titleStyleAndWeight = request.getParameterValues("titleStyleAndWeight");
            String titleFontSize = request.getParameter("titleFontSize");
            response.addCookie(new Cookie("maxRecords", maxRecords));
            response.addCookie(new Cookie("titleFontSize", titleFontSize));

            Cookie cookie = new Cookie("titleFontWeight", "");
            cookie.setMaxAge(0);
            response.addCookie(cookie);

            cookie = new Cookie("titleFontStyle", "");
            cookie.setMaxAge(0);
            response.addCookie(cookie);

            if(titleStyleAndWeight != null){
                for(String style: titleStyleAndWeight){
                    if(style.equals("bold")){
                        response.addCookie(new Cookie("titleFontWeight", "bold"));
                    }else if(style.equals("italic")){
                        response.addCookie(new Cookie("titleFontStyle", "italic"));
                    }

                }
            }

            response.setContentType("text/html");
            PrintWriter writer = response.getWriter();
            writer.println("<html><head></head><body>" +
                    MENU +
                    "Your preference has been set." +
                    "<br/><br/>Max. Record in Table: " + maxRecords +
                    "<br/>Title Font Size: " + titleFontSize +
                    "<br/>Title Font Style & Weight: ");

            if(titleStyleAndWeight != null){
                writer.println("<ul>");
                for(String style:titleStyleAndWeight){
                    writer.print("<li>" + style + "</li>");
                }
                writer.println("</ul>");
            }


                  writer.println("</body></html>");

        }

}

上面是一个生成设置Cookies的示例,
下面是两个使用Cookies的示例(分别是数量及字体)
 
 
package main.ServletStudy;

/**
 * Created by ehang on 2017/2/9.
 */

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(
        name = "CookieClassServlet",
        urlPatterns = {"/cookieClass"}
)
public class CookieClassServlet extends HttpServlet  {
    private static final long serialVersionUID = 837369L;

    private String[] methods = {
      "clone", "getComment", "getDomain",
            "getMaxAge", "getName", "getPath",
            "getSecure", "getValue", "getVersion",
            "isHttpOnly", "setComment", "setDomain",
            "setHttpOnly", "setMaxAge", "setPath",
            "setSecure", "setValue", "setVersion"
    };

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException{
        Cookie[] cookies = request.getCookies();
        Cookie maxRecordsCookie = null;
        if(cookies != null){
            for(Cookie cookie: cookies){
                if(cookie.getName().equals("maxRecords")){
                    maxRecordsCookie = cookie;
                    break;
                }
            }
        }

        int maxRecords = 5;
        if(maxRecordsCookie != null){
            try{
                maxRecords = Integer.parseInt(maxRecordsCookie.getValue());
            }catch(NumberFormatException e){
            }
        }

        response.setContentType("text/html");
        PrintWriter writer = response.getWriter();
        writer.println("<html><head><title>Cookie Class</title></head>" +
                PreferenceServlet.MENU +

                "<div>Here are some of the methods in javax.servlet.http.Cookie<ul>");

        for(int i = 0;i < maxRecords;i++){
            writer.print("<li>" + methods[i] + "</li>");
        }

         writer.print("</ul></div>" +
                "<body></body></html>");

    }

}

package main.ServletStudy;

/**
 * Created by ehang on 2017/2/9.
 */

import java.io.IOException;
import java.io.PrintWriter;
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;

@WebServlet(
        name = "CookieInfoServlet",
        urlPatterns = {"/cookieInfo"}
)
public class CookieInfoServlet extends HttpServlet {
    private static final long serialVersionUID = 3829L;

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException{
        Cookie[] cookies = request.getCookies();
        StringBuilder styles = new StringBuilder();
        styles.append(".title{");
        if(cookies != null){
            for(Cookie cookie: cookies){
                String name = cookie.getName();
                String value = cookie.getValue();

                if(name.equals("titleFontSize")){
                    styles.append("font-size:" + value + ";");
                }else if(name.equals("titleFontWeight")){
                    styles.append("font-weight:" + value + ";");
                }else if(name.equals("titleFontStyle")){
                    styles.append("font-style:" + value + ";");
                }

            }
        }
        styles.append("}");

        response.setContentType("text/html");
        PrintWriter writer = response.getWriter();
        writer.println("<html><head><title>Cookie Info</title><style>" +
                styles.toString() +
                "</style></head><body>" +
                PreferenceServlet.MENU +
                "<div class='title'>Session Management with Cookies:</div>" +
                "<div>");

        if(cookies == null){
            writer.print("No cookies in this HTTP response.");
        }else{
            writer.println("<br/>Cookies in this HTTP response:");
            for(Cookie cookie: cookies){
                writer.println("<br/>" + cookie.getName() + ":" + cookie.getValue());
            }
        }

         writer.print("</div></body></html>");

    }

}

都是进行状态数据传输的方法 Cookie的方法将记录状态的内容放在浏览器能够·看到的地方(Headers)
而session是将实际内容以对象的形式记录于内存中
下面是session的一个简单示例

package SessionStudy;

/**
 * Created by admin on 2017/2/14.
 */
import java.io.IOException;
import java.io.PrintWriter;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

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;


@WebServlet(
        name = "ShoppingCartServlet",
        urlPatterns = {
                "/products", "/viewProductDetails",
                "/addToCart", "/viewCart"
        }
)
public class ShoppingCartServlet extends HttpServlet {
        private static final long serialVersionID = -20L;
        private static final String CART_ATTRIBUTE = "cart";

        private List<Product> products = new ArrayList<>();
        private NumberFormat currencyForamt = NumberFormat.getCurrencyInstance(Locale.US);

        @Override
        public void init()throws ServletException{
                products.add(new Product(1, "Bravo 32' HDTV", "Low-cost HDTV from renowned TV manufacturer",
                        159.95F));
                products.add(new Product(2, "Bravo BluRay Player", "High quality stylish BluRay player", 99.95F));
                products.add(new Product(3, "Bravo Stereo System", "5 speaker hifi system with iPod player", 129.95F));
                products.add(new Product(4, "Bravo iPod player", "An iPod plug-in ", 39.95F));
        }

        @Override
        public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
                String uri = request.getRequestURI();
                if (uri.endsWith("/products")){
                        sendProductList(response);
                }else if(uri.endsWith("/viewProductDetails")){
                        sendProductDetails(request, response);
                }else if(uri.endsWith("viewCart")){
                        showCart(request, response);
                }
        }

        private void sendProductList(HttpServletResponse response)throws  IOException{
                response.setContentType("text/html");
                PrintWriter writer = response.getWriter();
                writer.println("<html><head><title>Products</title></head><body>" +
                        "<h2>Products</h2>" +
                        "<ul>" );
                for(Product product: products){
                        writer.println("<li>" + product.getName() + "(" + currencyForamt.format(product.getPrice()) +   ") ( " +
                                "<a href = 'viewProductDetails?id=" +product.getId() + "'>Details</a> ) </li>");
                }

                writer.println("</ul><a href = 'viewCart'>View Cart</a></body></html>");
        }

        private Product getProduct(int productId){
                for(Product product: products){
                        if(product.getId() == productId){
                                return product;
                        }
                }
                return null;
        }

        private void sendProductDetails(HttpServletRequest request, HttpServletResponse response) throws IOException{
                response.setContentType("text/html");
                PrintWriter writer = response.getWriter();
                int productId = 0;
                try{
                        productId = Integer.parseInt(request.getParameter("id"));
                }catch(NumberFormatException e){
                }

                Product product = getProduct(productId);

                if(product != null){
                        writer.println("<html><head><title>Product Details</title></head><body><h2>Product Details</h2>" +
                                "<form method = 'post' action = 'addToCart'>" +
                                "<input type = 'hidden' name = 'id' value = '" + productId +"'/>" +
                                "<table>" +
                                "<tr><td>Name:</td><td>" + product.getName() + "</td></tr>" +
                                "<tr><td>Descriptiom:</td><td>" + product.getDescription() +  "</td></tr>" +
                                "<tr><td><input name = 'quantity'/></td><td><input type='submit' value = 'Buy'/></td></tr>" +
                                "<tr><td colspan='2'><a href = 'products'>Products List</a></td></tr>" +
                                "</table></form></body></html>");
                }
                else{
                        writer.println("Mo product found");
                }


        }

        private void showCart(HttpServletRequest request, HttpServletResponse response)throws  IOException{
                response.setContentType("text/html");
                PrintWriter writer = response.getWriter();
                writer.println("<html><head><title>Shopping Cart</title></head><body>" +
                        "<a href = 'products'>Product List</a>");

                HttpSession session = request.getSession();
                List<ShoppingItem> cart = (List<ShoppingItem>) session.getAttribute(CART_ATTRIBUTE);
                if(cart != null){
                        writer.println("<table>" +
                                "<tr><td style = 'width:150px'>Product</td><td style = 'width:150px'>Price</td><td>Amount</td></tr>") ;
                        double total = 0.0;
                        for(ShoppingItem shoppingItem: cart){
                                Product product = shoppingItem.getProduct();
                                int quantity = shoppingItem.getQuantity();
                                if(quantity != 0){
                                        float price = product.getPrice();
                                        writer.println("<tr><td>" + quantity +"</td><td>" + product.getName() + "</td>" +
                                                "<td>"  + currencyForamt.format(price) + "</td>");
                                        double subtotal = price * quantity;
                                        writer.println("<td>" + currencyForamt.format(subtotal) + "</td>" +
                                                "</tr>");
                                        total += subtotal;
                                }
                        }

                        writer.println("<tr><td colspan='4' style = 'text-align:right'>" + "Total:" + currencyForamt.format(total) + "</td></tr>");

                        writer.println(
                        "</table>");
                }

                writer.println(
                        "</body></html>");


        }

        @Override
        public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
                int productId = 0;
                int quantity = 0;
                try{
                     productId = Integer.parseInt(request.getParameter("id"));
                     quantity = Integer.parseInt(request.getParameter("quantity"));
                }catch(NumberFormatException e){
                }

                Product product = getProduct(productId);
                if(product != null && quantity >= 0){
                        ShoppingItem shoppingItem = new ShoppingItem(product, quantity);
                        HttpSession session = request.getSession();
                        List<ShoppingItem> cart = (List<ShoppingItem>) session.getAttribute(CART_ATTRIBUTE);
                        if(cart == null){
                                cart = new ArrayList<ShoppingItem>();
                                session.setAttribute(CART_ATTRIBUTE, cart);
                        }
                        cart.add(shoppingItem);
                }
                sendProductList(response);

        }




}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值