servlet之session设置
商品对象,购物车对象,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设置的更多相关文章
- Servlet 使Session设置失效
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletExcep ...
- servlet的session为null?
servlet的session(会话)显示为null,一般是web.xml中配置不对或者在浏览器输入的url不正确造成的. web.xml配置如下: <servlet> <servl ...
- struts2 笔记01 登录、常用配置参数、Action访问Servlet API 和设置Action中对象的值、命名空间和乱码处理、Action中包含多个方法如何调用
Struts2登录 1. 需要注意:Struts2需要运行在JRE1.5及以上版本 2. 在web.xml配置文件中,配置StrutsPrepareAndExecuteFilter或FilterDis ...
- Web开发: servlet的session为null?
servlet的session(会话)显示为null,一般是web.xml中配置不对或者在浏览器输入的url不正确造成的. web.xml配置如下: <servlet> <servl ...
- 笔记01 登录、常用配置参数、Action访问Servlet API 和设置Action中对象的值、命名空间和乱码处理、Action中包含多个方法如何调用
Struts2登录 1. 需要注意:Struts2需要运行在JRE1.5及以上版本 2. 在web.xml配置文件中,配置StrutsPrepareAndExecuteFilter或FilterDis ...
- ActiveMQ中Session设置的相关理解
名词解释: P:生产者 C:消费者 服务端:P 或者 ActiveMQ服务 客户端:ActiveMQ服务 或者 C 客户端成功接收一条消息的标志是这条消息被签收.成功接收一条消息一般包括如下三个阶段: ...
- putty字体大小颜色、全屏/退出全屏快捷键 保存session设置[转]
字体大小设置 Window->Appearance->Font settings->Change按钮设置(我的设置为16)字体为(Consolas) 字体颜色设置 Window-&g ...
- cookie 和 session 设置
cookie: 保存在浏览器上的一组键值对, 是由服务器让浏览器进行设置的 下次浏览器访问的时候会携带cookie. request是客户端请求, response是服务端响应. 读取客户端的cook ...
- IT兄弟连 JavaWeb教程 Servlet会话跟踪 设置Session存活时长
方式一:修改所有的session默认时长,修改tomcat目录下的conf文件夹下的web.xml文件. <session-config> <session-timeout>希 ...
随机推荐
- CSS 剩余宽度和高度完全填充
<html><head><meta http-equiv="Content-Type" content="text/html; charse ...
- Django--基本篇:项目结构与设计模式(MVC)
Django在项目开发中有着结构清晰.层次明显.容易编写理解查阅demo的优点,那么我们来个小案例具体看看. 一.项目结构简析: 我们按照上一篇中的开发流程步骤创建一个新项目myblog,项目下 ...
- 20155214&20155216 实验二:固件程序设计
---恢复内容开始--- 20155214&20155216 实验二:固件程序设计 实验内容及要求 实验二 固件程序设计-1-MDK 实验要求: 1.注意不经老师允许不准烧写自己修改的代码 2 ...
- 基于微信小程序的失物招领系统的Postmortem
基于微信小程序的失物招领系统的Postmortem 设想和目标 1.我们的软件要解决什么问题?是否定义得很清楚?是否对典型用户和典型场景有清晰的描述? 对于我们团队要解决的问题和实现的功能在项目开始就 ...
- vue.js下载及安装配置
环境 Deepin15.4 下载及配置 node下载地址:http://nodejs.cn/download/ 解压到文件夹 /home/maskerk/vue/ 下 设置软连接: $ ln -s / ...
- Linux 磁盘和文件管理系统 文件打包解压备份 VIM、VI编辑器
- SQL常用语句,随时用随时更新
更多详细说明文档查询 http://www.postgres.cn/docs/9.5/infoschema-columns.html 1.1通过表名查询表的属性 SELECT * FROM sys.s ...
- nyoj n-1位数
n-1位数 时间限制:3000 ms | 内存限制:65535 KB 难度:1 描述 已知w是一个大于10但不大于1000000的无符号整数,若w是n(n≥2)位的整数,则求出w的后n-1位的 ...
- Win10安装Ubuntu14.04.5双系统(显示器为DP接口)
系统安装主要参考了这篇博文Win10+Ubuntu17.04双系统安装,不再重复. 重点说说DP接口的事,如果主机有VGA接口的话可以到此为止了,如果只有DP接口的话可以参考以下内容. 一.Ubunt ...
- 多台linux主机之间建立免密通信
多台linux主机之间设置免密通信 例:A 向 B设置免密通信 第一步 A生成密钥对 ssh-keygen -t rsa -t 指定秘钥的类型 rsa 秘钥类型 密钥目录:/root/.ssh/(如果 ...