一、首先创建实体类Product.java
然后生成set、get方法,有参的无参的构造方法
package entity;
public class Product {
int id;
String name;
String type;
double 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 getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
return "Product [id=" + id + ", name=" + name + ", type=" + type
+ ", price=" + price + "]";
}
public Product(int id, String name, String type, double price) {
super();
this.id = id;
this.name = name;
this.type = type;
this.price = price;
}
public Product() {
super();
// TODO Auto-generated constructor stub
}
}
二、创建dao文件ProductDao.java
为了方便起见,这里不读取数据库文件,直接用采用静态代码块的方法将数据加载到内存中,
然后设置查询所有商品信息方法和查询一件商品信息的方法
package dao;
import java.util.ArrayList;
import java.util.List;
import entity.Product;
public class ProductDao {
private static List<Product> data = new ArrayList<Product>();
static {
data.add(new Product(1, "神舟电脑", "电脑", 4500));
data.add(new Product(2, "oppor R9", "手机", 2400));
data.add(new Product(3, "方便面", "食品", 3.5));
data.add(new Product(4, "冰红茶", "饮料", 2));
data.add(new Product(5, "小米5", "手机", 1500));
data.add(new Product(6, "宝马", "汽车", 300000));
data.add(new Product(7, "绝味鸭脖", "食品", 50));
data.add(new Product(8, "iPhone7", "手机", 6000));
}
public List<Product> SelectAll(){
return data;
}
public Product select(int id){
for(Product d:data){
if(id==d.getId()){
return d;
}
}
return null;
}
}
三、创建servlet文件ProductList.java
该文件负责显示所有商品的列表信息,并且接收cookie,将最近浏览的商品id显示在本页面
为了测试功能实现,暂时只获取最近浏览过的一件商品id
package servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import dao.ProductDao;
import entity.Product;
public class ProductList extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
ProductDao dao=new ProductDao();
List<Product> list=dao.SelectAll();
String html="";
html+="<html>";
html+="<head>";
html+="<title>显示商品列表</title>";
html+="<body>";
html+="<table border='1' align='center' width='600px'>";
html+="<tr>";
html+="<th>编号</th><th>名称</th><th>类型</th><th>价格</th>";
html+="</tr>";
for (Product product : list) {
html+="<tr>";
html+="<td>"+product.getId()+"</td>"+"<td><a href="+request.getContextPath()+"/DetailServlet?id="+product.getId()+">"+product.getName()+"<a></td>"+"<td>"+product.getType()+"</td>"+"<td>"+product.getPrice()+"</td>";
html+="</tr>";
}
html+="</table>";
html+="</body>";
html+="</head>";
html+="</html>";
response.getWriter().write(html);
Cookie[] cookie = request.getCookies();
if (cookie != null) {
for (Cookie c : cookie) {
if(c.getName().equals("id")){
response.getWriter().write("最近访问的商品是:"+c.getValue());
}
}
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
四、创建商品详情页servlet文件DetailServlet.java
通过get传参方式拿到ProductList.java传递过来的id值,然后调用dao层select()方法获取商品信息
最后将商品id信息存储到cookie中并发送到浏览器(还是暂时只存储最近浏览的一个商品id)
package servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import dao.ProductDao;
import entity.Product;
public class DetailServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
int id = Integer.parseInt(request.getParameter("id"));
ProductDao dao = new ProductDao();
Product p = dao.select(id);
String html = "";
html += "<html>";
html += "<head>";
html += "<title>显示商品详情</title>";
html += "<body>";
html += "<table border='1' align='center' width='600px'>";
html += "<tr><th>编号</th><td>" + p.getId() + "</td></tr>";
html += "<tr><th>名称</th><td>" + p.getName() + "</td></tr>";
html += "<tr><th>类型</th><td>" + p.getType() + "</td></tr>";
html += "<tr><th>价格</th><td>" + p.getPrice() + "</td></tr>";
html += "</table>";
html += "<center><a href=" + request.getContextPath()
+ "/ProductList>[返回列表]</a></center>";
html += "</body>";
html += "</head>";
html += "</html>";
response.getWriter().write(html);
Cookie cook =new Cookie("id", request.getParameter("id"));
response.addCookie(cook);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
项目写到这可以基本完成所需功能,但是还是没能完成查看最近浏览的三件商品商品的功能,需要对两个servlet文件cookie部分的功能进行修改。
五、修改DetailServlet.java文件中cookie存储的算法,多个id值我们采用逗号分割,最后生成String类型数据发送到ProductList.java文件。修改后的文件如下:
package servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedList;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import dao.ProductDao;
import entity.Product;
public class DetailServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
int id = Integer.parseInt(request.getParameter("id"));
ProductDao dao = new ProductDao();
Product p = dao.select(id);
String html = "";
html += "<html>";
html += "<head>";
html += "<title>显示商品详情</title>";
html += "<body>";
html += "<table border='1' align='center' width='600px'>";
html += "<tr><th>编号</th><td>" + p.getId() + "</td></tr>";
html += "<tr><th>名称</th><td>" + p.getName() + "</td></tr>";
html += "<tr><th>类型</th><td>" + p.getType() + "</td></tr>";
html += "<tr><th>价格</th><td>" + p.getPrice() + "</td></tr>";
html += "</table>";
html += "<center><a href=" + request.getContextPath()
+ "/ProductList>[返回列表]</a></center>";
html += "</body>";
html += "</head>";
html += "</html>";
response.getWriter().write(html);
Cookie cook = new Cookie("id", createValue(request,request.getParameter("id")));
response.addCookie(cook);
}
private String createValue(HttpServletRequest request, String id) {
// 获取cookie中的id值
Cookie[] cookies = request.getCookies();
String prodHist = null;
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("id")) {
prodHist = cookie.getValue();
break;
}
}
}
// 情况一:如果之前没有访问,即 最近浏览的访问记录为空
if (cookies == null || prodHist == null) {
return id;// 直接返回传入的id
}
/*
* 其它情况下,即cookie中的id存在数据,不能直接添加新的数据,
* 需要对原来的cookie值的String类型进行转换,以方便对其进行操作 即String -> String[] ->
* Collection :为了方便判断重复id
*/
String[] ids = prodHist.split(",");
Collection colls = Arrays.asList(ids); // <3,21>
/*
* 为了方便地操作(增删改元素)需要将Collection类型进行转换 即为Collection -> LinkedList
*/
LinkedList list = new LinkedList(colls);
// 不超过3个
if (list.size() < 3) {
// 情况二:id小于三个且id重复,需要先去除重复id,然后把传入的id放最前面
if (list.contains(id)) {
list.remove(id);
list.addFirst(id);
} else {
// 情况三:id小于三个且id不重复,可以直接把传入的id放最前面
list.addFirst(id);
}
} else {// 等于3个
// 情况四:id等于三个且id重复,需要先去除重复id,然后把传入的id放最前面
if (list.contains(id)) {
list.remove(id);
list.addFirst(id);
} else {
// 情况五:id等于三个且id重复,需要先去除最后一个id,然后把传入的id放最前面
list.removeLast();
list.addFirst(id);
}
}
/*
* 最近浏览的id数据存储完成后,需要将数据类型进行转换 即将LinedList -> String
*/
StringBuffer sb = new StringBuffer();
for (Object object : list) {
sb.append(object + ",");
}
// 截取字符串,去掉最后的逗号
String result = sb.toString();
result = result.substring(0, result.length() - 1);
return result;
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
六、此时还需要修改ProductList.java文件,因为此时cookie中的id数据形如“2,5,3”,需要逗号分割
修改后的代码如下:
package servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import dao.ProductDao;
import entity.Product;
public class ProductList extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
ProductDao dao = new ProductDao();
List<Product> list = dao.SelectAll();
String html = "";
html += "<html>";
html += "<head>";
html += "<title>显示商品列表</title>";
html += "<body>";
html += "<table border='1' align='center' width='600px'>";
html += "<tr>";
html += "<th>编号</th><th>名称</th><th>类型</th><th>价格</th>";
html += "</tr>";
for (Product product : list) {
html += "<tr>";
html += "<td>" + product.getId() + "</td>" + "<td><a href="
+ request.getContextPath() + "/DetailServlet?id="
+ product.getId() + ">" + product.getName() + "<a></td>"
+ "<td>" + product.getType() + "</td>" + "<td>"
+ product.getPrice() + "</td>";
html += "</tr>";
}
html += "</table>";
html += "</body>";
html += "</head>";
html += "</html>";
response.getWriter().write(html);
Cookie[] cookie = request.getCookies();
if (cookie != null) {
for (Cookie c : cookie) {
if (c.getName().equals("id")) {
String prodHist = c.getValue(); // 3,2,1
String[] ids = prodHist.split(",");
response.getWriter().write("最近访问的商品是:"+"</br>");
for (String id : ids) {
// 显示到浏览器
response.getWriter().write(id+"</br>");
}
break;
}
}
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}