当前位置: 代码迷 >> Web前端 >> 深入体会JavaWeb开发内幕――使用Cookie模拟某网站向客户发出提示信息的应用
  详细解决方案

深入体会JavaWeb开发内幕――使用Cookie模拟某网站向客户发出提示信息的应用

热度:129   发布时间:2012-11-17 11:14:15.0
深入体验JavaWeb开发内幕――使用Cookie模拟某网站向客户发出提示信息的应用

       我们在访问某网站时,例如:购物网站、影视网站等这些网站在你登录时可能会向发出你最近购买的商品或观看过的影片等信息,那么这种效果是如何实现的呢?

具体效果如图:

当用户第一次登录该网站时:

   

浏览过某资源之后:

当你再次访问该网站时:

你还可以继续浏览那么下次再登录时还会做相似的提示:

相关代码实现:

一个用来封装Book对象的实体类

Book.java

package net.csdn.bookdomain;

public class Book {
   private String id;
   private String name;
   private String author;
   private String description;
public String getId() {
	return id;
}
public void setId(String id) {
	this.id = id;
}
public String getName() {
	return name;
}
public void setName(String name) {
	this.name = name;
}
public String getAuthor() {
	return author;
}
public void setAuthor(String author) {
	this.author = author;
}
public String getDescription() {
	return description;
}
public void setDescription(String description) {
	this.description = description;
}
   
   
}

一个封装了相应方法的接口

BookDao.java

package net.csdn.bookdao;

import java.util.List;

import net.csdn.bookdomain.Book;

public interface BookDao {
 public List<Book> getAllBook();
 public Book getBookDescription(String id);
}

一个封装了获取连接资源、和释放资源的工具类

DBManger.java

package net.csdn.bookutil;
import java.sql.*;
public class DBManager {
    static String url="jdbc:mysql://localhost:3306/book";
    static String user="root";
    static String password="root";
    static{
    	try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
    }
    
	public static Connection getConnection()throws SQLException{
		
		Connection con=DriverManager.getConnection(url, user, password);
		return  con;
	}
	
	public static void dbClose1(Statement st,Connection con){
		if(st!=null){
			try {
				st.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if(con!=null){
			try {
				con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void dbClose2(ResultSet rs,Statement st,Connection con){
		if(rs!=null){
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		dbClose1(st,con);
	}
	
}
一个对于BookDao的实现类BookDaoImpl.java

package net.csdn.bookdaoimpl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import net.csdn.bookdao.BookDao;
import net.csdn.bookdomain.Book;
import net.csdn.bookutil.DBManager;

public class BookDaoImpl implements BookDao {

	public List<Book> getAllBook() {
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet rs = null;

		try {
			con = DBManager.getConnection();
			String sql = "select bookId,bookName,bookAuthor,bookDescription from book";
			ps = con.prepareStatement(sql);
			rs = ps.executeQuery();
			List<Book> list = new ArrayList();
			while (rs.next()) {
				Book book = new Book();
				book.setId(rs.getInt("bookId") + "");
				book.setName(rs.getString("bookName"));
				book.setAuthor(rs.getString("bookAuthor"));
				book.setDescription(rs.getString("bookDescription"));
				list.add(book);
				
			}
			return list;

		} catch (SQLException e) {
             //必须为其声明返回值因为如果在try中出现了问题后它会找不到返回值
//			e.toString();
//			return null;
			throw new RuntimeException();
		} finally {
			DBManager.dbClose2(rs, ps, con);
		}

	}

	public Book getBookDescription(String id) {
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet rs = null;

		try {
			con = DBManager.getConnection();
			String sql = "select bookId,bookName,bookAuthor,bookDescription from book where bookId =?";
			ps = con.prepareStatement(sql);
			ps.setInt(1, Integer.valueOf(id));
			rs = ps.executeQuery();
			Book book = null;
			while (rs.next()) {
				 book = new Book();
				book.setId(rs.getInt("bookId") + "");
				book.setName(rs.getString("bookName"));
				book.setAuthor(rs.getString("bookAuthor"));
				book.setDescription(rs.getString("bookDescription"));
				
			}
			return book;
			}catch (SQLException e) {
	             //必须为其声明返回值因为如果在try中出现了问题后它会找不到返回值
				//System.out.println(e.toString());
//				return null;
				throw new RuntimeException(e);
			} finally {
				DBManager.dbClose2(rs, ps, con);
			}
	}
}

一个用来展示相关书籍的服务器类

ProductName.java

package net.csdn.controller;

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 net.csdn.bookdaoimpl.BookDaoImpl;
import net.csdn.bookdomain.Book;

public class ProductName extends HttpServlet {
    BookDaoImpl bdi = new BookDaoImpl();
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		out.println("请选择您要浏览的书名:"+"<br/>");
//		获取每一本书名
		List<Book> list = bdi.getAllBook();
		for(Book lists : list){
			out.print("<a href ='/BookDescription/ProductDescription?id="+lists.getId()+"' target = '_blank' >" 
+lists.getName()+"</a>"+"<br/>");
//			out.print("<a href ='' ">"+lists.getName()+"</a>"+"<br/>");
//		 "<a href ='/BookDescription?id="+lists.getId()+"'>" +lists.getName()+"</a>"+"<br/>";
		}
//		显示曾经浏览过的书
		out.println("您最近浏览过的图书:"+"<br/>");
		Cookie [] cookie = request.getCookies();
		for(int i=0;cookie!=null && i<cookie.length;i++){
			if(cookie[i].getName().equals("BrowseringHistory")){
				String [] ids = cookie[i].getValue().split(",");
				for(String id : ids ){
					Book book = bdi.getBookDescription(id);
				    out.print(book.getName()+"<br/>") ;
				}
//				String [] ids = ids.split(",");
			}
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
一个用来描述书籍相关信息的服务类:

ProductDescription.java

package net.csdn.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
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 net.csdn.bookdaoimpl.BookDaoImpl;
import net.csdn.bookdomain.Book;

public class ProductDescription extends HttpServlet {
    BookDaoImpl bdi = new BookDaoImpl();
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset = utf-8");
		PrintWriter out = response.getWriter();
//		显示每一本书的详细信息
		out.println("书籍详细信息:"+"<br/>");
		String id = request.getParameter("id");
		Book book = bdi.getBookDescription(id);
		out.println("Id:"+book.getId()+"<br/>");
		out.println("Name:"+book.getName()+"<br/>");
		out.println("Author:"+book.getAuthor()+"<br/>");
		out.println("Description:"+book.getDescription()+"<br/>");
//		将书号写入到cookie
		
		String cookieValue = getBrowseringHistroy(id,request);
		Cookie cookie = new Cookie("BrowseringHistory",cookieValue);
		cookie.setMaxAge(2*24*3600);
		cookie.setPath("/BookDescription");
		response.addCookie(cookie);

	}
//     获取cookie的返回值
	private String getBrowseringHistroy(String id, HttpServletRequest request) {
              String BrowseringHistroy = null;
              Cookie cookie [] = request.getCookies();
		for(int i=0;cookie!=null && i<cookie.length;i++){
			
			if(cookie[i].getName().equals("BrowseringHistory")){
				BrowseringHistroy = cookie[i].getValue();
			}
		}
		if(BrowseringHistroy == null){
			return id;
		}
		LinkedList<String> list = new LinkedList(Arrays.asList(BrowseringHistroy.split(",")));
		if(list.contains(id)){
			list.remove(id);
			list.addFirst(id);
		}else{
			if(list.size()>=3){
				list.removeLast();
				list.addFirst(id);
			}else{
				list.addFirst(id);
			}
		}
		StringBuffer sb = new StringBuffer();
		for(String cid : list){
			sb.append(cid+",");
		}
		return sb.deleteCharAt(sb.length()-1).toString();
//		return sb.substring(0,sb.length()-1 ).toString();
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
好了赶快自己动手创建一个数据库“book”再建一个相应的存放书籍的表“book”,去自己试一试这种效果吧!


  相关解决方案