您的位置:首页 > 大数据 > 人工智能

ee_15_mvc_db_page----demo---bai

2017-01-08 14:54 393 查看
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>

<body>
<form action="BookServlet?op=add" method="post">
书名:   <input name="bname"/><br/>
价格: <input name="price"/> <br/>
作者: <input name="author"/> <br/>
页码: <input name="pagecount"/> <br/>
<input type="submit" value="添加"/>
</form>
</body>
</html>


  

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'update.jsp' starting page</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->

</head>

<body>
<form action="BookServlet?op=update" method="post">
编号: <input name="bid" value="${book.bid }" readonly="readonly"/> <br/>
书名:   <input name="bname" value="${book.bname }"/><br/>
价格: <input name="price" value="${book.price }"/> <br/>
作者: <input name="author" value="${book.author }"/> <br/>
页码: <input name="pagecount" value="${book.pagecount }"/> <br/>
<input type="submit" value="提交">
</form>
</body>
</html>


  

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core"  prefix="c" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'showlist.jsp' starting page</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->

</head>

<body onload="showok(${canshow},'${msg}')">
<script>
function showok(canshow,msg)
{
if(canshow)
alert(msg);
}
function confirm_delete(bid)
{
if(window.confirm("确定删除编号为"+bid+"的书吗?"))
{
window.location.href = "BookServlet?op=delete&bid="+bid;
}
}
</script>
<table border="1">
<tr>
<th>
编号
</th>
<th>
书名
</th>
<th>
价格
</th>
<th>
操作
</th>
</tr>
<c:set var="i" value="0"/>
<c:forEach items="${list}" var="book">
<c:set var="i" value="${i+1}"/>
<tr>
<td>
${book.bid }
</td>
<td>
${book.bname }
</td>
<td>
${book.price }
</td>
<td>
<a href="javascript:confirm_delete(${book.bid})">删除</a>

<a href="BookServlet?op=toupdate&bid=${book.bid}">修改</a>
</td>
</tr>

</c:forEach>

</table>
一共有${i}本书。
<br/>
<a href="add.jsp">重新录入</a>
</body>
</html>


  

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core"  prefix="c" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'showlist.jsp' starting page</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->

</head>

<body onload="showok(${canshow},'${msg}')">
<script>
function showok(canshow,msg)
{
if(canshow)
alert(msg);
}
function confirm_delete(bid)
{
if(window.confirm("确定删除编号为"+bid+"的书吗?"))
{
window.location.href = "BookServlet?op=delete&bid="+bid;
}
}
</script>
<table border="1">
<tr>
<th>
编号
</th>
<th>
书名
</th>
<th>
价格
</th>
<th>
操作
</th>
</tr>
<c:set var="i" value="0"/>
<c:forEach items="${pm.list}" var="book">
<c:set var="i" value="${i+1}"/>
<tr>
<td>
${book.bid }
</td>
<td>
${book.bname }
</td>
<td>
${book.price }
</td>
<td>
<a href="javascript:confirm_delete(${book.bid})">删除</a>

<a href="BookServlet?op=toupdate&bid=${book.bid}">修改</a>
</td>
</tr>

</c:forEach>

</table>
一共有${i}本书。
<br/>
<a href="BookServlet?op=findbypage&pageno=1&pagesize=5">首页</a>
<a href="BookServlet?op=findbypage&pageno=${pm.pageno+1}&pagesize=5">下一页</a>
<a href="BookServlet?op=findbypage&pageno=${pm.pageno-1}&pagesize=5">上一页</a>
<a href="BookServlet?op=findbypage&pageno=${pm.totalpage}&pagesize=5">末页</a>
<br/>
<a href="add.jsp">重新录入</a>
</body>
</html>


  

package com.etc.model.entity;

public class Book
{
private int bid;
private String bname;
private float price;
private String author; //作者
private int pagecount; //页码

public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public int getPagecount() {
return pagecount;
}
public void setPagecount(int pagecount) {
this.pagecount = pagecount;
}
public int getBid() {
return bid;
}
public void setBid(int bid) {
this.bid = bid;
}
public String getBname() {
return bname;
}
public void setBname(String bname) {
this.bname = bname;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public Book(int bid, String bname, float price, String author, int pagecount) {
super();
this.bid = bid;
this.bname = bname;
this.price = price;
this.author = author;
this.pagecount = pagecount;
}

}


  

package com.etc.model.entity;

import java.util.ArrayList;
import java.util.List;

//分页的数据。对于实体对象的分页封装,必须新增分页的信息
//T为泛型参数
public class PageModel<T>
{
//分页的数据,用数组来保存!
private List<T> list= new ArrayList<T>();

//2个重要的分页参数
private int pagesize; //每页有几条
private int pageno; //第几页,从1开始

//3 总记录数
private int totalcount;

//4 总页码数
private int totalpage;

public List<T> getList() {
return list;
}

public void setList(List<T> list) {
this.list = list;
}

public int getPagesize() {
return pagesize;
}

public void setPagesize(int pagesize) {
this.pagesize = pagesize;
}

public int getPageno() {
return pageno;
}

public void setPageno(int pageno) {
this.pageno = pageno;
}

public int getTotalcount() {

return totalcount;
}

public void setTotalcount(int totalcount) {
this.totalcount = totalcount;
}

//根据pagesize和总记录数,自动算出总页面数
public int  Totalpage()
{
if(totalcount%pagesize==0) //整除
totalpage = totalcount/pagesize;
else //不整除
totalpage = totalcount/pagesize+1;
return totalpage;
}
}


  

package com.etc.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.etc.model.biz.BookBiz;
import com.etc.model.entity.Book;
import com.etc.model.entity.PageModel;

public class BookServlet extends HttpServlet {

/**
* Constructor of the object.
*/
public BookServlet() {
super();
}

/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}

/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

doPost(request,response);
}

/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
//所有mvc请求的统一入口
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//1 对请求参数进行解码
request.setCharacterEncoding("utf-8");
//2 对响应进行编码(偶尔也需要用servlet直接响应html-出错了)
response.setContentType("text/html;charset=utf-8");
//3 读取op参数
String op = request.getParameter("op");

//4 根据op的不同处理具体的不同请求
if("add".equals(op))
{
add(request,response); //添加
}
else if("findall".equals(op))
{
findall(request,response);//查询全部书
}
else if("delete".equals(op))
{
delete(request,response);//删除书
}
else if("toupdate".equals(op))
{
toupdate(request,response);//进入修改页面
}
else if("update".equals(op))
{
update(request,response);//执行修改
}
else if("findbypage".equals(op))  //新增,执行分页查询
{
findByPage(request,response);
}
}

private void update(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{

//1 读取参数
int bid = Integer.parseInt(request.getParameter("bid"));
String bname = request.getParameter("bname");
float price = Float.parseFloat(request.getParameter("price"));
String author = request.getParameter("author");
int pagecount = Integer.parseInt(request.getParameter("pagecount"));

//2 调用模型
Book book = new Book(bid, bname, price, author, pagecount);
BookBiz biz = new BookBiz();
if(biz.update(book))
{

//3 派发视图
//通过本地js实现信息提示并重新发起请求
String html = "<html><body><script>alert('修改成功!');window.location.href='BookServlet?op=findall';</script></body></html>";
response.getWriter().print(html);
}
else
{
String html = "<html><body>修改失败!<a href='history.back()'>返回</a></body></html>";
response.getWriter().print(html);
}
}

//进入修改页面
private void toupdate(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
//1 读取请求参数
int bid  = Integer.parseInt(request.getParameter("bid"));
//2 调用模型
BookBiz biz = new BookBiz();
Book book = biz.findByBid(bid);
//3 派发视图
//在作用域保存数据
request.setAttribute("book", book);
//转发
request.getRequestDispatcher("update.jsp").forward(request, response);
}

// 执行删除
private void delete(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
//1 读取请求参数
int bid  = Integer.parseInt(request.getParameter("bid"));
//2 调用模型
BookBiz biz = new BookBiz();
if(biz.delete(bid))
{
//3 派发视图
//通过本地js实现信息提示并重新发起请求
String html = "<html><body><script>alert('删除成功!');window.location.href='BookServlet?op=findall';</script></body></html>";
response.getWriter().print(html);
}
else
{
String html = "<html><body>删除失败!<a href='history.back()'>返回</a></body></html>";
response.getWriter().print(html);
}

}

//查询全部
private void findall(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
//1 读取请求参数,无需
//2 调用模型
BookBiz biz = new BookBiz();
List<Book> list = biz.findAll();

//3 派发视图
if(list!=null) //查询成功
{
//作用域保存数据
request.setAttribute("list", list);
request.setAttribute("canshow", false);
request.setAttribute("msg", "");
request.getRequestDispatcher("showlist.jsp").forward(request, response);
}
else //失败
{
String html = "<html><body>查询失败!<a href='history.back()'>返回</a></body></html>";
response.getWriter().print(html);
}
}

//查询指定页码
private void findByPage(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
//1 读取请求参数,
int pageno = Integer.parseInt(request.getParameter("pageno"));
int pagesize = Integer.parseInt(request.getParameter("pagesize"));
//2 调用模型
BookBiz biz = new BookBiz();
PageModel<Book> pm = biz.findByPage(pageno,pagesize);

//3 派发视图
if(pm!=null) //查询成功
{
//作用域保存数据
request.setAttribute("pm", pm);
request.setAttribute("canshow", false);
request.setAttribute("msg", "");
request.getRequestDispatcher("showlist.jsp").forward(request, response);
}
else //失败
{
String html = "<html><body>查询失败!<a href='history.back()'>返回</a></body></html>";
response.getWriter().print(html);
}
}

//处理add的请求
private void add(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
//1 读取请求参数
String bname = request.getParameter("bname");
float price = Float.parseFloat(request.getParameter("price"));
String author = request.getParameter("author");
int pagecount = Integer.parseInt(request.getParameter("pagecount"));

//2 调用模型
//创建模型-实体bean
Book book = new Book(-1, bname, price,author,pagecount);
BookBiz biz = new BookBiz();
if(biz.add(book)) //成功,那么???
{
//3 派发视图
//转发到"查询全部"的请求命令
request.getRequestDispatcher("BookServlet?op=findall").forward(request, response);

}
else //失败
{
String html = "<html><body>添加失败!<a href='javascript:history.back()'>返回</a></body></html>";
response.getWriter().print(html);
}
}

/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}

}


  

package com.etc.model.biz;

import java.util.List;

import com.etc.model.dao.BookDao;
import com.etc.model.entity.Book;
import com.etc.model.entity.PageModel;
//业务bean,实现具体的业务逻辑
public class BookBiz
{
private BookDao dao = new BookDao();
//添加书,返回是否成功
public boolean add(Book book) //添加书,返回是否添加成功!
{
//靠dao对象来实现具体的数据库操作
return dao.add(book);
}

//查询全部的数
public List<Book> findAll()
{
//靠dao对象来实现具体的数据库操作
return dao.findAll();
}
//删除书,返回是否成功
public boolean delete(int bid) //删除书,返回是否添加成功!
{
//靠dao对象来实现具体的数据库操作
return dao.delete(bid);
}
//查询指定 编号的书,用于进入修改页面
public Book findByBid(int bid)
{
return dao.findByBid(bid);
}

//修改书,返回是否成功
public boolean update(Book book) //修改书,返回是否添加成功!
{
//靠dao对象来实现具体的数据库操作
return dao.update(book);
}
//查找第n页的书
public PageModel<Book> findByPage(int pageno,int pagesize)
{
return dao.findByPage(pageno, pagesize);
}
}


  

package com.etc.model.dao;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import com.etc.model.entity.Book;
import com.etc.model.entity.PageModel;
import com.etc.utils.JDBCUtil;

//实现所有数据库的操作
public class BookDao {
//实现书的添加!返回是否成功!
public  boolean add(Book book)
{
//通过jdbc工具类来实现添加
String sql = "insert into book(bname,price,author,pagecount) "
+" values(?,?,?,?)";
String[] ps = {book.getBname(),book.getPrice()+"",book.getAuthor(),book.getPagecount()+""};
return JDBCUtil.doUpdate(sql, ps)==1;
}
//实现书的删除!返回是否成功!
public  boolean delete(int bid)
{
//通过jdbc工具类来实现添加
String sql = "delete from book where bid=?";
String[] ps = {bid+""};
return JDBCUtil.doUpdate(sql, ps)==1;
}

//实现书的全部查询
public List<Book> findAll()
{
List<Book> list = new ArrayList<Book>();

String sql = "select * from book";
ResultSet rs = JDBCUtil.doQuery(sql);
try {
//依次遍历记录
while (rs.next()) {
//读取每条记录的字段值
int bid = rs.getInt("bid");
String bname = rs.getString("bname");
float price = rs.getFloat("price");
String author = rs.getString("author");
int pagecount = rs.getInt("pagecount");
//创建对象并添加到数组中
list.add(new Book(bid, bname, price, author, pagecount));
}
} catch (Exception e) {
return null;
}
finally
{
JDBCUtil.close(rs);
}
return list;
}
//实现指定 编号的书的查询
public Book findByBid(int bid)
{
Book book = null;

String sql = "select * from book where bid = ?";
String[] ps = {bid+""};
ResultSet rs = JDBCUtil.doQuery(sql,ps);
try {
//依次遍历记录
if (rs.next()) {
//读取每条记录的字段值
String bname = rs.getString("bname");
float price = rs.getFloat("price");
String author = rs.getString("author");
int pagecount = rs.getInt("pagecount");
//创建对象并添加到数组中
book = new Book(bid, bname, price, author, pagecount);
}
else //找不到,返回空
return null;
} catch (Exception e) {
return null;
}
finally
{
JDBCUtil.close(rs);
}
return book;
}
//实现书的修改!返回是否成功!
public  boolean update(Book book)
{
//通过jdbc工具类来实现添加
String sql = "update book set bname=?,price=?,author=?,pagecount=? where bid=?";
String[] ps = {book.getBname(),book.getPrice()+"",book.getAuthor(),book.getPagecount()+"",book.getBid()+""};
return JDBCUtil.doUpdate(sql, ps)==1;
}
//获得书本的总的记录数
private int getTotalCount()
{
String sql = "select count(1) as t from book";

ResultSet rs = JDBCUtil.doQuery(sql);
try {
//依次遍历记录
rs.next();
return rs.getInt("t"); //返回记录数
} catch (Exception e) {
return -1;
}
finally
{
JDBCUtil.close(rs);
}
}
//实现指定页面数的书的查询
public PageModel<Book> findByPage(int pageno,int pagesize)
{
List<Book> list = new ArrayList<Book>();

String sql = "select * from book limit "+
pagesize*(pageno-1)+","+pagesize;
//设置起点和条数
ResultSet rs = JDBCUtil.doQuery(sql);
try {
//依次遍历记录
while (rs.next()) {
//读取每条记录的字段值
int bid = rs.getInt("bid");
String bname = rs.getString("bname");
float price = rs.getFloat("price");
String author = rs.getString("author");
int pagecount = rs.getInt("pagecount");
//创建对象并添加到数组中
list.add(new Book(bid, bname, price, author, pagecount));
}
PageModel<Book> pm = new PageModel<Book>();
pm.setList(list); //该页装载的记录数
pm.setPageno(pageno); //页面数
pm.setPagesize(pagesize); //每页有几条
int count = getTotalCount();//获得总的记录数
pm.setTotalcount(count); //总的记录数
return pm;
} catch (Exception e) {
return null;
}
finally
{
JDBCUtil.close(rs);
}
}

}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: