JSP training (8) -- add functions and display on pages

Source: Internet
Author: User

Objective: To further master the MVC design mode, to master the implementation of the add function, and to master the implementation of the paging display function. Main Content: l introduce the MVC mode through the user information addition function; l 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. There are many information items in the actual application of the added user interface, 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 the public Boolean adduser () {connection con = NULL in the user; statement stmt = NULL; Boolean B; // indicates whether the database is successfully added. 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) values ('" + username + "', '" + userpass + "') to query database information "') "; // 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 the servlet for control reference code: 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 input string username = request. getparameter ("username"); string userpass = request. getparameter ("userpass"); // Step 2: Call JavaBean 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 adding the parameter, jump to the userlist. JSP file processing, but data needs to be obtained before display, so the servlet needs to be executed first, so it is dedicated to getalluser Control. 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. On the list page, a message is displayed, prompting you to modify the userlist. the JSP code is as follows, and 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 and enter the correct user name and password for testing. output the existing user name for testing. 8. The page display is continuously added, and a large number of records are already in the database table. When there are many records, it should be displayed by page. Paging display can be performed in multiple ways: l control in SQL to query only the required records; l encapsulate only relevant records when traversing the result set; l 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. To display the page by page, you need to make three changes: l add a pagination hyperlink on the interface; l modify the user. java: controls the result set traversal. In addition, you need to increase the method for obtaining the number of page numbers. l transfer the required page number and total page number to the Controller. 9. added the page display function <% @ 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> where pageno indicates the current page number and pagecount indicates the total page number. 10. In user. add public int getpagecount () {connection con = NULL; statement stmt = NULL; resultset rs = NULL in Java; 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. creat Estatement (); // run the SQL statement to obtain the 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 the 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 "); // creation and Data Connection between libraries con = drivermanager. getconnection ("JDBC: oracle: thin: @ 192.168.0.170: 1521: fhdn", "Scott", "Tiger "); // compile the SQL statement string SQL = "select * From usertable" for querying database information; // create a statement object for executing 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 the end does not display if (index> end) break; index ++; string usern Ame = 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. getparam Eter ("pageno"); int ipageno = 1; if (pageno! = NULL) {ipageno = integer. parseint (pageno);} // Step 2: Call JavaBean 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 "; reques Tdispatcher RD = request. getrequestdispatcher (forward); Rd. forward (request, response);} public void dopost (httpservletrequest request, httpservletresponse response) throws ioexception, servletexception {doget (request, response );}} 13. Test and run again. 14. Add control over the first and last pages. If the control is 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} "> the last page </a> </C: If> is not displayed, or you can choose not to add a hyperlink. 15. Add Exception Handling. If the user accesses http: // 127.0.0.1: 8080/ch8/getalluser in this way? Pageno = aaa, an exception will occur. Because the page number is not a number, an exception is required. Modify ipageno = integer. parseint (pageno); To try {ipageno = integer. parseint (pageno);} catch (exception e ){}

 

Reference material: Basic tutorial on Java Web Programming

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.