商品对象,购物车对象,servlet的实现

商品:

package app02d;
public class Product {
    private int id;
    private String name;
    private String description;
    private float price;
    
    public Product(int id, String name, String description, float price) {
        this.id = id;
        this.name = name;
        this.description = description;
        this.price = price;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public float getPrice() {
        return price;
    }

    public void setPrice(float price) {
        this.price = price;
    }
}

购物车:

package app02d;
public class ShoppingItem {

    private Product product;
    private int quantity;
    
    public ShoppingItem(Product product, int quantity) {
        this.product = product;
        this.quantity = quantity;
    }

    public Product getProduct() {
        return product;
    }

    public void setProduct(Product product) {
        this.product = product;
    }

    public int getQuantity() {
        return quantity;
    }

    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }
}
servlet的实现:

package app02d;

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;

/**
 * Servlet implementation class ShoppingCartServlet
 */
@WebServlet( name = "ShoppingCartServlet", urlPatterns = {"/products", "/viewProductDetails","/addToCart","/viewCart"})
public class ShoppingCartServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private static final String CART_ATTRIBUTE = "cart";
    
    private List<Product> products = new ArrayList<Product>();
    private NumberFormat currencyFormat = NumberFormat
            .getCurrencyInstance(Locale.US);
    
    // 创建商品对象,加入商品列表中(1)
    @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 that can play multiple formats",
                39.95F));
    }
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ShoppingCartServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * 分支(2)
     */
    protected 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);
        }
    }
    
    
    
    

    /**
     * addToCart
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // add to cart
        int productId = 0; // 商品id
        int quantity = 1; // 商品数量(默认购买一件)
        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);
            // 创建session对象
            HttpSession session = request.getSession();
            List<ShoppingItem> cart = (List<ShoppingItem>) session.getAttribute(CART_ATTRIBUTE);
            if (cart == null) {
                cart = new ArrayList<ShoppingItem>();
                // 设置session值
                session.setAttribute(CART_ATTRIBUTE, cart);
            }
            cart.add(shoppingItem);
        }
        sendProductList(response);
    }
    
    /**
     * 显示商品列表 (4)
     * @param response
     * @throws IOException
     */
    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>");
        writer.println("<ul>");
        for (Product product : products) {
            writer.println("<li>" + product.getName() + "("
                    + currencyFormat.format(product.getPrice())
                    // 商品详细信息的显示
                    + ") (" + "<a href='viewProductDetails?id="
                    + product.getId() + "'>Details</a>)");
        }
        writer.println("</ul>");
        writer.println("<a href='viewCart'>View Cart</a>");
        writer.println("</body></html>");

    }

    /**
     * 根据商品id获取商品对象
     * @param productId
     * @return
     */
    private Product getProduct(int productId) {
        for (Product product : products) {
            if (product.getId() == productId) {
                return product;
            }
        }
        return null;
    }

    /**
     * 获取商品的详细信息,并显示
     * @param request
     * @param response
     * @throws IOException
     */
    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'>");
            // 隐藏域
            writer.println("<input type='hidden' name='id' "
                    + "value='" + productId + "'/>");
            writer.println("<table>");
            writer.println("<tr><td>Name:</td><td>"
                    + product.getName() + "</td></tr>");
            writer.println("<tr><td>Description:</td><td>"
                    + product.getDescription() + "</td></tr>");
            writer.println("<tr>" + "<tr>"
                    // 购买的数量
                    + "<td><input name='quantity'/></td>"
                    + "<td><input type='submit' value='Buy'/>"
                    + "</td>"
                    + "</tr>");
            writer.println("<tr><td colspan='2'>"
                    + "<a href='products'>Product List</a>"
                    + "</td></tr>");
            writer.println("</table>");
            writer.println("</form></body>");
        } else {
            writer.println("No product found");
        }

    }

    /**
     * 显示购物车
     * @param request
     * @param response
     * @throws IOException
     */
    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>");
        writer.println("<body><a href='products'>" +
                "Product List</a>");
        // 创建session对象
        HttpSession session = request.getSession();
        // 获取session内容
        List<ShoppingItem> cart = (List<ShoppingItem>) session.getAttribute(CART_ATTRIBUTE);
        if (cart != null) {
            writer.println("<table>");
            writer.println("<tr><td style='width:150px'>Quantity"
                    + "</td>"
                    + "<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>");
                    writer.println("<td>" + quantity + "</td>");
                    writer.println("<td>" + product.getName()
                            + "</td>");
                    writer.println("<td>"
                            + currencyFormat.format(price)
                            + "</td>");
                    double subtotal = price * quantity;

                    writer.println("<td>"
                            + currencyFormat.format(subtotal)
                            + "</td>");
                    total += subtotal;
                    writer.println("</tr>");
                }
            }
            writer.println("<tr><td colspan='4' "
                    + "style='text-align:right'>"
                    + "Total:"
                    + currencyFormat.format(total)
                    + "</td></tr>");
            writer.println("</table>");
        }
        writer.println("</table></body></html>");
    }

}

servlet之session设置的更多相关文章

  1. Servlet 使Session设置失效

    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletExcep ...

  2. servlet的session为null?

    servlet的session(会话)显示为null,一般是web.xml中配置不对或者在浏览器输入的url不正确造成的. web.xml配置如下: <servlet> <servl ...

  3. struts2 笔记01 登录、常用配置参数、Action访问Servlet API 和设置Action中对象的值、命名空间和乱码处理、Action中包含多个方法如何调用

    Struts2登录 1. 需要注意:Struts2需要运行在JRE1.5及以上版本 2. 在web.xml配置文件中,配置StrutsPrepareAndExecuteFilter或FilterDis ...

  4. Web开发: servlet的session为null?

    servlet的session(会话)显示为null,一般是web.xml中配置不对或者在浏览器输入的url不正确造成的. web.xml配置如下: <servlet> <servl ...

  5. 笔记01 登录、常用配置参数、Action访问Servlet API 和设置Action中对象的值、命名空间和乱码处理、Action中包含多个方法如何调用

    Struts2登录 1. 需要注意:Struts2需要运行在JRE1.5及以上版本 2. 在web.xml配置文件中,配置StrutsPrepareAndExecuteFilter或FilterDis ...

  6. ActiveMQ中Session设置的相关理解

    名词解释: P:生产者 C:消费者 服务端:P 或者 ActiveMQ服务 客户端:ActiveMQ服务 或者 C 客户端成功接收一条消息的标志是这条消息被签收.成功接收一条消息一般包括如下三个阶段: ...

  7. putty字体大小颜色、全屏/退出全屏快捷键 保存session设置[转]

    字体大小设置 Window->Appearance->Font settings->Change按钮设置(我的设置为16)字体为(Consolas) 字体颜色设置 Window-&g ...

  8. cookie 和 session 设置

    cookie: 保存在浏览器上的一组键值对, 是由服务器让浏览器进行设置的 下次浏览器访问的时候会携带cookie. request是客户端请求, response是服务端响应. 读取客户端的cook ...

  9. IT兄弟连 JavaWeb教程 Servlet会话跟踪 设置Session存活时长

    方式一:修改所有的session默认时长,修改tomcat目录下的conf文件夹下的web.xml文件. <session-config> <session-timeout>希 ...

随机推荐

  1. JAVA连接SAP

    1.首先需要在SAP事务码SE37中新建一个可以被远程调用的RFC 事务码:SE37 新建一个函数组:输入事务码SE37回车后,来到函数构建器屏幕,到上面一排菜单栏:转到 -> 函数组 -> ...

  2. 对lua表中数据按一定格式处理,循环

    function putStartCard(handCard) function dataDeal(array,a,b,c) cclog("进入datadeal=============== ...

  3. 【Nginx系列】Nginx虚拟主机的配置核日志管理

    Nginx配置段 #user nobody; worker_processes 1;// 有1个工作的子进程,可以自行修改,但太大无益,因为要争夺CPU,一般设置为 CPU数*核数 #error_lo ...

  4. vue计算属性详解——小白速会

    一.什么是计算属性 模板内的表达式非常便利,但是设计它们的初衷是用于简单运算的.在模板中放入太多的逻辑会让模板过重且难以维护.例如: <div id="example"> ...

  5. beta冲刺5-咸鱼

    昨天的问题: 登陆页面的整合重新制作 各主机版本更迭 我的社团显示功能修改调整 主页的头部替换掉 +修复帖子无法显示内容的问题 +试着将邮箱等判定用正则表达式进行实时判定. 今天的完成: 主要是线下进 ...

  6. C语言第一次博客作业—输入输出

    一.PTA实验作业 题目1:7-3 温度转换 本题要求编写程序,计算华氏温度150°F对应的摄氏温度.计算公式:C=5×(F−32)/9,式中:C表示摄氏温度,F表示华氏温度,输出数据要求为整型. 1 ...

  7. 简易web服务器

    当通过Socket开发网络应用程序的时候,首先需要考虑所使用的网络类型,主要包括以下三个方面: 1)Socket类型,使用网络协议的类别,如IPv4的类型为PF_INET. 2)数据通信的类型,常见的 ...

  8. C语言——第二次作业(2)

    作业要求一 PTA作业的提交列表 作业要求二 题目1.删除字符串中数字字符(函数题) 1.设计思路 - (1)算法 第一步:调用定义的函数. 第二步:定义i=0.j=0,i为原字符数组角标,j为删除后 ...

  9. verilog学习笔记(4)_有限状态机

    有限状态机: 有限状态机是由寄存器组和组合逻辑构成的硬件时序电路: - 其状态(即由寄存器组的1和0的组合状态所构成的有限个状态)只能在同一时钟跳变沿的情况下才能从一个状态转向另一个状态: - 究竟转 ...

  10. python中 return 的用法

    return 语句就是讲结果返回到调用的地方,并把程序的控制权一起返回 程序运行到所遇到的第一个return即返回(退出def块),不会再运行第二个return. 要返回两个数值,写成一行即可: de ...