Javabean servlet jsp

Source: Internet
Author: User

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 {// Connection String private final static String CONNECTIONSTRING = "jdbc: sqlserver: // 127.0.0.1: 1433; databaseName = lib"; private connection Connection; private ResultSet rs; private PreparedStatement pstmt; // get the connection private void getC Onnection () {try {Class. forName ("com. microsoft. sqlserver. jdbc. SQLServerDriver "); connection = DriverManager. getConnection (CONNECTIONSTRING, "sa", "sa");} catch (Exception e) {System. out. println (e );}} /*** obtain the query result set * @ param SQL * the SQL statement to be queried * @ param objs parameter list * @ return ResultSet result set */public ResultSet getResultSet (String SQL, object [] objs) {try {getConnection (); pstmt = connection. prepareStatement (SQL); (Int I = 0; I <objs. length; I ++) {pstmt. setObject (I + 1, objs [I]);} return pstmt.exe cuteQuery ();} catch (SQLException e) {System. out. println (e);} return null ;} /*** run the add, delete, modify, and @ param SQL * SQL statement * @ param objs * parameter list * @ 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]); // parameter settings start from 1} return pstmt.exe cuteUpdate ();} catch (SQLException e) {return-1 ;}} // release the 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 "); /*** query List information by page ** @ param page * page information * @ param bookName * condition * @ return result set */public List
 
  
GetListByList (Page page, String bookName) {try {StringBuffer sb = new StringBuffer (); List parm = new ArrayList (); // set of parameters // construct the query statement 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"); // query the total number of results. 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 (); // release resource sb. append ("where t. r>? And t. r
  List = new ArrayList
  
   
(); BookInfo book; while (rs. next () {// use the constructor to assign book = new BookInfo (rs. getInt (1), rs. getString (2), rs. getInt (3), rs. getString (4), rs. getString (5), rs. getString (6); list. add (book); // add to set} close (); // release resource return list; // return data} catch (SQLException e) {System. out. println (e);} return null;}/*** query result by id ** @ param id * @ return */public BookInfo getByid (String id) {String SQL = "select * from bo OK 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 ;} /*** save ** @ 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 ()}); // set the parameter}/*** update ** @ 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 ()}); // set parameters} // save or update public void saveorUpdate (BookInfo book) {if (book. getId () = null) {save (book); // If the id is null, it is added} else {update (book ); // If the id is not empty, update it }}}
  
 

Package cn. jbit. entity; import sun. print. resources. serviceui; public class BookInfo {private Integer id; // idprivate String name; // book name private int price; // book price private String category; // book category private String date; // publication date private String loan; // whether there is inventory 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; imp Ort 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; @ Overrideprotected void doGet (HttpServletRequest req, httpServletResponse resp) throws ServletException, IOExcep Tion {req. setCharacterEncoding ("UTF-8"); BookInfoDao bs = new BookInfoDao (); // get the service String Signature = req. getParameter ("parameter"); // obtain the operation if (response! = Null & found. equals ("edit") {// if it is to modify BookInfo book = bs. getByid (req. getParameter ("id"); // obtain the information req by id. setAttribute ("book", book); req. getRequestDispatcher ("edit. jsp "). forward (req, resp); // jump to the modify page return;} else if (response! = Null & amp; parameters. equals ("save") {// if it is to save Integer id = null; // idif (req. getParameter ("id ")! = Null &&! Req. getParameter ("id "). trim (). isEmpty () {id = Integer. valueOf (req. getParameter ("id "). trim ();} String name = req. getParameter ("name "). trim (); // book name int price = Integer. valueOf (req. getParameter ("price "). trim (); // book price String category = req. getParameter ("category "). trim (); // book category String date = req. getParameter ("date "). trim (); // publication date String loan = req. getParameter ("loan "). trim (); // whether there is inventory BookInfo book = new BookInfo (id, name, price, category, date, loan); bs. saveorUpdate (book); // save or update req. setAttribute ("name", book. getName (); // set the updated query condition to the updated value} List
 
  
Books = new ArrayList
  
   
(); Page page = new Page (); // Page information String curentPage = req. getParameter ("cp"); // obtain the page number to be displayed if (curentPage! = Null &&! CurentPage. isEmpty () {page. setCurentPage (Integer. valueOf (curentPage);} String bookName = req. getParameter ("name"); // obtain the query condition if (bookName! = Null) {bookName = bookName. trim ();} books = bs. getListByList (page, bookName); // obtain the req set queried. setAttribute ("books", books); req. setAttribute ("page", page); // sets the page information req. setAttribute ("name", bookName); // display the paging condition req. getRequestDispatcher ("index. jsp "). forward (req, resp); // jump to the List page} @ Overrideprotected void doPost (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet (req, resp ); // execute the get method }}
  
 

Package cn. jbit. util; public class Page {private int totalPage; // total number of pages private int pageSize = 10; // Page size private int curentPage = 1; // default current Page private int perverPage; // previous private int nextPage; // next private int count; // total number of records 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) {// Advanced page calculation algorithm Haha this. totalPage = (count-1 + pageSize)/pageSize; // calculate the next page if (totalPage = curentPage) {nextPage = curentPage;} else {nextPage = curentPage + 1 ;} // calculate the number of previous pages 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 + "/"; %>Book list
 
 
 
 
 
 <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>Library Management System
Book No. Book name Book Price Book category Publication date Inventory?
Homepage | Previous Page | Next page | Last page The Page/Total Page (total Items)

<% @ 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 + "/"; %>Book list
 
 
 
 
 
 <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" pai.parent().next().css ("display", "");} else {$ ("# name" 2.16.parent().next().css ("display ", "none") ;}}); $ ("# category "). blur (function () {if ($ ("# category "). val (). length <1) {$ ("# category" ).parent().next().css ("display", "");} else {$ ("# cat Egory "pai.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" pai.parent().next().css ("display", "none ");} else {$ ("# date" pai.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" pai.parent().next().css ("display", "none");} else {$ ("# price" 2.16.parent().next().css ("display ", "") ;}}); $ ("# r "). click (function () {$ ("form") [0]. reset (); $ ("span "). parent (). css ("display", "none") ;}); function check () {var a =$ ("td: hidden "). size (); if (! = 5) {alert ("incomplete information"); return false;} return true ;}</script>Modify book information

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 = 2048 GB, FILEGROWTH = 10%) goalter database [lib] SET COMPATIBILITY_LEVEL = 100 GOIF (1 = FULLTEXTSERVICEPROPERTY ('isfulltextinstalled') beginEXEC [lib]. [dbo]. [sp_fulltext_database] @ action = 'enable' endGOALTER DATABASE [lib] SET offline offgoalter database [lib] SET ANSI_NULLS offgoalter database [lib] SET ANSI_PADDING offgoalter database [lib] SET ANSI_WARNINGS offgoalter database [lib] set arithabort offgoalter database [lib] SET AUTO_CLOSE offgoalter database [lib] SET policongoalter DATABASE [lib] SET AUTO_SHRINK offgoalter database [lib] SET AUTO_UPDATE_STATISTICS ongoalter database [lib] SET limit OFFGOALTER DATABASE DATABASE [lib] SET CURSOR_DEFAULT globalgoalter database [lib] SET offline offgoalter database [lib] SET NUMERIC_ROUNDABORT offgoalter database [lib] SET QUOTED_IDENTIFIER offgoalter database [lib] SET offline offgoalter database [lib] SET DISABLE_BROKERGOALTER DATABASE [lib] SET parameter offgoalter database [lib] SET DATE_CORRELATION_OPTIMIZATION offgoalter database [lib] set trustworthy offgoalter database [lib] SET parameter offgoalter database [lib] set parameterization simplegoalter database [lib] SET READ_COMMITTED_SNAPSHOT offgoalter database [lib] SET offline offgoalter database [lib] SET READ_WRITEGOALTER DATABASE [lib] set recovery fullgoalter database [lib] SET MULTI_USERGOALTER DATABASE [lib] SET PAGE_VERIFY checkgoalter DATABASE [lib] SET DB_CHAINING OFFGOEXEC sys. sp_db_vardecimal_storage_format N 'lib', N 'ON 'gouse [lib] GO/***** Object: Table [dbo]. [Book] Script Date: 01/15/2014 10:24:02 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOSET ANSI_PADDING ongocreate 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, rows = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY] GOSET ANSI_PADDING OFFGO/***** 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) goalter 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] = 'you' OR [bloan] = 'None') goalter table [dbo]. [Book] check constraint [CK_Book_1] GO

Declare @ I int = 1 while (@ I <33) beginINSERt into book values ('name' + CAST (@ I as varchar (4), @ I, 'computer ', CAST (getdate () as varchar (20), 'you') set @ I + = 1 endupdate Book set bdate = '2017-10-12'

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.