需求:浏览商品(商品来自xml),可以查看商品详情,显示最近浏览的3个商品
项目结构:
xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<girls-list>
<girl id="1">
<name>小兰</name>
<price>3000</price>
<address>广西</address>
</girl>
<girl id="2">
<name>小菊</name>
<price>2500</price>
<address>湖南</address>
</girl>
<girl id="3">
<name>小美</name>
<price>4000</price>
<address>贵州</address>
</girl>
<girl id="4">
<name>小梅</name>
<price>3000</price>
<address>广东</address>
</girl>
</girls-list>
dao包:
GirlDao
public class GirlDao {
private GirlDao(){}
private List<Girl> list= new ArrayList<Girl>();
private static GirlDao dao = null;
public static GirlDao getInstance(){
if (dao==null){
dao = new GirlDao();
}
return dao;
}
public List<Girl> findAll(){
list.clear();
Document doc = XMLTool.getDocument();
List<Element> girlList = doc.getRootElement().elements("girl");
for (Element girlElem : girlList) {
Girl g = new Girl();
g.setId(girlElem.attributeValue("id"));
g.setName(girlElem.elementText("name"));
g.setPrice(Integer.parseInt(girlElem.elementText("price")));
g.setAddress(girlElem.elementText("address"));
list.add(g);
}
return list;
}
//返回指定id的Girl对象
public Girl findByID(String id){
for (Girl girl :list){
if (girl.getId().equals(id)){
return girl;
}
}
return null;
}
}
servlet包:
DetailGirlServlet
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//取出传递过来的编号
String id = request.getParameter("id");
GirlDao dao = GirlDao.getInstance();
Girl girl = dao.findByID(id);
if (girl!=null){
String content="";
response.setContentType("text/html;charset=utf-8");
content+="<html>";
content+="<body width=100px>";
content+="<ul align='center'>";
content+="<li style='list-style-type:none'>编号:"+girl.getId()+"</li>";
content+="<li style='list-style-type:none'>姓名:"+girl.getName()+"</li>";
content+="<li style='list-style-type:none'>价格:"+girl.getPrice()+"</li>";
content+="<li style='list-style-type:none'>地址:"+girl.getAddress()+"</li>";
content+="</ul>";
content+="<center><a href='"+request.getContextPath()+"/ListGirlServlet'>返回上一层</a></center>";
content+="</body>";
content+="</html>";
response.getWriter().write(content);
Cookie c = new Cookie("prodHist",getCookieValue(request,girl.getId()+""));
response.addCookie(c);
}
}
//获取完整的编号字符串(如"2,3,1")
private String getCookieValue(HttpServletRequest request,String id) {
Cookie[] cookies = request.getCookies();
String prodHist = null;
if(cookies!=null){
for (Cookie cookie : cookies) {
if(cookie.getName().equals("prodHist")){
//取出当前的编号字符串
prodHist = cookie.getValue();
break;
}
}
}
if(cookies==null || prodHist==null){
return id;
}
//拆分编号字符串
String[] prodHists = prodHist.split(",");
// String->Collection
Collection colls = Arrays.asList(prodHists);
// Collectoin->LinkedList(因为LinkedList便于添加删除)
LinkedList list = new LinkedList(colls);
if(list.size()<3){ //如果还没满3个记录
//如果id重复
if(list.contains(id)){
list.remove(id);
list.addFirst(id);
}else{
list.addFirst(id);
}
}else{ //如果满了3个记录,那么删除最久的一久访问记录
if(list.contains(id)){
list.remove(id);
list.addFirst(id);
}else{
list.removeLast();
list.addFirst(id);
}
}
//List->String
String str = "";
for (Object obj : list) {
str += obj+",";
}
//切莫把最后一个,也带进去
str = str.substring(0, str.length()-1);
return str;
}
ListGirlServlet
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
GirlDao dao = GirlDao.getInstance();
List <Girl>girlList = dao.findAll();
resp.setContentType("text/html;charset=utf-8");
String content = "";
resp.getWriter().write("");
content+="<html>";
content+="<body>";
content+="<table border=1 align='center' width='600px'>";
content+="<tr>";
content+="<th>编号</th><th>姓名</th><th>价格</th><th>地址</th>";
for (Girl girl :girlList){
content+="<tr>";
content+="<td>"+girl.getId()+"</td>";
content+="<td>"+girl.getName()+"</td>";
content+="<td>"+girl.getPrice()+"</td>";
content+="<td>"+girl.getAddress()+"</td>";
//把参数放到地址栏上,也相当于是使用GET方式提交的参数
content+="<td><a href='"+req.getContextPath()+"/DetailGirlServlet?id="+girl.getId()+"'>详情</a></td>";
content+="</tr>";
}
content+="</tr>";
content+="</table>";
content+="<hr/>最近浏览的3个商品<br/><br/>";
//把浏览器传来的cookie中的编号拿出来
Cookie[] cookies = req.getCookies();
if(cookies!=null){
for (Cookie cookie : cookies) {
if(cookie.getName().equals("prodHist")){
String prodHist = cookie.getValue();
String[] ids = prodHist.split(",");
for (String id : ids) {
Girl g = dao.findByID(id);
content += ""+g.getId()+" "+g.getName()+" "+g.getPrice()+" "+g.getAddress()+"<br/>";
}
break;
}
}
}
content+="</body>";
content+="</html>";
resp.getWriter().write(content);
}
util包:
XMLTool
public static Document getDocument(){
InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream("girls.xml");
try {
//Document doc = new SAXReader().read(new File("d:/girls.xml"));//new File("./src/girls.xml")
Document doc = new SAXReader().read(stream);//new File("./src/girls.xml")
return doc;
} catch (DocumentException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
public static void write2xml(Document doc){
try {
OutputStream out = new FileOutputStream("./src/girls.xml");
OutputFormat format = OutputFormat.createPrettyPrint();
XMLWriter writer = new XMLWriter(out,format);
writer.write(doc);
writer.close();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}