首先们实现此功能需要用到的架包有:c3p0-0.9.1.2jar;commons-dbutils-1.6.jar;jstl.jar;mysql-connector-java-5.1.38-bin.jar;standard.jar;
第一步;准备sql表单 ;
需要准备的表单有:book;root;users等等其它表单;这里就不一一列出了;主要看代码;
第二步;java代码
org.wenyuan.dao--BookDao.java
package org.wenyuan.dao;
import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.wenyuan.entity.Book;
import org.wenyuan.entity.BookPage;
import org.wenyuan.util.JdbcUtil;
public class BookDao {
public void insert(Book book) throws SQLException {
String sql = "insert into books values(null,?,?,?,?)";
ResultSetHandler rsh = new ResultSetHandler() {
@Override
public Object handle(ResultSet arg0) throws SQLException {
System.out.println("abc");
return null;
}
};
// ResultSetHandler<Long> rsh = new ScalarHandler<>();
Object r = JdbcUtil.qr.insert(sql, rsh, book.getName(),
book.getZuoze(), book.getPrice(), book.getRiqi());
// return r.intValue();
}
public void delete(int id) throws SQLException {
String sql = "delete from books where id=?";
JdbcUtil.qr.update(sql, id);
}
public void update(Book book) throws SQLException {
String sql = "update books set name=?,zuoze=?,price=?,riqi=? where id=?";
JdbcUtil.qr.update(sql, book.getName(), book.getZuoze(),
book.getPrice(), book.getRiqi(), book.getId());
}
public Book get(int id) throws SQLException {
String sql = "select * from books where id=?";
ResultSetHandler<Book> rsh = new BeanHandler<>(Book.class);
return JdbcUtil.qr.query(sql, rsh, id);
}
// public Book getAll(Book book) throws SQLException {
// String sql = "select * from books";
// ResultSetHandler<Book> rsh = new BeanHandler<>(Book.class);
// return JdbcUtil.qr.query(sql, rsh, book.getId(),book.getName(), book.getZuoze(),
// book.getPrice(), book.getRiqi());
// }
public List<Book> getAll() throws SQLException{
List<Book> books= new ArrayList<>();
String sql="select * from books";
MapListHandler rsh = new MapListHandler();
List<Map<String,Object>> list= JdbcUtil.qr.query(sql, rsh);
for(Map<String,Object>map:list){
books.add(mapToBook(map));
}
return books;
}
public Book mapToBook(Map<String, Object> map) {
Class c=Book.class;
Book book =null;
if(map.size()!=0){
book =new Book();
}
for(Map.Entry<String, Object>entry:map.entrySet()){
String fieldName = entry.getKey();
Object fieldValue = entry.getValue();
Field field = null;
try {
field = c.getDeclaredField(fieldName);
field.setAccessible(true);
try {
field.set(book, fieldValue);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
}
}
return book;
}
public void getPage(BookPage bp) throws SQLException{
String key =bp.getKey();
String zuoze =bp.getZuoze();
double minPrice=bp.getMinprice();
double maxPrice=bp.getMaxprice();
int pageNo =bp.getPageNo();
int pageSize =bp.getPageSize();
MapListHandler rsh = new MapListHandler();
//查数据
String sql1 = "select * from books "
+ "where (name like '%"+key+"%' or zuoze like '%"+key+"%') "
+ "and zuoze like '%"+zuoze+"%' "
+ "and price >=? and price <= ? limit ?,?";
System.out.println(pageNo);
List<Map<String,Object>> list = JdbcUtil.qr.query(sql1, rsh,minPrice,maxPrice,pageSize*(pageNo-1),pageSize);
List<Book> books =new ArrayList<Book>();
for (Map<String,Object> map:list) {
Book book =mapToBook(map);
books.add(book);
}
//查数量
String sql2 ="select count(*) from books "
+ "where (name like '%"+key+"%' or zuoze like '%"+key+"%') "
+ "and zuoze like '%"+zuoze+"%' "
+ "and price >=? and price <= ?";
ScalarHandler<Long> rsh2 =new ScalarHandler<>();
Long count = JdbcUtil.qr.query(sql2,rsh2,minPrice,maxPrice);
int maxPageNo;
if (count%pageSize==0) {
maxPageNo=(int) (count/pageSize);
} else {
maxPageNo=(int) (count/pageSize+1);
}
//设置数据
bp.setBooks(books);
bp.setMaxPagNo(maxPageNo);
}
}
org.wenyuan.dao--UserDao.java
package org.wenyuan.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.wenyuan.entity.User;
import org.wenyuan.util.JdbcUtil;
public class UserDao {
public User login(String userName,String userPwd) throws SQLException {
Connection conn = JdbcUtil.getConnection();
String sql = "select yhname,pwd from users where yhname=? and pwd=?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, userName);
ps.setString(2, userPwd);
ResultSet rs = ps.executeQuery();
User u = null;
if(rs.next()){
u = new User(rs.getString(1),rs.getString(2));
}
rs.close();
ps.close();
conn.close();
return u;
}
}
org.wenyuan.entity--Book.java
package org.wenyuan.entity;
import java.util.Date;
public class Book {
private int id;
private String name;
private String zuoze;
private double price;
private Date riqi;
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 getZuoze() {
return zuoze;
}
public void setZuoze(String zuoze) {
this.zuoze = zuoze;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public Date getRiqi() {
return riqi;
}
public void setRiqi(Date riqi) {
this.riqi = riqi;
}
public Book(int id, String name, String zuoze, double price, Date riqi) {
super();
this.id = id;
this.name = name;
this.zuoze = zuoze;
this.price = price;
this.riqi = riqi;
}
public Book(String name, String zuoze, double price, Date riqi) {
super();
this.name = name;
this.zuoze = zuoze;
this.price = price;
this.riqi = riqi;
}
public Book() {
super();
}
@Override
public String toString() {
return "Book [id=" + id + ", name=" + name + ", zuoze=" + zuoze
+ ", price=" + price + ", riqi=" + riqi + "]";
}
}
org.wenyuan.entity--BookPage.java
package org.wenyuan.entity;
import java.util.ArrayList;
import java.util.List;
public class BookPage {
// 搜索信息
private String key;
private String zuoze;
private double minprice;
private double maxprice;
// 页面信息
private int pageNo;
private int pageSize;
private int maxPagNo;
// 数据
private List<Book> books = new ArrayList<>();
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getZuoze() {
return zuoze;
}
public void setZuoze(String zuoze) {
this.zuoze = zuoze;
}
public double getMinprice() {
return minprice;
}
public void setMinprice(double minprice) {
this.minprice = minprice;
}
public double getMaxprice() {
return maxprice;
}
public void setMaxprice(double maxprice) {
this.maxprice = maxprice;
}
public int getPageNo() {
return pageNo;
}
public void setPageNo(int pageNo) {
this.pageNo = pageNo;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getMaxPagNo() {
return maxPagNo;
}
public void setMaxPagNo(int maxPagNo) {
this.maxPagNo = maxPagNo;
}
public List<Book> getBooks() {
return books;
}
public void setBooks(List<Book> books) {
this.books = books;
}
public BookPage(String key, String zuoze, double minprice, double maxprice,
int pageNo, int pageSize, int maxPagNo, List<Book> books) {
super();
this.key = key;
this.zuoze = zuoze;
this.minprice = minprice;
this.maxprice = maxprice;
this.pageNo = pageNo;
this.pageSize = pageSize;
this.maxPagNo = maxPagNo;
this.books = books;
}
public BookPage(String key, String zuoze, double minprice, double maxprice,
int pageNo, int pageSize) {
super();
this.key = key;
this.zuoze = zuoze;
this.minprice = minprice;
this.maxprice = maxprice;
this.pageNo = pageNo;
this.pageSize = pageSize;
}
public BookPage() {
super();
}
}
org.wenyuan.entity--User.java
package org.wenyuan.entity;
public class User {
private String yhname;
private String pwd;
public String getYhname() {
return yhname;
}
public void setYhname(String yhname) {
this.yhname = yhname;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public User(String yhname, String pwd) {
super();
this.yhname = yhname;
this.pwd = pwd;
}
public User() {
super();
}
}
org.wenyuan.serlvet--AllFilter.java
package org.wenyuan.serlvet;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.wenyuan.entity.User;
import org.wenyuan.service.UserService;
/**
* Servlet Filter implementation class AllFilter
*/
@WebFilter("/BookServket/*")
public class AllFilter implements Filter {
/**
* Default constructor.
*/
public AllFilter() {
}
/**
* @see Filter#destroy()
*/
public void destroy() {
}
/**
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest r = (HttpServletRequest) request;
HttpServletResponse p = (HttpServletResponse) response;
User u = (User) r.getSession().getAttribute("user");
if (u== null) {
p.sendRedirect(r.getContextPath() + "/index.jsp");
return;
}
chain.doFilter(request, response);
}
/**
* @see Filter#init(FilterConfig)
*/
public void init(FilterConfig fConfig) throws ServletException {
}
}
org.wenyuan.serlvet--BookServlet.java
package org.wenyuan.serlvet;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;
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;
import org.wenyuan.entity.Book;
import org.wenyuan.entity.BookPage;
import org.wenyuan.entity.User;
import org.wenyuan.service.BookService;
import org.wenyuan.util.DataUtil;
import com.mysql.jdbc.StringUtils;
/**
* Servlet implementation class BookServlet
*/
@WebServlet("/BookServlet/*")
public class BookServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public BookServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @param methodName
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// 获取请求的地址
String requestURI = request.getRequestURI();
// 截取地址作为方法名
String fun = requestURI.substring(requestURI.lastIndexOf("/") + 1);
Method method;
try {
method = this.getClass().getDeclaredMethod(fun,
HttpServletRequest.class, HttpServletResponse.class);
method.invoke(this, request, response);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
public void submit(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
String token = (String) session.getAttribute("code");
String vCode = request.getParameter("vCode");
System.out.println(token);
if (!vCode.equalsIgnoreCase(token)) {
response.sendRedirect(request.getContextPath() + "/info.jsp");
return;
}
if (token != null) {
// 移除验证码
session.removeAttribute("code");
// 取出用户输入的信息
// request.setCharacterEncoding("utf-8");
// response.setCharacterEncoding("utf-8");
String id = request.getParameter("id");
String name = request.getParameter("name");
String zuoze = request.getParameter("zuoze");
String price = request.getParameter("price");
String riqi = request.getParameter("date");
Date birth = DataUtil.testStringToDate(riqi);
// 创建对象
Book book = new Book(name, zuoze, Double.parseDouble(price), birth);
if (id != null) {
book.setId(Integer.parseInt(id));
}
// 插入对象
new BookService().insertOrUpdate(book);
// 重定向到显示所有图书的信息页面
response.sendRedirect(request.getContextPath() + "/index.jsp");
// response.sendRedirect("BookServlet/getAll?key=&zuoze=&minPrice=&maxPrice=&pageNo=1&pageSize=60");
}
}
public void delete(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 取出要删除的id
String id = request.getParameter("id");
// 删除
new BookService().delete(Integer.parseInt(id));
// 重定向到所有图书页面
HttpSession s = request.getSession();
User user = (User) s.getAttribute("user");
if (user == null) {
response.sendRedirect(request.getContextPath()+"/denglu.jsp");
} else {
response.sendRedirect(request.getContextPath() + "/index.jsp");
}
}
public void update(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 获取请求参数
String strId = request.getParameter("id");
// 查询要更新的图书
Book book = new BookService().get(Integer.parseInt(strId));
System.out.println(book);
// 放入请求域中
request.setAttribute("book", book);
HttpSession s = request.getSession();
User user = (User) s.getAttribute("user");
if (user == null) {
response.sendRedirect(request.getContextPath()+"/denglu.jsp");
} else {
request.getRequestDispatcher("/m.jsp").forward(request, response);
}
}
public void getAll(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 搜索信息
String key = request.getParameter("key");
String zuoze = request.getParameter("zuoze");
String minPrice = request.getParameter("minPrice");
String maxPrice = request.getParameter("maxPrice");
// 价格是否是默认价格
if (StringUtils.isNullOrEmpty(minPrice)) {
minPrice = "0";
}
if (StringUtils.isNullOrEmpty(maxPrice)) {
maxPrice = Double.MAX_VALUE + "";
}
// 页面信息
String pageNo = request.getParameter("pageNo");
String pageSize = request.getParameter("pageSize");
// 封装一个查询条件的对象
BookPage bp = new BookPage(key, zuoze, Double.parseDouble(minPrice),
Double.parseDouble(maxPrice), Integer.parseInt(pageNo),
Integer.parseInt(pageSize));
// 查询数据
new BookService().getPage(bp);
// // 获取所有的对象
// List<Book> books = new BookService().getAll();
// 把图书放到请求域中
request.setAttribute("books", bp);
// 转发到jsp显示
request.getRequestDispatcher("/all.jsp").forward(request, response);
}
}
org.wenyuan.serlvet--Check.java
package org.wenyuan.serlvet;
import java.io.IOException;
import java.util.LinkedHashSet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.wenyuan.entity.Book;
import org.wenyuan.service.BookService;
/**
* Servlet implementation class Check
*/
@WebServlet("/Check")
public class Check extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Check() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String id = request.getParameter("id");
Book book = new BookService().get(Integer.parseInt(id));
//存入cookie的信息
String bookInfo =book.getName()+"-"+book.getId();
//用于存放所有的浏览记录
LinkedHashSet<String> cookieInfos = new LinkedHashSet<>();
cookieInfos.add(bookInfo);
Cookie[] cookies = request.getCookies();
if(cookies!=null) {
for(Cookie cookie:cookies) {
if(cookie.getName().startsWith("book")) {
cookieInfos.add(cookie.getValue());
}
}
}
// System.out.println("cookieInfos:"+cookieInfos);
//记录浏览记录
int count=1;
for(String cookieInfo:cookieInfos) {
Cookie c = new Cookie("book"+(count++),cookieInfo);
c.setPath("/");
c.setMaxAge(3600);
response.addCookie(c);
if(count>5) {
break;
}
}
request.setAttribute("book", book);
// 转发
request.getRequestDispatcher("/check.jsp").forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
}
}
org.wenyuan.serlvet--
org.wenyuan.serlvet--Deng.java
package org.wenyuan.serlvet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.wenyuan.entity.User;
import org.wenyuan.service.UserService;
/**
* Servlet implementation class Deng
*/
@WebServlet("/Deng")
public class Deng extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Deng() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("yhname");
String pwd = request.getParameter("pwd");
User u = new UserService().user(username, pwd);
System.out.println(u);
if (u != null) {