javabean servlet jsp

package cn.jbit.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class BaseDao {
	// 连接字符串
	private final static String CONNECTIONSTRING = "jdbc:sqlserver://127.0.0.1:1433;databaseName=lib";
	private Connection connection;
	private ResultSet rs;
	private PreparedStatement pstmt;

	// 获取连接
	private  void getConnection() {
		try {
			Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
			connection = DriverManager.getConnection(CONNECTIONSTRING, "sa",
					"sa");
		} catch (Exception e) {
			System.out.println(e);
		}
	}

	/**
	 * 获取查询结果集
	 * @param sql
	 *            要查询的sql
	 * @param objs参数列表
	 * @return ResultSet结果集
	 */
	public ResultSet getResultSet(String sql, Object[] objs) {
		try {
			getConnection();
			pstmt = connection.prepareStatement(sql);
			for (int i = 0; i < objs.length; i++) {
				pstmt.setObject(i + 1, objs[i]);
			}

			return pstmt.executeQuery();
		} catch (SQLException e) {
			System.out.println(e);
		}
		return null;
	}

	/**
	 * 执行增删改操作
	 * @param sql
	 *            要执行的sql语句
	 * @param objs
	 *            参数列表
	 * @return
	 */
	public int excuteUpdate(String sql, Object[] objs) {
		getConnection();
		try {
			pstmt = connection.prepareStatement(sql);
			for (int i = 0; i < objs.length; i++) {
				pstmt.setObject(i + 1, objs[i]);// 参数设置从1开始
			}
			return pstmt.executeUpdate();
		} catch (SQLException e) {
			return -1;
		}
	}

	// 释放连接
	public void close() {
		try {
			if (rs != null) {
				rs.close();
			}
			if (pstmt != null) {
				pstmt.close();
			}
			if (connection != null) {
				pstmt.close();
			}
		} catch (SQLException e) {
			System.out.println(e);
		}
	}

}

package cn.jbit.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import cn.jbit.entity.BookInfo;
import cn.jbit.util.Page;

import com.sun.org.apache.regexp.internal.recompile;


public class BookInfoDao extends BaseDao   {
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

	/**
	 * 分页查询 列表信息
	 * 
	 * @param page
	 *            分页信息
	 * @param bookName
	 *            条件
	 * @return 结果集
	 */
	public List<BookInfo> getListByList(Page page, String bookName) {
		try {
			StringBuffer sb = new StringBuffer();
			List parm = new ArrayList();// 参数集合
			// 构建查询语句
			sb.append("	select * from (	select *,ROW_NUMBER() over (order by bid) as r from Book where 1=1 ");
			if (bookName != null && !bookName.isEmpty()) {
				sb.append(" and bName like ? ");
				parm.add("%" + bookName + "%");
			}

			sb.append(")	 as t ");
			// 查询总条数
			ResultSet rs = getResultSet(
					"select count(1) from  (" + sb.toString() + ") as tt",
					parm.toArray());
			if (rs.next()) {
				int count = rs.getInt(1);
				if (count < 1) {
					return null;
				}
				page.setCount(count);
			} else {
				return null;
			}
			close();//释放资源
			sb.append("  where t.r>? and t.r<?");
			parm.add((page.getCurentPage() - 1) * page.getPageSize());// 设置分页参数
			parm.add(page.getCurentPage() * page.getPageSize());// 设置分页参数
			rs = getResultSet(sb.toString(), parm.toArray());
			if (rs != null) {
				List<BookInfo> list = new ArrayList<BookInfo>();
				BookInfo book;
				while (rs.next()) {
					// 使用构造函数进行赋值
					book = new BookInfo(rs.getInt(1), rs.getString(2),
							rs.getInt(3), rs.getString(4), rs.getString(5),rs.getString(6));
					list.add(book);// 添加到集合

				}
				close();// 释放资源
				return list;// 返回数据
			}
		} catch (SQLException e) {
			System.out.println(e);
		}
		return null;

	}

	/**
	 * 通过id查询
	 * 
	 * @param id
	 *            id
	 * @return 查询到的结果
	 */
	public BookInfo getByid(String id) {
	
		String sql = "select * from book where bid= ?";
		ResultSet rs = getResultSet(sql, new Object[] { id });
		BookInfo book = null;
		try {
			if (rs.next()) {
				book = new BookInfo(rs.getInt(1), rs.getString(2),
						rs.getInt(3), rs.getString(4), rs.getString(5),rs.getString(6));
			}
			close();
			return book;
		} catch (SQLException e) {
		}
		return null;
	}

	/**
	 * 保存
	 * 
	 * @param book
	 */
	public void save(BookInfo book) {
		String sql = "INSERt INTO BOOK VALUES(?,?,?,?,?)";
		int count = excuteUpdate(
				sql,
				new Object[] {book.getName(),book.getPrice(),book.getCategory(),book.getDate(),book.getLoan() });// 设置参数

	}

	/**
	 * 更新
	 * 
	 * @param book
	 */
	public void update(BookInfo book) {
		String sql = "update  BOOK  set bName=? ,bprice=?,bcategory=? ,bdate=? ,bloan=? where bid=?";
		int count = excuteUpdate(
				sql,
				new Object[] {book.getName(),book.getPrice(),book.getCategory(),book.getDate(),book.getLoan(),book.getId() });// 设置参数

	}
	// 保存或者更新
		public void saveorUpdate(BookInfo book) {
		
			if(book.getId()==null){
				 save(book);// 如果id为空那么就是新增
			}else{
				 update(book);// 如果id不为空就是更新
				
			}
			
		}
}

package cn.jbit.entity;

import sun.print.resources.serviceui;

public class BookInfo {
	private Integer id;// id
	private String name;// 图书名称
	private int price;// 图书价格
	private String category;//图书类别
	private String date;// 出版日期
	private String loan;// 是否有库存
	
	
	
	
	public BookInfo() {
		super();
	}
	public BookInfo(Integer id, String name, int price, String category,
			String date, String loan) {
		super();
		this.id = id;
		this.name = name;
		this.price = price;
		this.category = category;
		this.date = date;
		this.loan = loan;
	}

	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getPrice() {
		return price;
	}
	public void setPrice(int price) {
		this.price = price;
	}
	public String getCategory() {
		return category;
	}
	public void setCategory(String category) {
		this.category = category;
	}
	public String getDate() {
		return date;
	}
	public void setDate(String date) {
		this.date = date;
	}
	public String getLoan() {
		return loan;
	}
	public void setLoan(String loan) {
		this.loan = loan;
	}
	
}

package cn.jbit.servlet;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

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 sun.java2d.pipe.SpanShapeRenderer.Simple;

import cn.jbit.dao.BookInfoDao;
import cn.jbit.entity.BookInfo;
import cn.jbit.util.Page;

@WebServlet(name = "bookServlet", urlPatterns = "/bookServlet")
public class BookServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		BookInfoDao bs = new BookInfoDao();// 获取服务
		String oper = req.getParameter("oper");// 获取操作
		if (oper != null && oper.equals("edit")) {// 若是是要去修改
			BookInfo book = bs.getByid(req.getParameter("id"));// 通过id获取到信息
			req.setAttribute("book", book);
			req.getRequestDispatcher("edit.jsp").forward(req, resp);// 跳转到修改页面
			return;
		} else if (oper != null && oper.equals("save")) {// 如是是保存
			Integer id = null;// id
			if (req.getParameter("id") != null
					&& !req.getParameter("id").trim().isEmpty()) {
				id = Integer.valueOf(req.getParameter("id").trim());
			}
			String name = req.getParameter("name").trim();// 图书名称
			int price = Integer.valueOf(req.getParameter("price").trim());// 图书价格
			String category = req.getParameter("category").trim();// 图书类别
			String date = req.getParameter("date").trim();// 出版日期
			String loan = req.getParameter("loan").trim();// 是否有库存
			BookInfo book = new BookInfo(id, name, price, category, date, loan);
			bs.saveorUpdate(book);// 保存或者更新
			req.setAttribute("name", book.getName());// 设置更新后的查询条件为更新后的值
		}
		List<BookInfo> books = new ArrayList<BookInfo>();
		Page page = new Page();// 分页信息
		String curentPage = req.getParameter("cp");// 获取要显示的页码
		if (curentPage != null && !curentPage.isEmpty()) {
			page.setCurentPage(Integer.valueOf(curentPage));
		}
		String bookName = req.getParameter("name");// 获取查询条件
		if (bookName != null) {
			bookName = bookName.trim();
		}
		books = bs.getListByList(page, bookName);// 获取查询到集合
		req.setAttribute("books", books);
		req.setAttribute("page", page);// 设置分页信息
		req.setAttribute("name", bookName);// 回显分页条件
		req.getRequestDispatcher("index.jsp").forward(req, resp);// 跳转到列表页面

	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);// 执行get方法
	}
}

package cn.jbit.util;

public class Page {

	private int totalPage;// 总页数
	private int pageSize = 10;// 分页大小
	private int curentPage = 1;// 默认当前页吗
	private int perverPage;// 上一页
	private int nextPage;// 下一页
	private int count;// 总记录数

	public int getTotalPage() {
		return totalPage;
	}

	public void setTotalPage(int totalPage) {
		this.totalPage = totalPage;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public int getCurentPage() {
		return curentPage;
	}

	public void setCurentPage(int curentPage) {
		this.curentPage = curentPage;
	}

	public int getPerverPage() {
		return perverPage;
	}

	public void setPerverPage(int perverPage) {
		this.perverPage = perverPage;
	}

	public int getNextPage() {
		return nextPage;
	}

	public void setNextPage(int nextPage) {
		this.nextPage = nextPage;
	}

	public int getCount() {
		return count;
	}

	public void setCount(int count) {
		// 计算页数高深算法哈哈
		this.totalPage = (count - 1 + pageSize) / pageSize;

		//计算下一页
		if (totalPage == curentPage) {
			nextPage = curentPage;
		} else {
			nextPage = curentPage + 1;
		}
		// 计算上一页数
		if (curentPage == 1) {
			perverPage = 1;
		} else {
			perverPage = curentPage - 1;
		}
		this.count = count;
	}
}

<%@ 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>图书列表</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>
<script type="text/javascript" src="jquery-1.8.3.min.js"></script>
<script type="text/javascript">
	$(function() {
		$("tr:odd").css("background", "pink");

	});
	function serarch(page) {
		$("#cp").val(page);
		$("form")[0].submit();
	}
</script>
<body>
	<h1>图书管理系统</h1>
	<br>
	<form action="bookServlet" onsubmit="serarch(1)" method="post">
		<input type="hidden" value="${page.curentPage }" name="cp" id="cp">
		请输入书名:<input type="text" name="name" value="${name} " /> <input
			type="submit" value="查询">
	</form>
	<table border="1">
		<tr style="font-weight: bold;">
			<td>图书编号</td>
			<td>图书名称</td>
			<td>图书价格</td>
			<td>图书类别</td>
			<td>出版日期</td>
			<td>是否有库存</td>
		</tr>

		<c:forEach items="${books}" var="b" varStatus="s">
			<tr>
				<td><a href="bookServlet?oper=edit&id=${b.id}"><c:out value="${b.id}"></c:out></a>
				</td>
				<td> <c:out
							value="${b.name}"></c:out> 
				</td>
				<td><c:out value="${b.price}"></c:out>
				</td>
				<td><c:out value="${b.category}"></c:out>
				</td>
				<td><c:out value="${b.date}"></c:out>
				</td>
				<td><c:out value="${b.loan}"></c:out>
				</td>
			</tr>
		</c:forEach>
		
	</table>
	<table>
	<tr >
			<td><a href="javascript:serarch(1)">首页</a>|
			</td>
			<td><a href="javascript:serarch(${page.perverPage })">上一页</a>|
			</td>
			<td><a href="javascript:serarch(${page.nextPage })">下一页</a>|
			</td>
			<td><a href="javascript:serarch(${page.totalPage })">尾页</a>
			</td>
			<td><a>第<c:out value="${page.curentPage } "></c:out>页/ 共<c:out
						value="${page.totalPage } "></c:out>页(共<c:out
						value="${page.count } "></c:out>条)</a>
			</td>

		</tr>
	</table>
</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>图书列表</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>
<script type="text/javascript" src="jquery-1.8.3.min.js"></script>
<script type="text/javascript">
$(function (){
	$("#name").blur(function (){
		if($("#name").val().length<1){
			$("#name").parent().next().css("display","");
		}else{
			$("#name").parent().next().css("display","none");
		}
	});
	$("#category").blur(function (){
		if($("#category").val().length<1){
			$("#category").parent().next().css("display","");
		}else{
			$("#category").parent().next().css("display","none");
		}
	});
	
	$("#date").blur(function (){
		var reg =/^\d{4}-\d{2}-\d{2}$/;
		var b=reg.test($.trim( $("#date").val()));
		if(b){
			$("#date").parent().next().css("display","none");
		}else{
			$("#date").parent().next().css("display","");
		}
	});
	$("#price").blur(function (){
		var reg =/^\d+$/;
		var b=reg.test($("#price").val());
		if($("#price").val()<1||$("#price").val()>500){
			b=false;
		}
		
		if(b){
			$("#price").parent().next().css("display","none");
		}else{
			$("#price").parent().next().css("display","");
		}
	});
	$("#r").click(function (){
		$("form")[0].reset();
		$("span").parent() .css("display","none");
	});
	 
	
	
	
});
	function check(){
		var a=$("td:hidden").size();
		if(a!=5){
			alert("信息不完整");
			return false;			
		}
		 return true;

	 
	}
	 
</script>
<body>
	<h1>修改图书信息</h1>
	<form action="bookServlet" onsubmit=" return check()" method="post">
		<input type="hidden" value="${book.id }" name="id"> <input
			type="hidden" value="save" name="oper">
		<table border="1">
			<tr>
				<td>图书名称</td>
				<td><input type="text" value="${book.name}" id="name"
					name="name">
				</td>
				<td style="display:none;"><span style="color:red ">图书名称不能为空</span>
				</td>
			</tr>
			<tr>
				<td>图书价格</td>
				<td><input type="text" value="${book.price}" id="price"
					name="price">
				</td>
				<td style="display: none;"><span style="color:red ">必须为整数1--500</span>
				</td>
			</tr>
			<tr>
				<td>图书类别</td>
				<td><input type="text" value="${book.category} " id="category"
					name="category"></td>
				<td style="display: none;"><span style="color:red ">图书类别不能为空</span>
				</td>
			</tr>
			<tr>
				<td>出版日期</td>
				<td><input type="text" value="${book.date}" id="date"
					name="date"></td>
				<td style="display: none;"><span style="color:red ">格式必须为yyyy-MM-dd</span>
				</td>
			</tr>
			<tr>
				<td>是否有库存</td>
				<td><c:if test="${book.loan ==‘有‘}"></c:if> <input type="radio"
					name="loan" value="有"
					<c:if test="${book.loan ==‘有‘}">checked="checked"</c:if>> 有
					  <input type="radio" name="loan" value="无"
					<c:if test="${book.loan ==‘无‘}">checked="checked"</c:if>> 无
					 
				<td style="display: none;"></td>
			</tr>
			<tr>
			<td colspan="3" style="text-align: center;"><input type="submit" value="保存">     <input type="button" id="r" value="重置"></td>
			 
			</tr>
		</table>
		
	</form>
</body>
</html>

USE [master]
GO
/****** Object:  Database [lib]    Script Date: 01/15/2014 10:24:01 ******/
CREATE DATABASE [lib] ON  PRIMARY 
( NAME = N‘lib‘, FILENAME = N‘E:\web2\lib.mdf‘ , SIZE = 3072KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )
 LOG ON 
( NAME = N‘lib_log‘, FILENAME = N‘E:\web2\lib_log.ldf‘ , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)
GO
ALTER DATABASE [lib] SET COMPATIBILITY_LEVEL = 100
GO
IF (1 = FULLTEXTSERVICEPROPERTY(‘IsFullTextInstalled‘))
begin
EXEC [lib].[dbo].[sp_fulltext_database] @action = ‘enable‘
end
GO
ALTER DATABASE [lib] SET ANSI_NULL_DEFAULT OFF
GO
ALTER DATABASE [lib] SET ANSI_NULLS OFF
GO
ALTER DATABASE [lib] SET ANSI_PADDING OFF
GO
ALTER DATABASE [lib] SET ANSI_WARNINGS OFF
GO
ALTER DATABASE [lib] SET ARITHABORT OFF
GO
ALTER DATABASE [lib] SET AUTO_CLOSE OFF
GO
ALTER DATABASE [lib] SET AUTO_CREATE_STATISTICS ON
GO
ALTER DATABASE [lib] SET AUTO_SHRINK OFF
GO
ALTER DATABASE [lib] SET AUTO_UPDATE_STATISTICS ON
GO
ALTER DATABASE [lib] SET CURSOR_CLOSE_ON_COMMIT OFF
GO
ALTER DATABASE [lib] SET CURSOR_DEFAULT  GLOBAL
GO
ALTER DATABASE [lib] SET CONCAT_NULL_YIELDS_NULL OFF
GO
ALTER DATABASE [lib] SET NUMERIC_ROUNDABORT OFF
GO
ALTER DATABASE [lib] SET QUOTED_IDENTIFIER OFF
GO
ALTER DATABASE [lib] SET RECURSIVE_TRIGGERS OFF
GO
ALTER DATABASE [lib] SET  DISABLE_BROKER
GO
ALTER DATABASE [lib] SET AUTO_UPDATE_STATISTICS_ASYNC OFF
GO
ALTER DATABASE [lib] SET DATE_CORRELATION_OPTIMIZATION OFF
GO
ALTER DATABASE [lib] SET TRUSTWORTHY OFF
GO
ALTER DATABASE [lib] SET ALLOW_SNAPSHOT_ISOLATION OFF
GO
ALTER DATABASE [lib] SET PARAMETERIZATION SIMPLE
GO
ALTER DATABASE [lib] SET READ_COMMITTED_SNAPSHOT OFF
GO
ALTER DATABASE [lib] SET HONOR_BROKER_PRIORITY OFF
GO
ALTER DATABASE [lib] SET  READ_WRITE
GO
ALTER DATABASE [lib] SET RECOVERY FULL
GO
ALTER DATABASE [lib] SET  MULTI_USER
GO
ALTER DATABASE [lib] SET PAGE_VERIFY CHECKSUM
GO
ALTER DATABASE [lib] SET DB_CHAINING OFF
GO
EXEC sys.sp_db_vardecimal_storage_format N‘lib‘, N‘ON‘
GO
USE [lib]
GO
/****** Object:  Table [dbo].[Book]    Script Date: 01/15/2014 10:24:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Book](
	[bid] [int] IDENTITY(1,1) NOT NULL,
	[bName] [varchar](30) NOT NULL,
	[bprice] [int] NOT NULL,
	[bcategory] [varchar](100) NOT NULL,
	[bdate] [varchar](100) NULL,
	[bloan] [varchar](2) NOT NULL,
 CONSTRAINT [PK_Book] PRIMARY KEY CLUSTERED 
(
	[bid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Check [CK_Book]    Script Date: 01/15/2014 10:24:02 ******/
ALTER TABLE [dbo].[Book]  WITH CHECK ADD  CONSTRAINT [CK_Book] CHECK  (([bprice]>=(1) OR [bprice]<=(500)))
GO
ALTER TABLE [dbo].[Book] CHECK CONSTRAINT [CK_Book]
GO
/****** Object:  Check [CK_Book_1]    Script Date: 01/15/2014 10:24:02 ******/
ALTER TABLE [dbo].[Book]  WITH CHECK ADD  CONSTRAINT [CK_Book_1] CHECK  (([bloan]=‘有‘ OR [bloan]=‘无‘))
GO
ALTER TABLE [dbo].[Book] CHECK CONSTRAINT [CK_Book_1]
GO

declare @i int =1
while(@i<33)
begin
INSERt INTO BOOK VALUES(‘name‘+CAST(@i as varchar (4)),@i,‘计算机‘,CAST(getdate() as varchar(20)),‘有‘)
set @i+=1
end


update Book set bdate=‘2013-10-12‘

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。