JAVA入门简单的增删改查(Servlet+JSP)一_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > JAVA入门简单的增删改查(Servlet+JSP)一

JAVA入门简单的增删改查(Servlet+JSP)一

 2015/4/8 22:07:12  南头一霸  程序员俱乐部  我要评论(0)
  • 摘要:是一个图书的增删改查JDBC的连接packagecom.zhouxiaobo.demo.jdbc.util;importjava.sql.Connection;publicinterfaceDBUtil{publicConnectionopenConn();publicvoidcloseConn();}重写packagecom.zhouxiaobo.demo.jdbc.util;importjava.sql.Connection;importjava.sql.DriverManager
  • 标签:Java Servlet JS
是一个图书的增删改查
JDBC的连接
package com.zhouxiaobo.demo.jdbc.util;

import java.sql.Connection;

public interface DBUtil {

public  Connection openConn();

public void closeConn();
}
重写
package com.zhouxiaobo.demo.jdbc.util;

import java.sql.Connection;
import java.sql.DriverManager;

public class DefaultDBUtil implements DBUtil{
public static String url="jdbc:mysql://localhost:3306/d";
public static String username="root";
public static String password="root";
public static String drive="com.mysql.jdbc.Driver";
public Connection conn=null;
@Override
public  Connection openConn() /*throws RuntimeException */  {
try{
Class.forName(drive);
    conn = DriverManager.getConnection(url,username,password);
return conn;
}catch(Exception e){
//throw new RuntimeException(e);
e.getMessage();
return null;
}
}

@Override
public void closeConn()throws RuntimeException {
try{
conn.close();
}catch(Exception s){
throw new RuntimeException(s);
}
}

}


Bean层
package com.zhouxiaobo.demo.jdbc.bean;

public class Book {
public String getSn() {
return sn;
}
public void setSn(String sn) {
this.sn = sn;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private String sn;
private String name;

}


BookLend 层

package com.zhouxiaobo.demo.jdbc.bean;

public class BookLend {
public Book getBook() {
return book;
}
public void setBook(Book book) {
this.book = book;
}
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
private Book book;
private Student student;
private int number;

}

BookStore 层

package com.zhouxiaobo.demo.jdbc.bean;

public class BookStore {

public Book getBook() {
return book;
}
public void setBook(Book book) {
this.book = book;
}
public int getTotalNumber() {
return totalNumber;
}
public void setTotalNumber(int totalNumber) {
this.totalNumber = totalNumber;
}

private Book book;
private int totalNumber;
}

Student 层

package com.zhouxiaobo.demo.jdbc.bean;

public class Student {

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;
}
private String id;
private String name;

}

DAO层
package com.zhouxiaobo.demo.jdbc.dao;


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 com.zhouxiaobo.demo.jdbc.bean.Book;

public class BookDao {
public List<Book> findbysn(String sn,Connection conn){
String sql="select * from book where sn=?";
List<Book> books=new ArrayList<Book>();
try{
PreparedStatement ps=conn.prepareStatement(sql);
ps.setString(1, sn);
ResultSet rs=ps.executeQuery();
while(rs.next()){
Book book=new Book();
book.setSn(rs.getString(1));
book.setName(rs.getString(2));
books.add(book);
}
return books;
}catch(SQLException s){
s.printStackTrace();
return null;
}
}
public void insert(String sn,String name,Connection conn){
String sql="insert book values(? ,?)";
try{
int row=0;
PreparedStatement ps=conn.prepareStatement(sql);
ps.setString(1, sn);
ps.setString(2, name);
row=ps.executeUpdate();
if(row>0){
System.out.println("success");
}
}catch(SQLException s){
s.printStackTrace();
}
}
public void update(String sn,String name,Connection conn){
String sql="update book set name=? where sn=?";
try{
int row=0;
PreparedStatement ps=conn.prepareStatement(sql);
ps.setString(1,name);
ps.setString(2, sn);
row=ps.executeUpdate();
if(row>0){
System.out.println("Success!");
}
}catch(SQLException s){
s.printStackTrace();
}
}
public List<Book> getquery(Connection conn){
String sql="select * from book";
List<Book> books=new ArrayList<Book>();
try{
PreparedStatement ps=conn.prepareStatement(sql);
ResultSet rs=ps.executeQuery();

while(rs.next()){
Book book=new  Book();
book.setSn(rs.getString(1));
book.setName(rs.getString(2));
books.add(book);
}
return books;
}catch (SQLException e) {
// TODO: handle exception
e.printStackTrace();
return null;
}
}
public void delete(String sn,Connection conn){
String sql="delete from book where sn=?";
try{
PreparedStatement ps=conn.prepareStatement(sql);
ps.setString(1, sn);
int row=0;
row=ps.executeUpdate();
if(row>0){
System.out.println("Success!");
}
}catch (SQLException e) {
// TODO: handle exception
e.printStackTrace();
}
}

}


package com.zhouxiaobo.demo.jdbc.dao;

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

public class BookLendDao {

public void insert(String sn, String id, int number, Connection conn) {
String sql = "insert booklend values(?,?,?)";
try {
int row = 0;
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, sn);
ps.setString(2, id);
ps.setInt(3, number);
row = ps.executeUpdate();
if (row > 0) {
System.out.println("success");
}
} catch (SQLException s) {
s.printStackTrace();
}
}
public void delete(String sn,Connection conn){
String sql="delete from booklend where sn=?";
try{
PreparedStatement ps=conn.prepareStatement(sql);
ps.setString(1, sn);
int row=0;
row=ps.executeUpdate();
if(row>0){
System.out.println("success");
}
}catch(SQLException s){
s.printStackTrace();
}
}

}


package com.zhouxiaobo.demo.jdbc.dao;

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

import com.zhouxiaobo.demo.jdbc.bean.Book;
import com.zhouxiaobo.demo.jdbc.bean.BookStore;

public class BookStoreDao {

public void update(String sn, int totalNumber, Connection conn){
String sql="update bookstore set totalNumber=? where sn=?";
try{
int row=0;
PreparedStatement ps=conn.prepareStatement(sql);
ps.setInt(1,totalNumber);
ps.setString(2, sn);
row=ps.executeUpdate();
if(row>0){
System.out.println("???3????");
}

}catch(SQLException s){
s.printStackTrace();
}
}

public int getbooknumberbysn(String sn,Connection conn){
String sql="select * from bookstore where sn=?";
try{
PreparedStatement ps=conn.prepareStatement(sql);
ResultSet rs=ps.executeQuery();
if(rs.next()){
String s1=rs.getNString(3);
System.out.println("?????????"+s1+"??");
int a=Integer.parseInt(s1);
return a;
}
}catch(SQLException s){
s.printStackTrace();
}
return 0;
}


public  void insert(Book book, int totalNumber, Connection conn ){
String sql="insert bookstore value(?,?,?)";
BookStore bookStore=new BookStore();
try{
int row=0;
    PreparedStatement ps=conn.prepareStatement(sql);
    ps.setString(1, bookStore.getBook().getSn());
    ps.setString(2, bookStore.getBook().getName());
    ps.setInt(3, bookStore.getTotalNumber());
    row=ps.executeUpdate();
    if(row>1){
    System.out.println("????????");
    }
}catch(SQLException s){
s.printStackTrace();
}
}
public void delete(String sn,Connection conn){
String sql="delete from bookstore where sn=?";
BookStore bookStore=new BookStore();
try{
PreparedStatement ps=conn.prepareStatement(sql);
ps.setString(1,bookStore.getBook().getSn());
int row=0;
row=ps.executeUpdate();
if(row>0){
System.out.println("???????");
}
}catch(SQLException s){
s.printStackTrace();
}finally{

}
}
public void findbysn(String sn,Connection conn){
String sql="select *from bookstore where sn=?";
BookStore bookStore=new BookStore();
try{
PreparedStatement ps=conn.prepareStatement(sql);
ps.setString(1, bookStore.getBook().getSn());
ResultSet rs=ps.executeQuery();
String s1=rs.getString(1);
String s2=rs.getString(2);
String s3=rs.getString(3);
System.out.println(s1+"\t"+s2+"\t"+s3);
}catch(SQLException a){
a.printStackTrace();
}
}
/*public List<BookStore> getquery(Connection conn){
String sql="select * from bookstore";

try{
PreparedStatement ps=conn.prepareStatement(sql);
ResultSet rs=ps.executeQuery();
List<BookStore> bookList =new ArrayList<BookStore>();
while(rs.next()){
BookStore  bookStore=new BookStore();
//bookStore.setBook()

}

}catch(SQLException s){
s.printStackTrace();
}
}*/
}

三个有点相似 看一个就好

Service

接口
package com.zhouxiaobo.demo.jdbc.service;

import java.sql.Connection;
import java.util.List;

import com.zhouxiaobo.demo.jdbc.bean.Book;
import com.zhouxiaobo.demo.jdbc.bean.BookLend;
import com.zhouxiaobo.demo.jdbc.bean.Student;

public interface BussinessService {

public void lendBook(Student student, Book book, int number);

public void returnbook(BookLend bookLend);

public List<Book> showallbooks();

public void setConn(Connection conn);

public void updatebook(String sn,String name,Connection conn);

public  void deletebook(String sn,Connection conn);

public String insertbook(String sn,String name,Connection conn);

public List<Book> findbysn(String sn,Connection conn);
}

重写
package com.zhouxiaobo.demo.jdbc.service;

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

import com.zhouxiaobo.demo.jdbc.bean.Book;
import com.zhouxiaobo.demo.jdbc.bean.BookLend;
import com.zhouxiaobo.demo.jdbc.bean.Student;
import com.zhouxiaobo.demo.jdbc.dao.BookDao;
import com.zhouxiaobo.demo.jdbc.dao.BookLendDao;
import com.zhouxiaobo.demo.jdbc.dao.BookStoreDao;
import com.zhouxiaobo.demo.jdbc.exception.DemoJDBCException;

public class BussinessServiceImpl implements BussinessService {

private BookLendDao booklendDao;
private BookStoreDao bookStoreDao;

private Connection conn;

public BussinessServiceImpl(){

}

public BussinessServiceImpl(Connection conn){
this.conn = conn;
}

public void setConn(Connection conn) {
this.conn = conn;
}

@Override
public void lendBook(Student student, Book book, int number) {

booklendDao = new BookLendDao();
bookStoreDao = new BookStoreDao();

try{
conn.setAutoCommit(false);

//TODO: ??lendBook????????????

booklendDao.insert(book.getSn(), student.getId(), number, conn);

//????????ж?????????
int total = bookStoreDao.getbooknumberbysn(book.getSn(),conn);
int currentNumber = total - number;

bookStoreDao.update(book.getSn(), currentNumber, conn);
//TODO: ??bookStoreDao???????
conn.commit();

}catch(Exception e){
try {
conn.rollback();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
throw new DemoJDBCException("xzzxz",e);
}finally{
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void returnbook(BookLend bookLend){
//????????
booklendDao=new BookLendDao();
bookStoreDao=new BookStoreDao();
try{
conn.setAutoCommit(false);
booklendDao.delete(bookLend.getBook().getSn(), conn);
//????????
int number=bookStoreDao.getbooknumberbysn(bookLend.getBook().getSn(),conn);
int totalNumber=number+bookLend.getNumber();
bookStoreDao.update(bookLend.getBook().getSn(), totalNumber, conn);
conn.commit();
}catch(Exception x){
try {
conn.rollback();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

public List<Book> showallbooks(){
BookDao bookDao=new BookDao();
List<Book> result = null;
try{
conn.setAutoCommit(false);
return bookDao.getquery(conn);
}catch (SQLException e) {
// TODO: handle exception
try {
conn.rollback();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
e.printStackTrace();
}
return null;
}
    public void updatebook(String sn,String name,Connection conn){
   BookDao bookDao=new BookDao();
   bookDao.update(sn, name, conn);
   }
    public void deletebook(String sn,Connection conn){
    BookDao bookDao=new BookDao();
    try{
    conn.setAutoCommit(false);
    bookDao.delete(sn, conn);
    conn.commit();
    }catch(SQLException x){
    x.printStackTrace();
    try {
conn.rollback();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
    }
    }
    public String insertbook(String sn,String name,Connection conn){
    BookDao bookDao=new BookDao();
    List<Book> books=new ArrayList<Book>();
    books=bookDao.findbysn(sn, conn);
    if( books.size()==0){
try{
    conn.setAutoCommit(false);
    bookDao.insert(sn, name, conn);
    conn.commit();
    return "1";
    }catch(SQLException s){
    s.printStackTrace();
    try {
conn.rollback();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
    return "1";
    }
    }else{
    return sn;
    }
}
   
    public List<Book> findbysn(String sn,Connection conn){
    BookDao bookDao=new BookDao();
    List<Book> result = null;
    try{
    conn.setAutoCommit(false);
    return bookDao.findbysn(sn, conn);
    }catch (Exception e) {
// TODO: handle exception
    try {
conn.rollback();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
    e.printStackTrace();
    return null;
}
    }

}


Action层

package com.zhouxiaobo.demo;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.util.Collection;
import java.util.List;

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

import com.zhouxiaobo.demo.jdbc.bean.Book;
import com.zhouxiaobo.demo.jdbc.service.BussinessService;
import com.zhouxiaobo.demo.jdbc.service.BussinessServiceImpl;
import com.zhouxiaobo.demo.jdbc.util.DBUtil;
import com.zhouxiaobo.demo.jdbc.util.DefaultDBUtil;

/**
* Servlet implementation class FindAllBook
*/
public class FindAllBook extends HttpServlet {
private static final long serialVersionUID = 1L;

    /**
     * Default constructor.
     */
    public FindAllBook() {
        // TODO Auto-generated constructor stub
    }

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
DBUtil dbUtil=new DefaultDBUtil();
try{
Connection conn = dbUtil.openConn();
BussinessService businessService = new BussinessServiceImpl();
businessService.setConn(conn);
List<Book> BookStore = businessService.showallbooks();
request.setAttribute("book",BookStore);

request.getRequestDispatcher("/booklist.jsp").forward(request, response);

}finally{
dbUtil.closeConn();
}
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}

}

JSP
界面
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>图书管理系统</h1>
<p align="center">
</p>
<td><a href="/LIB/Addbook.jsp">添加图书</a></td>
<td><a href="/LIB/findAllBook">查看所有图书</a></td>
<td><a href="/LIB/editBookServlet">更改图书</a></td>
<td><a href="/LIB/Find.jsp">按条件查找</a></td>
</body>
</html>

显示所有图书
<%@page import="java.util.List"%>
<%@page import="com.zhouxiaobo.demo.jdbc.bean.Book"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> 
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<table border="1" cellspacing="0" cellpadding="0 width="100%" style="align:center;">
<tr bgcolor="AAAAAA" style="font-weight:bold;">


<th>编号</th><th>书名</th><th><th width="0" colspan="2"></th>
<c:forEach  var="bk" items="${book}" varStatus="status">
  <tr>
  <c:if test="${status.count%2==0}" >
  <tr bgcolor="CCC000" style="font-weight:bold;">
  </c:if>
  <c:if test="${status.count%2==1}">
  <tr bgcolor="FFFFOO" style="font-weight:bold;">
  </c:if>
   <td>${bk.sn}</td>
   <td>${bk.name}</td>
   <td><a href="/LIB/deleteBookServlet?sn=${bk.sn}">删除</a>|<a href="/LIB/editBookServlet?sn=${bk.sn}">更改</a></td>
</c:forEach>

<c:if test="${!empty flag}">
  ISBN ${flag}is deleted!
</c:if>
<c:if test="${!empty flag1}">
  ISBN ${flag1} is haved !
  </c:if>
</tr>
</table>

发表评论
用户名: 匿名