Common JSP page query display mode (with source code)

Source: Internet
Author: User
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:


  1. // Query the data code
  2. Connection conn = dbutil. getconnection ();
  3. Preparedstatement PST =Null;
  4. Resultset rs =Null;
  5. Try{
  6. StringSQL = "select emp_code, real_name from t_employee where organ_id = ?";
  7. Pst = conn. preparedstatement (SQL );
  8. Pst. setstring (1, 101 ");
  9. Resultset rs = pst.exe cutequery ();
  10. List list =NewArraylist ();
  11. Employee EMP;
  12. While(Rs. Next ()){
  13. EMP =NewEmployee ();
  14. EMP. setreakname (Rs. getstring ("real_name "));
  15. EMP. setempcode (Rs. getstring ("emp_code "));
  16. ...
  17. List. Add (EMP );
  18. }
  19. ReturnList;
  20. }Finally{
  21. Dbutil. Close (RS, Pst, Conn );
  22. }


  23. // Display part of the JSP code
  24. <%
  25. List emplist = (list) request. getattribute ("emplist ");
  26. If(Emplist =Null) Emplist = collections. empty_list;
  27. %>
  28. ...
  29. <Table cellspacing = "0" width = "90%">
  30. <Tr> <TD> Code </TD> <TD> name </TD> </tr>
  31. <%
  32. Employee EMP;
  33. For(IntI = 0; I <emplist. Size (); I ++ ){
  34. EMP = (employee) emplist. Get (I );
  35. %>
  36. <Tr>
  37. <TD> <% = EMP. getempcode () %> </TD>
  38. <TD> <% = EMP. getrealname () %> </TD>
  39. </Tr>
  40. <%
  41. }// End
  42. %>
  43. </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:


  1. // Code for querying data:
  2. ...
  3. Connection conn = dbutil. getconnection ();
  4. Preparedstatement PST =Null;
  5. Resultset rs =Null;
  6. Try{
  7. StringSQL = "select emp_code, real_name from t_employee where organ_id = ?";
  8. Pst = conn. preparedstatement (SQL );
  9. Pst. setstring (1, 101 ");
  10. Rs = pst.exe cutequery ();
  11. List list = dbutil. resultsettolist (resultset RS );
  12. ReturnList;
  13. }Finally{
  14. Dbutil. Close (RS, Pst, Conn );
  15. }



  16. // Display part of the JSP code
  17. <%
  18. List emplist = (list) request. getattribute ("emplist ");
  19. If(Emplist =Null) Emplist = collections. empty_list;
  20. %>
  21. ...
  22. <Table cellspacing = "0" width = "90%">
  23. <Tr> <TD> Code </TD> <TD> name </TD> </tr>
  24. <%
  25. Map colmap;
  26. For(IntI = 0; I <emplist. Size (); I ++ ){
  27. Colmap = (MAP) emplist. Get (I );
  28. %>
  29. <Tr>
  30. <TD> <% = colmap. Get ("emp_code") %> </TD>
  31. <TD> <% = colmap. Get ("real_name") %> </TD>
  32. </Tr>
  33. <%
  34. }// End
  35. %>
  36. </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:

  1. // Code for querying data:
  2. ImportJavax. SQL.Rowset;
  3. ImportOracle. JDBC. rowset. oraclecachedrowset;
  4. ...
  5. Connection conn = dbutil. getconnection ();
  6. Preparedstatement PST =Null;
  7. Resultset rs =Null;
  8. Try{......
  9. StringSQL = "select emp_code, real_name from t_employee where organ_id = ?";
  10. Pst = conn. preparedstatement (SQL );
  11. Pst. setstring (1, 101 ");
  12. Rs = pst.exe cutequery ();
  13. Oraclecachedrowset ors = neworaclecachedrowset ();
  14. // Encapsulate data in the resultset into the rowset
  15. ORS. populate (RS );
  16. ReturnORS;
  17. }Finally{
  18. Dbutil. Close (RS, Pst, Conn );
  19. }


  20. // Display part of the JSP code
  21. <%
  22. Javax. SQL.RowsetEmprs = (javax. SQL.Rowset) Request. getattribute ("emprs ");
  23. %>
  24. ...
  25. <Table cellspacing = "0" width = "90%">
  26. <Tr> <TD> Code </TD> <TD> name </TD> </tr>
  27. <%
  28. If(Emprs! =Null)While(Emprs. Next ()){
  29. %>
  30. <Tr>
  31. <TD> <% = emprs. Get ("emp_code") %> </TD>
  32. <TD> <% = emprs. Get ("real_name") %> </TD>
  33. </Tr>
  34. <%
  35. }// End while
  36. %>
  37. </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:

  1. ImportJava. util.List;
  2. ImportJava. util.Arraylist;
  3. ImportJava. util.Map;
  4. ImportJava. util.Hashmap;
  5. ImportJava. util.Properties;
  6. ImportJava. util.Collections;

  7. ImportJava. SQL.Connection;
  8. ImportJava. SQL.Sqlexception;
  9. ImportJava. SQL.Resultset;
  10. ImportJava. SQL.Resultsetmetadata;
  11. ImportJava. SQL.Statement;
  12. ImportJava. SQL.Preparedstatement;

  13. ImportJavax. naming.Context;
  14. ImportJavax. naming.Initialcontext;
  15. ImportJavax. naming.Namingexception;

  16. ImportJavax. SQL.Datasource;

  17. Public ClassDbutil {

  18. Private Static Final StringJdbc_data_source = "Java: COMP/ENV/jdbc/datasource ";

  19. /**
  20. Enablelocaldebug: whether to debug locally. <Br>
  21. If the value is true, if the data source fails to be searched, use drivermanager to establish a connection with the database;
  22. If the value is false, only the data source is searched for to establish a database connection.
  23. The default value is false. <Br>
  24. Enablelocaldebug can be set to true through the system attribute JDBC. enable_local_debug = true to enable local debugging: <br>
  25. Added JVM parameter:-djdbc. enable_local_debug = true.
  26. */
  27. Private Static BooleanEnablelocaldebug =False;

  28. Static{
  29. Enablelocaldebug =Boolean. Getboolean ("JDBC. enable_local_debug ");
  30. }


  31. Private Static ContextCTX =Null;
  32. Private StaticJavax. SQL.DatasourceDS =Null;


  33. Private Static VoidInitdatasource ()Throws Exception{
  34. // Put Connection Properties in to a hashtable.


  35. If(CTX =Null){
  36. CTX =New Initialcontext();
  37. }
  38. If(DS =Null){
  39. DS = (javax. SQL.Datasource) CTX. Lookup (jdbc_data_source );
  40. }
  41. }

  42. /**
  43. * Search for the application server data source and obtain the database connection from the data source. <Br>
  44. * If the data source fails to be searched during local debugging and enablelocaldebug = true
  45. * Use Java. SQL. drivermanager to establish a connection based on system properties. <Br>
  46. * The following system attributes can be configured during local debugging: <br>
  47. * <P>
  48. * # JDBC driver name <br>
  49. * JDBC. Driver = <I> oracle. JDBC. Driver. oracledriver </I> <br>
  50. * # Database connection string <br>
  51. * JDBC. url = <I> JDBC: oracle: thin: @ 10.1.1.1: 1521: ocrl </I> <br>
  52. * # Database username <br>
  53. * JDBC. Username = <I> Scott </I> <br>
  54. * # Database User Password <br>
  55. * JDBC. Password = <I> tiger </I> <br>
  56. * </P>
  57. * The preceding system attributes can be set using JVM parameters: <br>
  58. *-Djdbc. Driver = oracle. JDBC. Driver. oracledriver
  59. *-Djdbc. url = JDBC: oracle: thin: @ 10.1.1.1: 1521: ocrl
  60. *-Djdbc. Username = Scott-djdbc. Password = Tiger
  61. * @ Return connection
  62. * @ Throws namingexception if data source search fails
  63. * @ Throws sqlexception if the database connection fails
  64. */
  65. Public Static ConnectionGetconnection ()ThrowsSqlexception{
  66. Try{
  67. Initdatasource ();
  68. ReturnDS. getconnection ();
  69. }Catch(SqlexceptionSqle ){
  70. ThrowSqle;
  71. }Catch(ExceptionNe ){
  72. If(Enablelocaldebug ){
  73. ReturnGettestconn ();
  74. }Else{
  75. Throw New Runtimeexception(Ne. tostring ());
  76. }
  77. }
  78. }


  79. // Establish a local test connection through drivermanager
  80. Private Static ConnectionGettestconn (){
  81. Try{
  82. StringDriver =System. Getproperty ("JDBC. Driver ");
  83. System. Out. println ("JDBC. Driver =" + driver );

  84. StringUrl =System. Getproperty ("JDBC. url ");
  85. System. Out. println ("JDBC. url =" + URL );

  86. StringUsername =System. Getproperty ("JDBC. username ");
  87. System. Out. println ("JDBC. Username =" + username );

  88. StringPassword =System. Getproperty ("JDBC. Password ");
  89. System. Out. println ("JDBC. Password =" + password );

  90. Class. Forname (driver). newinstance ();
  91. ReturnJava. SQL.Drivermanager. Getconnection (URL, username, password );
  92. }
  93. Catch(ExceptionEx ){
  94. Ex. printstacktrace ();
  95. Throw New Runtimeexception(EX. getmessage ());
  96. }
  97. }

  98. /**
  99. * Encapsulate the query result into a list. <Br>
  100. * 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.
  101. * @ Param Rs resultset
  102. * @ Return list
  103. * @ Throws java. SQL. sqlexception
  104. */
  105. Public Static ListResultsettolist (ResultsetRS)ThrowsJava. SQL.Sqlexception{
  106. If(Rs =Null)Return Collections. Empty_list;

  107. ResultsetmetadataMD = Rs. getmetadata ();
  108. IntColumncount = md. getcolumncount ();

  109. ListList =New Arraylist();
  110. MapRowdata;
  111. While(Rs. Next ()){
  112. Rowdata =New Hashmap(Columncount );
  113. For(IntI = 1; I <= columncount; I ++ ){
  114. Rowdata. Put (Md. getcolumnname (I), RS. GetObject (I ));
  115. }
  116. List. Add (rowdata );
  117. }
  118. ReturnList;
  119. }

  120. /**
  121. * Disable resultset, statement, and connection.
  122. * @ Param Rs resultset to be closed
  123. * @ Param stmt statement or preparedstatement to be closed
  124. * @ Param conn connection to be closed
  125. */
  126. Public Static VoidClose (ResultsetRS,StatementStmt,ConnectionConn ){
  127. If(RS! =Null)Try{
  128. Rs. Close ();
  129. }Catch(Java. SQL.SqlexceptionEx ){
  130. Ex. printstacktrace ();
  131. }
  132. If(Stmt! =Null)Try{
  133. Stmt. Close ();
  134. }Catch(Java. SQL.SqlexceptionEx ){
  135. Ex. printstacktrace ();
  136. }
  137. If(Conn! =Null)Try{
  138. Conn. Close ();
  139. }Catch(Java. SQL.SqlexceptionEx ){
  140. Ex. printstacktrace ();
  141. }
  142. }

  143. }// End of dbui
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.