Cross-Use of jsp and javabean, and use of jspjavabean
Many times, when we program jsp, there will be a lot of repeated code. At this time, we need to use javabean. Next I will introduce you to the use of javabean in jsp files.
Directory structure
You only need to add a red code at the beginning of the jsp file.
Use it directly
<% @ 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"/>
<! Doctypehtml 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 = ''";
ResultSet rs mongodbjb.exe cuteQuery (SQL );//Return the SQL statement query result set (SET)
.........................
With DB. Java code
PackageLytjb;
ImportJava. SQL .*;
// A tool class used to find data sources.
Public classDB {
PrivateConnectioncon =Null;
PrivateStatementstmt =Null;
ResultSet rs =Null;
PublicResultSet executeQuery (String SQL)ThrowsException {
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 ();
Rs1_stmt.exe cuteQuery (SQL );
}Catch(Exception e ){}
ReturnRs;
}
// Execute the Insert and Update statements
Public voidExecuteUpdate (String SQL)ThrowsException {
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 ();
IntRs=Stmt.exe cuteUpdate (SQL );
}Catch(Exception e ){}
}
// CloseStmtAnd close the connection
Public voidClose_all (){
Try{
Stmt. close ();
Con. close ();
}Catch(SQLException e ){
E. printStackTrace ();
}
}
}