Many times when we are programming in JSP, there will be a lot of duplicate code, this time we need to use JavaBean. Let me introduce you to JSP file using JavaBean
Directory structure
only need to be in JSP the beginning of the file plus a red code
Use directly when using
<%@ page language= "java"import="java.util.*,java.sql.*"pageencoding=" UTF-8 "%>
<%
String path =request.getcontextpath ();
String BasePath =request.getscheme () +"://"+request.getservername () +":"+ Request.getserverport () +path+"/";
%>
<jsp:usebean id="DBJB" scope="page"class="LYTJB. DB "/>
<! DOCTYPE HTML Public "-//w3c//dtdhtml 4.01 transitional//en" >
< HTML >
< Head >
< title > My JSP ' index.jsp ' starting page</title>
</ Head >
.........
...........
..........
String sql="Selectbook_picture,book_name,book_out_price,book_stock from College_info wherecollege= " Politics ' ";
ResultSet rs =dbjb.executequery (SQL); / return SQL statement Query result set ( collection )
.........................
Attached Db.java code
Package lytjb;
import java.sql.*;
// a tool class that is used to find the data source.
Public class DB {
Private Connectioncon = null;
Private Statementstmt = null;
ResultSet rs = null;
Public ResultSet executeQuery (String sql)throws Exception {
Try {
Class. forname ("Com.microsoft.sqlserver.jdbc.SQLServerDriver");
con=drivermanager. getconnection ("JDBC:SQLSERVER://LOCALHOST:1433;DATABASENAME=SHB","sa","1234567");
//class.forname ("Sun.jdbc.odbc.JdbcOdbcDriver");
//con=drivermanager.getconnection ("Jdbc:odbc:JDBCSQLDemo_JSPTest");
stmt=con. createstatement ();
rs=stmt. executeQuery (SQL);
}catch(Exception e) {}
return RS;
}
// Execution insert,update Statement
Public void executeupdate (String sql) throws Exception {
Try {
Class. forname ("Com.microsoft.sqlserver.jdbc.SQLServerDriver");
con=drivermanager. getconnection ("JDBC:SQLSERVER://LOCALHOST:1433;DATABASENAME=SHB","sa","1234567");
//class.forname ("Sun.jdbc.odbc.JdbcOdbcDriver");
//con=drivermanager.getconnection ("Jdbc:odbc:JDBCSQLDemo_JSPTest");
stmt=con. createstatement ();
int rs=stmt. executeupdate (SQL);
}catch(Exception e) {}
}
// Close stmt and close the connection
Public void Close_all () {
Try {
stmt. Close ();
con. Close ();
} catch (SQLException e) {
E.printstacktrace ();
}
}
}
Cross-use of JSP and JavaBean