综合运用javaBean、servlet对数据库的查询、插入等操作

(数据库使用的是SQL server 2008)综合运用javaBean、servlet对数据库的查询、插入等操作,将代码贴处理,以后需要时直接用就行了。


综合应用。本实验采用MVC设计模式,通过数据源和DAO对象访问数据库。其中JavaBeans实现模型,访问数据库,Servlet实现控制器,JSP页面实现视图,分页功能实现。

·        模型包括2个JavaBean:BookBean用于存放图书信息,BookDAO用于访问数据库。

·        控制器包括2个Servlet:BookQueryServlet根据请求参数查询图书信息、BookInsertServlet用来向数据库中插入数据。

·        视图包括4个JSP页面:bookQuery.jsp显示查询页面、bookInsert.jsp显示插入页面、display.jsp显示查询结果页面和errorPage.jsp显示错误页面。


【步骤1】存放图书信息的JavaBeans代码BookBean.java,它也是一个传输对象。

package com.beans;

import java.io.*;

public class BookBean implements Serializable{
    private String bookid = null;
    private String title = null;
    private String author = null;
    private String publisher = null;
    private float price = 0.0F;

    public BookBean(){}
    public BookBean(String bookId, String title, String author, String publisher, float price) {
        this.bookid = bookId;
        this.title = title;
        this.author = author;
        this.publisher = publisher;
        this.price = price;
    }
    public String getBookid() { return this.bookid; }
    public String getTitle() { return title; }
    public String getAuthor() { return this.author; }
    public float getPrice() { return price; }
    public String getPublisher () { return publisher; }
    
    public void setBookid(String bookid){ this.bookid=bookid;	}
    public void setTitle(String title){this.title=title;	}
    public void setAuthor(String author){ this. author = author;	}
    public void setPrice(float price){this.price=price;	}
    public void setPublisher (String publisher){ this.publisher = publisher;}
}

【步骤2】下面的BookDAO是一个简单的JavaBeans,它实现数据库的访问。
package com.beans;

import java.sql.*;

import javax.sql.*;
import javax.naming.*;

import java.util.ArrayList;

import com.beans.BookBean;

public class BookDAO{
//   private static InitialContext context= null;
//   private DataSource dataSource = null;
   
    Connection conn =null;
    PreparedStatement pstmt = null;
    ResultSet rst = null;
   public BookDAO(){
   	try{
   		Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();   //jar包
   	    conn = DriverManager.getConnection("jdbc:sqlserver://127.0.0.1:1433;DatabaseName=bookStore","sa","123456"); 
     }catch(Exception e){
     }
   }
   // 根据书号查询图书信息
   public BookBean searchBook(String bookid){  	 
      BookBean  book = new BookBean();
      try{
   	    pstmt = conn.prepareStatement("SELECT * FROM book WHERE bookid=?"); 
   	    pstmt.setString(1,bookid);
   	    rst = pstmt.executeQuery();
   	    if(rst.next()){
   	      book.setBookid(rst.getString("bookid"));
   	      book.setTitle(rst.getString("title"));
          book.setAuthor(rst.getString("author"));
          book.setPublisher(rst.getString("publisher"));
          book.setPrice(rst.getFloat("price"));
   	      return book;
        }else{
          return  null;
        }
   	 }catch(SQLException se){
   	  	return null;
   	 }finally{
   	  	 try{
   	  		 if(conn!=null)
   	  	 	 conn.close();
   	  	 }catch(SQLException se){
   	  	 }
   	 }
   }   
   // 插入一本图书记录
   public boolean insertBook(BookBean book){  	  
   	   try{
   	  	 pstmt = conn.prepareStatement(
   	  	 	 "INSERT INTO book VALUES(?,?,?,?,?)"); 
   	     pstmt.setString(1,book.getBookid());
   	     pstmt.setString(2,book.getTitle());
   	     pstmt.setString(3,book.getAuthor());
   	     pstmt.setString(4,book.getPublisher());
   	     pstmt.setFloat(5,book.getPrice());
   	     pstmt.executeUpdate();
   	     pstmt.close();
   	     return true;
   	   }catch(SQLException se){
   	  	 return false;
   	   }finally{
   	  	  try{
   	  	 	conn.close();
   	  	  }catch(SQLException se){ }
   	   }
   }     
}


【步骤3】下面的JSP页面bookQuery.jsp实现根据书号查询图书信息

<%@ page contentType="text/html; charset=gb2312" %>
<html><head> <title>Book Query</title>
</head>
<body>
请输入一个书号:<br>
<form action="BookQueryServlet" method = "post">
<input type="text" name="bookid"><br>
<input type="submit" value="提交">
</form>
</body>
</html>

【步骤4】下面的JSP页面bookInsert.jsp实现向数据库中插入数据

<%@ page contentType="text/html; charset=gb2312" %>
<html><head> <title>Book Insert</title>
</head>
<body>
<h3>请输入图书信息:</h3>
<% if(request.getAttribute("result")!=null)
     out.print(request.getAttribute("result"));
%>
<form action = "BookInsertServlet" method = "post">
 <table>
  <tr><td>书号</td> <td><input type="text" name="bookid" ></td></tr>
  <tr><td>书名</td><td><input type="text" name="title"></td></tr>      
  <tr><td>作者</td><td><input type="text" name="author" ></td></tr>
  <tr><td>出版社</td><td><input type="text" name="publisher" ></td></tr>
  <tr><td>单价</td><td><input type="text" name="price" ></td></tr>
  <tr><td><input type="submit" value="确定" ></td>
      <td><input type="reset" value="重置" ></td>
  </tr>
</table>
</form>
</body></html>

【步骤5】显示查询结果的JSP页面display.jsp:

<%@ page contentType="text/html;charset=gb2312"%>
<jsp:useBean id="book" class="com.beans.BookBean" scope="session"/>
<html><body>
   书号:<jsp:getProperty name="book" property="bookid"/><br><br>
   书名:<jsp:getProperty name="book" property="title"/><br><br>
   作者:<jsp:getProperty name="book" property="author"/><br><br>
   出版社:<jsp:getProperty name="book" property="publisher"/><br><br>
   价格:<jsp:getProperty name="book" property="price"/><br><br>
</body></html>

【步骤6】错误页面errorPage.jsp代码如下:

<%@ page contentType="text/html;charset=gb2312"%>
<html><body>
    对不起,您查的图书不存在!
</body></html>

【步骤7】下面的Servlet实现从请求参数获得书号,然后从数据库中查找该书,最后根据查询结果将请求转发到显示页面(display.jsp)或错误页面(errorPage.jsp)。

BookQueryServlet.java

import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import com.beans.BookBean;
import com.beans.BookDAO;


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String bookid = request.getParameter("bookid");
	    BookDAO bookdao = new BookDAO();
	    BookBean book = bookdao.searchBook(bookid);
	    
	    if(book!=null){
	      request.getSession().setAttribute("book", book);
	      RequestDispatcher view = request.getRequestDispatcher("/display.jsp");
	      view.forward(request, response);
	    }else{
	      RequestDispatcher view = request.getRequestDispatcher("/errorPage.jsp");
	      view.forward(request, response);
	    }

	}

【步骤8】下面的Servlet实现向数据库插入数据,并将控制请求的转发到bookInsert.jsp页面。

BookInsertServlet.java

import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import com.beans.BookBean;
import com.beans.BookDAO;	


protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        request.setCharacterEncoding("gb2312");
        String message = null;  
        BookBean book = new BookBean(
            request.getParameter("bookid"),request.getParameter("title"),
            request.getParameter("author"),request.getParameter("publisher"),
            Float.parseFloat(request.getParameter("price"))
            ); 
        BookDAO bookdao = new BookDAO();
        boolean success = bookdao.insertBook(book);
        if(success){
           message = "成功插入一条记录!";
         }else{ 
           message = "插入记录错误!";
        }   
       request.setAttribute("result",message);
       RequestDispatcher view = request.getRequestDispatcher("/bookInsert.jsp");
       view.forward(request, response);

    }


插入:

插入后:




查询:


查询结果:



数据库中的数据:


发布了491 篇原创文章 · 获赞 226 · 访问量 21万+
展开阅读全文

用javabean向数据库添加数据,请问为什么DoInsert.jsp一直报错

04-02

package com.javabean.user; //用于封装用户信息 public class User { private int id; private String username; private String password; private String type; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getType() { return type; } public void setType(String type) { this.type = type; } } ---------------------------------------------------------------------------------------- package com.javabean.user; //用户连接数据库------获得特定数据库的连接对象,使以后可以调查此方法来访问数据库 import java.sql.*; public class Conn { public static final String DBDRIVER="com.mysql.jdbc.Driver"; //包加类名 public static final String DBURL="jdbc:mysql://localhost:3306/test"; public static final String DBUSER="root"; public static final String DBPASS="123456"; public Connection getConn() { Connection conn=null; try { Class.forName(DBDRIVER); conn=DriverManager.getConnection(DBURL,DBUSER,DBPASS); }catch(Exception e) { e.printStackTrace(); } return conn; } } --------------------------------------------------------------------------------------------- package com.javabean.user; //对数据库的增删改查操作 import com.javabean.user.Conn; import java.sql.*; import java.util.ArrayList; import java.util.List; import com.javabean.user.User; public class Userdao { //添加数据 public int InsertUser(User usera) { int rs=0; try { //驱动连接了数据库 Conn conn=new Conn(); Connection dbc=conn.getConn(); //插入语句 String sql_insert="insert into user(username,password,type) values(?,?,?)"; //将SQl语句预编译保存在pst中 PreparedStatement pst=dbc.prepareStatement(sql_insert); //为sql语句中的属性赋值 pst.setString(1,usera.getUsername()); pst.setString(2,usera.getPassword()); pst.setString(3,usera.getType()); //执行sql语句,将结果放在rs中 rs=pst.executeUpdate(); }catch(Exception e) { e.printStackTrace(); } return rs; } public List<User> SelectUser() { ResultSet rs=null; List<User> list=new ArrayList<User>(); try { Conn conn=new Conn(); Connection dbc=conn.getConn(); String sql_select="select * from user"; PreparedStatement pst=dbc.prepareStatement(sql_select); rs=pst.executeQuery(); while(rs.next()) { User user=new User(); user.setId(rs.getInt(1)); user.setUsername(rs.getString(2)); user.setPassword(rs.getString(3)); user.setType(rs.getString(4)); list.add(user); } }catch(Exception e) { e.printStackTrace(); } return list; } } ------------------------------------------------------------------------------------------------- <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import="com.javabean.user.Conn"%> <%@ page import="com.javabean.user.Userdao" %> <%@ page import="com.javabean.user.User" %> <!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>DoInsert</title> </head> <body> <%--对Inser.jsp页面中表单的提交请求进行处理,该页面将获取表单提交的所有信息,然后将信息添加到数据库--%> <%request.setCharacterEncoding("utf-8"); %> <jsp:useBean id="user" class="com.javabean.user.User"> <jsp:setProperty name="user" property="*"/> </jsp:useBean> <% Userdao userdaoa=new Userdao(); userdaoa.InsertUser(user); %> </body> </html> 问答

JSP对数据库进行信息添加及关键字查询出现错误,怎么解决

06-09

org.apache.jasper.JasperException: An exception occurred processing JSP page /emp_list.jsp at line 18 15: if(keyWord==null){ 16: keyWord=""; 17: } 18: List<Emp> all=DAOFactory.getIEmpDAOInstance().findAll(keyWord); 19: Iterator<Emp> iter=all.iterator(); 20: %> 21: <center> Stacktrace: org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:568) org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:455) org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:395) org.apache.jasper.servlet.JspServlet.service(JspServlet.java:339) javax.servlet.http.HttpServlet.service(HttpServlet.java:727) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) root cause javax.servlet.ServletException: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server. org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:916) org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:845) org.apache.jsp.emp_005flist_jsp._jspService(emp_005flist_jsp.java:141) org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70) javax.servlet.http.HttpServlet.service(HttpServlet.java:727) org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432) org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:395) org.apache.jasper.servlet.JspServlet.service(JspServlet.java:339) javax.servlet.http.HttpServlet.service(HttpServlet.java:727) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) root cause com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server. sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57) sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) java.lang.reflect.Constructor.newInstance(Constructor.java:525) com.mysql.jdbc.Util.handleNewInstance(Util.java:409) com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1118) com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:343) com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2308) com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2122) com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:774) com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:49) sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57) sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) java.lang.reflect.Constructor.newInstance(Constructor.java:525) com.mysql.jdbc.Util.handleNewInstance(Util.java:409) com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:375) com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:289) java.sql.DriverManager.getConnection(DriverManager.java:579) java.sql.DriverManager.getConnection(DriverManager.java:221) com.wgh.dbc.DatabaseConnection.<init>(DatabaseConnection.java:13) com.wgh.dao.proxy.EmpDAOProxy.<init>(EmpDAOProxy.java:13) com.wgh.factory.DAOFactory.getIEmpDAOInstance(DAOFactory.java:7) org.apache.jsp.emp_005flist_jsp._jspService(emp_005flist_jsp.java:82) org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70) javax.servlet.http.HttpServlet.service(HttpServlet.java:727) org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432) org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:395) org.apache.jasper.servlet.JspServlet.service(JspServlet.java:339) javax.servlet.http.HttpServlet.service(HttpServlet.java:727) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) root cause java.net.UnknownHostException: locahost java.net.Inet6AddressImpl.lookupAllHostAddr(Native Method) java.net.InetAddress$1.lookupAllHostAddr(InetAddress.java:866) java.net.InetAddress.getAddressesFromNameService(InetAddress.java:1258) java.net.InetAddress.getAllByName0(InetAddress.java:1211) java.net.InetAddress.getAllByName(InetAddress.java:1127) java.net.InetAddress.getAllByName(InetAddress.java:1063) com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:246) com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:292) com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2308) com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2122) com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:774) com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:49) sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57) sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) java.lang.reflect.Constructor.newInstance(Constructor.java:525) com.mysql.jdbc.Util.handleNewInstance(Util.java:409) com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:375) com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:289) java.sql.DriverManager.getConnection(DriverManager.java:579) java.sql.DriverManager.getConnection(DriverManager.java:221) com.wgh.dbc.DatabaseConnection.<init>(DatabaseConnection.java:13) com.wgh.dao.proxy.EmpDAOProxy.<init>(EmpDAOProxy.java:13) com.wgh.factory.DAOFactory.getIEmpDAOInstance(DAOFactory.java:7) org.apache.jsp.emp_005flist_jsp._jspService(emp_005flist_jsp.java:82) org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70) javax.servlet.http.HttpServlet.service(HttpServlet.java:727) org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432) org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:395) org.apache.jasper.servlet.JspServlet.service(JspServlet.java:339) javax.servlet.http.HttpServlet.service(HttpServlet.java:727) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) note The full stack trace of the root cause is available in the Apache Tomcat/7.0.57 logs. 问答

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览