Common JSP page query display mode title: Common JSP page query Display Mode
Author: Evan
Email: evan_zhao@hotmail.com
Background:
1. List the database query results in JSP
2. In a good J2EE mode, database queries are generally implemented using Dao (Data Access Object). jsp is only used to display data.
Problem:
You can use JDBC resultset to obtain the query results (stored in the database buffer). However, after statement and connection are disabled, resultset is unavailable. Therefore, you need to retrieve all the query results and pass them to the JSP page.
Solution 1:
Use value object. Encapsulate each record into a JavaBean object and load these objects into a collection file and send them to JSP for display. The disadvantage of this method is that a Java class needs to be defined for each query and a lot of additional code is required to encapsulate record data into a Java object.
Sample Code:
- // Query the data code
- Connection conn = dbutil. getconnection ();
- Preparedstatement PST =Null;
- Resultset rs =Null;
- Try{
- StringSQL = "select emp_code, real_name from t_employee where organ_id = ?";
- Pst = conn. preparedstatement (SQL );
- Pst. setstring (1, 101 ");
- Resultset rs = pst.exe cutequery ();
- List list =NewArraylist ();
- Employee EMP;
- While(Rs. Next ()){
- EMP =NewEmployee ();
- EMP. setreakname (Rs. getstring ("real_name "));
- EMP. setempcode (Rs. getstring ("emp_code "));
- ...
- List. Add (EMP );
- }
- ReturnList;
- }Finally{
- Dbutil. Close (RS, Pst, Conn );
- }
- // Display part of the JSP code
- <%
- List emplist = (list) request. getattribute ("emplist ");
- If(Emplist =Null) Emplist = collections. empty_list;
- %>
- ...
- <Table cellspacing = "0" width = "90%">
- <Tr> <TD> Code </TD> <TD> name </TD> </tr>
- <%
- Employee EMP;
- For(IntI = 0; I <emplist. Size (); I ++ ){
- EMP = (employee) emplist. Get (I );
- %>
- <Tr>
- <TD> <% = EMP. getempcode () %> </TD>
- <TD> <% = EMP. getrealname () %> </TD>
- </Tr>
- <%
- }// End
- %>
- </Table>
Solution 2:
Traverse the resultset to retrieve all data and encapsulate it into the collection.
Specific Practices:
1. Generate a list object (list = new arraylist ()).
2. Generate a map object (MAP map = new hashmap ()). Use Map to encapsulate a row of data. The key is the name of each field and the value is the corresponding value. (Map. Put ("user_name"), RS. getstring ("user_name "))
3. Load the map object generated in step 1 into the list object (list. Add (MAP) in step 2 )).
4. Repeat steps 2 and 3 until the resultset traversal is complete.
The preceding procedure is implemented in the dbutil. resultsettolist (resultset RS) method (uppercase is used for all column names.
Sample Code:
- // Code for querying data:
- ...
- Connection conn = dbutil. getconnection ();
- Preparedstatement PST =Null;
- Resultset rs =Null;
- Try{
- StringSQL = "select emp_code, real_name from t_employee where organ_id = ?";
- Pst = conn. preparedstatement (SQL );
- Pst. setstring (1, 101 ");
- Rs = pst.exe cutequery ();
- List list = dbutil. resultsettolist (resultset RS );
- ReturnList;
- }Finally{
- Dbutil. Close (RS, Pst, Conn );
- }
- // Display part of the JSP code
- <%
- List emplist = (list) request. getattribute ("emplist ");
- If(Emplist =Null) Emplist = collections. empty_list;
- %>
- ...
- <Table cellspacing = "0" width = "90%">
- <Tr> <TD> Code </TD> <TD> name </TD> </tr>
- <%
- Map colmap;
- For(IntI = 0; I <emplist. Size (); I ++ ){
- Colmap = (MAP) emplist. Get (I );
- %>
- <Tr>
- <TD> <% = colmap. Get ("emp_code") %> </TD>
- <TD> <% = colmap. Get ("real_name") %> </TD>
- </Tr>
- <%
- }// End
- %>
- </Table>
Solution 3:
Use rowset.
Rowset is an interface provided in jdbc2.0. Oracle implements this interface accordingly. It is useful for Oracle. JDBC. rowset. oraclecachedrowset. Oraclecachedrowset implements all the methods in resultset. However, unlike resultset, data in oraclecachedrowset remains valid after connection is disabled.
The Oracle rowset is implemented in the jdbcdownload of http://otn.oracle.com/software/content.html. it is named ocrs12.zip.
Sample Code:
- // Code for querying data:
- ImportJavax. SQL.Rowset;
- ImportOracle. JDBC. rowset. oraclecachedrowset;
- ...
- Connection conn = dbutil. getconnection ();
- Preparedstatement PST =Null;
- Resultset rs =Null;
- Try{......
- StringSQL = "select emp_code, real_name from t_employee where organ_id = ?";
- Pst = conn. preparedstatement (SQL );
- Pst. setstring (1, 101 ");
- Rs = pst.exe cutequery ();
- Oraclecachedrowset ors = neworaclecachedrowset ();
- // Encapsulate data in the resultset into the rowset
- ORS. populate (RS );
- ReturnORS;
- }Finally{
- Dbutil. Close (RS, Pst, Conn );
- }
- // Display part of the JSP code
- <%
- Javax. SQL.RowsetEmprs = (javax. SQL.Rowset) Request. getattribute ("emprs ");
- %>
- ...
- <Table cellspacing = "0" width = "90%">
- <Tr> <TD> Code </TD> <TD> name </TD> </tr>
- <%
- If(Emprs! =Null)While(Emprs. Next ()){
- %>
- <Tr>
- <TD> <% = emprs. Get ("emp_code") %> </TD>
- <TD> <% = emprs. Get ("real_name") %> </TD>
- </Tr>
- <%
- }// End while
- %>
- </Table>
Applicable scenarios:
Method 1: use custom query operations
Method 2 is applicable when multiple query statements or query results need to be processed.
Method 3 is suitable for a single query statement and is suitable for rapid development.
Related Links:
For paging display, see JSP paging technology implementation.
If you need to generate word or excel in the query result, see: use JSP to print reports in word or Excel format.
Appendix:Dbutil code:
- ImportJava. util.List;
- ImportJava. util.Arraylist;
- ImportJava. util.Map;
- ImportJava. util.Hashmap;
- ImportJava. util.Properties;
- ImportJava. util.Collections;
- ImportJava. SQL.Connection;
- ImportJava. SQL.Sqlexception;
- ImportJava. SQL.Resultset;
- ImportJava. SQL.Resultsetmetadata;
- ImportJava. SQL.Statement;
- ImportJava. SQL.Preparedstatement;
- ImportJavax. naming.Context;
- ImportJavax. naming.Initialcontext;
- ImportJavax. naming.Namingexception;
- ImportJavax. SQL.Datasource;
- Public ClassDbutil {
- Private Static Final StringJdbc_data_source = "Java: COMP/ENV/jdbc/datasource ";
- /**
- Enablelocaldebug: whether to debug locally. <Br>
- If the value is true, if the data source fails to be searched, use drivermanager to establish a connection with the database;
- If the value is false, only the data source is searched for to establish a database connection.
- The default value is false. <Br>
- Enablelocaldebug can be set to true through the system attribute JDBC. enable_local_debug = true to enable local debugging: <br>
- Added JVM parameter:-djdbc. enable_local_debug = true.
- */
- Private Static BooleanEnablelocaldebug =False;
- Static{
- Enablelocaldebug =Boolean. Getboolean ("JDBC. enable_local_debug ");
- }
- Private Static ContextCTX =Null;
- Private StaticJavax. SQL.DatasourceDS =Null;
- Private Static VoidInitdatasource ()Throws Exception{
- // Put Connection Properties in to a hashtable.
- If(CTX =Null){
- CTX =New Initialcontext();
- }
- If(DS =Null){
- DS = (javax. SQL.Datasource) CTX. Lookup (jdbc_data_source );
- }
- }
- /**
- * Search for the application server data source and obtain the database connection from the data source. <Br>
- * If the data source fails to be searched during local debugging and enablelocaldebug = true
- * Use Java. SQL. drivermanager to establish a connection based on system properties. <Br>
- * The following system attributes can be configured during local debugging: <br>
- * <P>
- * # JDBC driver name <br>
- * JDBC. Driver = <I> oracle. JDBC. Driver. oracledriver </I> <br>
- * # Database connection string <br>
- * JDBC. url = <I> JDBC: oracle: thin: @ 10.1.1.1: 1521: ocrl </I> <br>
- * # Database username <br>
- * JDBC. Username = <I> Scott </I> <br>
- * # Database User Password <br>
- * JDBC. Password = <I> tiger </I> <br>
- * </P>
- * The preceding system attributes can be set using JVM parameters: <br>
- *-Djdbc. Driver = oracle. JDBC. Driver. oracledriver
- *-Djdbc. url = JDBC: oracle: thin: @ 10.1.1.1: 1521: ocrl
- *-Djdbc. Username = Scott-djdbc. Password = Tiger
- * @ Return connection
- * @ Throws namingexception if data source search fails
- * @ Throws sqlexception if the database connection fails
- */
- Public Static ConnectionGetconnection ()ThrowsSqlexception{
- Try{
- Initdatasource ();
- ReturnDS. getconnection ();
- }Catch(SqlexceptionSqle ){
- ThrowSqle;
- }Catch(ExceptionNe ){
- If(Enablelocaldebug ){
- ReturnGettestconn ();
- }Else{
- Throw New Runtimeexception(Ne. tostring ());
- }
- }
- }
- // Establish a local test connection through drivermanager
- Private Static ConnectionGettestconn (){
- Try{
- StringDriver =System. Getproperty ("JDBC. Driver ");
- System. Out. println ("JDBC. Driver =" + driver );
- StringUrl =System. Getproperty ("JDBC. url ");
- System. Out. println ("JDBC. url =" + URL );
- StringUsername =System. Getproperty ("JDBC. username ");
- System. Out. println ("JDBC. Username =" + username );
- StringPassword =System. Getproperty ("JDBC. Password ");
- System. Out. println ("JDBC. Password =" + password );
- Class. Forname (driver). newinstance ();
- ReturnJava. SQL.Drivermanager. Getconnection (URL, username, password );
- }
- Catch(ExceptionEx ){
- Ex. printstacktrace ();
- Throw New Runtimeexception(EX. getmessage ());
- }
- }
- /**
- * Encapsulate the query result into a list. <Br>
- * The element type in the list is the map that encapsulates a row of data. The map key is the field name (uppercase), and the value is the corresponding field value.
- * @ Param Rs resultset
- * @ Return list
- * @ Throws java. SQL. sqlexception
- */
- Public Static ListResultsettolist (ResultsetRS)ThrowsJava. SQL.Sqlexception{
- If(Rs =Null)Return Collections. Empty_list;
- ResultsetmetadataMD = Rs. getmetadata ();
- IntColumncount = md. getcolumncount ();
- ListList =New Arraylist();
- MapRowdata;
- While(Rs. Next ()){
- Rowdata =New Hashmap(Columncount );
- For(IntI = 1; I <= columncount; I ++ ){
- Rowdata. Put (Md. getcolumnname (I), RS. GetObject (I ));
- }
- List. Add (rowdata );
- }
- ReturnList;
- }
- /**
- * Disable resultset, statement, and connection.
- * @ Param Rs resultset to be closed
- * @ Param stmt statement or preparedstatement to be closed
- * @ Param conn connection to be closed
- */
- Public Static VoidClose (ResultsetRS,StatementStmt,ConnectionConn ){
- If(RS! =Null)Try{
- Rs. Close ();
- }Catch(Java. SQL.SqlexceptionEx ){
- Ex. printstacktrace ();
- }
- If(Stmt! =Null)Try{
- Stmt. Close ();
- }Catch(Java. SQL.SqlexceptionEx ){
- Ex. printstacktrace ();
- }
- If(Conn! =Null)Try{
- Conn. Close ();
- }Catch(Java. SQL.SqlexceptionEx ){
- Ex. printstacktrace ();
- }
- }
- }// End of dbui