JSP allows you to add and analyze instances by page.

Source: Internet
Author: User

JSP allows you to add and analyze instances by page.

This example describes how to add a JSP file and display it by page. Share it with you for your reference. The details are as follows:

Objective:

① Further master the MVC design model;
② Master the implementation of the add function;
③ Master the implementation of the paging display function.

Main content:

① Use the user information adding function to further introduce the MVC mode;
② Introduce the principle and implementation of the paging display function through the paging display of user information.

1. How to add users in MVC mode?

First, consider how to interact with people: there should be an interface for entering user information, including the user name and password, and a feedback interface.

Then, consider how to implement the function: You need to add a method to the User class to complete the addition of User information.
Finally, consider the Controller: get the information, call JavaBean, pass the value, and select the interface response.

2. Add User Interface

There are many information items in the actual application, and the user input information must be verified. The process of adding is emphasized here, so the problem is simplified. You can modify it on the basis of the logon interface. The reference code is as follows:

<% @ Page contentType = "text/html; charset = gb2312 "%> Add User <br> <form name =" form1 "method =" post "action =" addUser "> User ID: <input type = "text" name = "username"> <br> password: <input type = "password" name = "userpass"> <br> <input type = "submit" value = "add"> <input type = "reset" value = "reset "> </form> <% @ include file =" contact. jsp "%>

3. Add a method to the User

Public boolean addUser () {Connection con = null; Statement stmt = null; boolean B; // indicates whether the Connection is successful. try {// specifies the driver Class required to connect to the database. forName ("oracle. jdbc. driver. oracleDriver "); // establish a connection with the database // you need to change myserver to the IP address of your database server // change mydb to your own database) con = DriverManager. getConnection ("jdbc: oracle: thin :@ myserver: 1521: mydb", "scott", "tiger "); // compile the SQL statement String SQL = "insert into usertable (username, userpass) value to query database information S ('"+ username +"', '"+ userpass +"') "; // create a statement object for executing the SQL statement stmt = con. createStatement (); // execute a statement that does not return a result set. The returned result is the number of records in the database table int n = stmt.exe cuteUpdate (SQL); if (n> 0) B = true; else B = false;} catch (Exception e) {B = false;} finally {// close related object if (stmt! = Null) try {stmt. close ();} catch (Exception ee) {}if (con! = Null) try {con. close () ;}catch (Exception ee) {}} return B ;}

4. Use Servlet for control

The reference code is as follows:

Package servlet; import java. io. *; import javax. servlet. *; import javax. servlet. http. *; import javabean. *; import java. util. *; public class AddUser extends HttpServlet {public void doGet (HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {request. setCharacterEncoding ("gb2312"); // Step 1: Obtain the user's input String username = request. getParameter ("username"); String userpass = Request. getParameter ("userpass"); // Step 2: Call JavaBean User user = new User (); user. setUsername (username); user. setUserpass (userpass); boolean B = user. addUser (); // Step 3: Pass the value String info; if (B) info = "added successfully! "; Else info =" failed to add! "; Request. setAttribute ("addinfo", info); // Step 4: Select an interface to respond to the user String forward = "getAllUser"; RequestDispatcher rd = request. getRequestDispatcher (forward); rd. forward (request, response);} public void doPost (HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {doGet (request, response );}}

After the adding is complete, the user will jump to the userlist. jsp file for processing, but the data needs to be obtained before the display, so the Servlet needs to be executed first, so the getAllUser controller is dedicated.

5. modify the configuration file

  <servlet>   <servlet-name>addUser</servlet-name>   <servlet-class>servlet.AddUser</servlet-class>  </servlet>  <servlet-mapping>   <servlet-name>addUser</servlet-name>   <url-pattern>/addUser</url-pattern>  </servlet-mapping>

6. display the prompt information on the List page.

Modify the userlist. jsp code as follows. The red part is the added content:

<% @ Page contentType = "text/html; charset = gb2312 "%> <% @ taglib prefix =" c "uri =" http://java.sun.com/jsp/jstl/core "%> <font color =" red ">$ {addinfo} </font> <br> <c: forEach var = "user" items = "$ {users}"> user name: $ {user. username} password: $ {user. userpass} <br> </c: forEach>

7. Run the test

Enter the correct username and password for testing;
Output an existing user name for testing.

8. Add pagination

After continuous addition, database tables already have a large number of records. When there are many records, it should be displayed by page. Pagination can be performed in multiple ways:

① Control in SQL and query only the required records;
② When traversing the result set, only relevant records are encapsulated;
③ Control the display.

The first method requires a high level of SQL for developers, and the third method delivers a large amount of data, so we will introduce the second method.

You need to modify the page display in three ways:

① Add a pagination hyperlink to the interface;
② Modify User. java to control the result set traversal. In addition, you need to increase the method for obtaining the number of page numbers;
③ Pass the required page number and total page number in the controller.

9. added the page display function on the interface.

<% @ Page contentType = "text/html; charset = gb2312 "%> <% @ taglib prefix =" c "uri =" http://java.sun.com/jsp/jstl/core "%> <font color =" red ">$ {addinfo} </font> <br> <a href = "getAllUser? PageNo = 1 "> page 1 </a> <a href =" getAllUser? PageNo =$ {pageNo-1} "> previous page </a> <a href =" getAllUser? PageNo =$ {pageNo + 1} "> next page </a> <a href =" getAllUser? PageNo =$ {pageCount} "> last page </a> <br> <c: forEach var =" user "items =" $ {users} "> user Name: $ {user. username} password: $ {user. userpass} <br> </c: forEach>

PageNo indicates the current page number, and pageCount indicates the total page number.

10. Add a method to obtain the total page number in User. java.

Public int getPageCount () {Connection con = null; Statement stmt = null; ResultSet rs = null; try {// specifies the driver Class required to connect to the database. forName ("oracle. jdbc. driver. oracleDriver "); // establish a connection with the database. con = DriverManager. getConnection ("jdbc: oracle: thin :@ myserver: 1521: mydb", "scott", "tiger "); // compile the SQL statement String SQL = "select count (*) from usertable" to query database information; // create a statement object for executing the SQL statement stmt = con. createStatement (); // run the SQL statement to complete the statement. Result set rs = stmt.exe cuteQuery (SQL); rs. next (); // obtain the total number of records int number = rs. getInt (1); return (number-1)/10 + 1;} catch (Exception e) {return 0;} finally {// close related object if (rs! = Null) try {rs. close ();} catch (Exception ee) {}if (stmt! = Null) try {stmt. close ();} catch (Exception ee) {}if (con! = Null) try {con. close () ;}catch (Exception ee ){}}}

11. added a method for obtaining information by page number.

Public ArrayList getUserByPage (int pageNo) {int number = 10; // number of records displayed on each page int begin = (pageNo * number)-9; int end = pageNo * number; int index = 1; Connection con = null; Statement stmt = null; ResultSet rs = null; ArrayList users = new ArrayList (); try {// specifies the driver Class required to connect to the database. forName ("oracle. jdbc. driver. oracleDriver "); // establish a connection with the database. con = DriverManager. getConnection ("jdbc: oracle: thin: @ 192.168.0. 170: 1521: fhdn "," scott "," tiger "); // write the SQL statement String SQL =" select * from usertable "for querying database information "; // create a statement object to execute the SQL statement stmt = con. createStatement (); // run the SQL statement to obtain the result set rs = stmt.exe cuteQuery (SQL); // traverse the result set while (rs. next () {// The record before in is not displayed if (index <begin) {index ++; continue ;} // The record after end does not display if (index> end) break; index ++; String username = rs. getString (1); String userpass = rs. getString (2); // java. util. Date birthday = rs. getDate (3); // int age = rs. getInt (4); User user = new User (); user. setUsername (username); user. setUserpass (userpass); users. add (user) ;}} catch (Exception e) {System. out. println (e. getMessage ();} finally {// close related object if (rs! = Null) try {rs. close ();} catch (Exception ee) {}if (stmt! = Null) try {stmt. close ();} catch (Exception ee) {}if (con! = Null) try {con. close ();} catch (Exception ee) {}} return users ;}

12. Modify the Controller

Package servlet; import java. io. *; import javax. servlet. *; import javax. servlet. http. *; import javabean. *; import java. util. *; public class GetAllUser extends HttpServlet {public void doGet (HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {// Step 1: Get user input String pageNo = request. getParameter ("pageNo"); int iPageNo = 1; if (pageNo! = Null) {iPageNo = Integer. parseInt (pageNo);} // Step 2: Call JavaBean User user = new User (); ArrayList users = null; users = user. getUserByPage (iPageNo); int pageCount = user. getPageCount (); // Step 3: Pass the value request. setAttribute ("users", users); request. setAttribute ("pageNo", new Integer (iPageNo); request. setAttribute ("pageCounter", new Integer (pageCount); // Step 4: Select an interface to respond to the user String forward = "userlist. jsp "; RequestDispatcher rd = request. getRequestDispatcher (forward); rd. forward (request, response);} public void doPost (HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {doGet (request, response );}}

13. Run the test later.

14. Added control over the first and last pages.

If you are already on the first page, you cannot click the first page or homepage. If you are already on the last page, you cannot click the last page or next page. Modify the code in userlist. jsp as follows (partial code ):

<C: if test = "$ {pageNo! = 1} "> <a href =" getAllUser? PageNo = 1 "> page 1 </a> <a href =" getAllUser? PageNo =$ {pageNo-1} "> previous page </a> </c: if> <c: if test =" $ {pageNo! = PageCounter} "> <a href =" getAllUser? PageNo =$ {pageNo + 1} "> next page </a> <a href =" getAllUser? PageNo =$ {pageCounter} "> last page </a> </c: if>

This parameter is set to not display, or to not add a hyperlink.

15. Added handling of exceptions.

If the user accesses: http: // 127.0.0.1: 8080/ch8/getAllUser? PageNo = aaa, an exception will occur. Because the page number is not a number, an exception is required. Modify:
Copy codeThe Code is as follows: iPageNo = Integer. parseInt (pageNo );
Is:
Copy codeThe Code is as follows: try {iPageNo = Integer. parseInt (pageNo);} catch (Exception e ){}

I hope this article will help you with JSP program design.

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.