This article describes the JSP implementation of adding functionality and paging display methods. Share to everyone for your reference. Specifically as follows:
Learning objectives:
① further grasps the MVC design pattern;
② Mastering the realization of adding function;
③ Master the realization of pagination display function.
Main content:
① the MVC pattern through the user information adding function;
② introduces the principle and implementation of pagination display through the paging display of user information.
1, how to use the MVC pattern to complete the user add?
First consider how you interact with people: you should have an interface for entering user information, including username and password, and a feedback interface.
Then consider how the functionality is implemented: you need to add a method to the user class to complete the addition of your information.
Finally, consider the controller: Get information, call JavaBean, transfer value, select interface Response.
2, add user's interface
The information items in the actual application are more, and the user input information needs to be validated. The emphasis here is on adding the process, so the problem is simplified. Can be modified on the basis of the login 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 method in the user
public boolean addUser ()
{
Connection con = null;
Statement stmt = null;
Boolean B; Indicates whether the Add Success
try{
//Indicates the driver required to connect to the database
class.forname ("Oracle.jdbc.driver.OracleDriver");
Establish a connection to the database/
/need to modify the IP address of the MyServer to its own database server
//change mydb to its own database)
con = drivermanager.getconnection (" Jdbc:oracle:thin: @myserver: 1521:mydb ", Scott", "Tiger");
SQL statement to write query database information
String sql= "insert into usertable (Username,userpass) VALUES (' +username+" ', ' "+userpass+ ')" ;
Creates a statement object that executes the SQL statement
stmt = Con.createstatement ();
Executes a statement that does not return a result set, and returns the number of
int n = stmt.executeupdate (SQL) that affects the records in the database table;
if (n>0)
B = true;
else
B = false;
catch (Exception e) {
b = false;
}
finally{
//Close related objects
if (stmt!=null) try{stmt.close ();} catch (Exception ee) {}
if (con!=null) try{con.close ();} catch (Exception ee) {}
} return
B;
}
4. Use servlet to 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");
First step: Get user input information String username = request.getparameter ("username");
String Userpass = Request.getparameter ("Userpass");
Step two: Invoke JavaBean user user = new user ();
User.setusername (username);
User.setuserpass (Userpass);
Boolean B = User.adduser ();
Step three: Pass the value String info; if (b) info= "Add success!"
"; Else info= "Add failed!"
";
Request.setattribute ("Addinfo", info);
Fourth step: 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 completion of the add to userlist.jsp file processing, but before the display needs to get the data, so you need to execute the servlet, so the Getalluser controller.
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 in the list interface
Modify the userlist.jsp code as follows, and the red section is for 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}" >
username: ${user.username} password: ${user.userpass} <br>
</c: Foreach>
7, run the test
Enter the correct username and password test;
Test the output of a user name that already exists.
8, add pagination display
After constant addition, there are already a lot of records in the database table. When the record is more, it should be paged display. Pagination display can take several ways:
① in the SQL control, only to query the required records;
② only encapsulates the relevant records when traversing the result set;
The ③ is controlled at the time of display.
The first approach to the developer's SQL level requirements are higher, the third way the amount of data transmission is relatively large, so we introduce the second.
To complete the paging display, you need to make 3 modifications:
① on the interface to increase the paging display of hyperlinks;
② Modify the User.java, when traversing the result set control, another need to increase the number of pages to obtain the method;
③ the required page number and total page number in the controller.
9, in the interface to increase the paging 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 "> First page </a>
<a href=" getalluser?pageno=${pageno-1} "> Prev </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 represents the current page number, PageCount represents the total page count.
10, in the User.java to increase the total number of ways to get
public int Getpagecount ()
{
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try{
//Indicates the driver required to connect to the database
class.forname ("Oracle.jdbc.driver.OracleDriver");
Establish a connection to the database
con = drivermanager.getconnection ("Jdbc:oracle:thin: @myserver: 1521:mydb", "Scott", "Tiger");
SQL statement to write query database information
String sql= "SELECT COUNT (*) from usertable";
Creates a statement object that executes the SQL statement
stmt = Con.createstatement ();
Execute the SQL statement to get the result set
rs = stmt.executequery (sql);
Rs.next ();
Get the total number of records
int = rs.getint (1);
Return (number-1)/10+1;
} catch (Exception e) {return
0;
}
finally{
//Close related objects
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. Increase the way to get information by page number
Public ArrayList getuserbypage (int pageno) {int number=10;
The number of records displayed on each page int begin = (PageNo *)-9;
int end = PageNo * number;
int index=1;
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
ArrayList users = new ArrayList ();
try{//Indicates the driver required to connect to the database Class.forName ("Oracle.jdbc.driver.OracleDriver");
Establish a connection to the database con = drivermanager.getconnection ("Jdbc:oracle:thin:@192.168.0.170:1521:fhdn", "Scott", "Tiger");
Write a SQL statement that queries database information String sql= "SELECT * from Usertable";
Creates a statement object that executes the SQL statement stmt = con.createstatement ();
Execute the SQL statement to get the result set rs = stmt.executequery (SQL);
Traversal of the result set while (Rs.next ()) {//record before begin is not displayed if (index<begin) {index++;
Continue
The record after end does not show the 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 objects 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 to users;
}
12, modify 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 {//First step: Get user input information String pageno=request.getparameter ("PageNo");
int ipageno=1;
if (pageno!=null) {Ipageno = Integer.parseint (PageNo);
//Step Two: Invoke JavaBean user user = new user ();
ArrayList Users=null;
Users = User.getuserbypage (Ipageno);
int Pagecount=user.getpagecount ();
Step three: Transfer value Request.setattribute ("Users", users);
Request.setattribute ("PageNo", New Integer (Ipageno));
Request.setattribute ("PageCounter", New Integer (PageCount));
Fourth step: 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, then the test run
14, increase the control of the first and last page
If you are already on the first page, you can no longer click on the first page or homepage. If you are already on the last page, you cannot click the last page or the next page. Modify the code in userlist.jsp as follows (partial code):
<c:if test= "${pageno!=1}" >
<a href= "getalluser?pageno=1" > First page </a>
<a href= "Getalluser ? Pageno=${pageno-1} "> Prev </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 is set to not display, or it can be set to not add hyperlinks.
15, increase the handling of the exception
If the user accesses: Http://127.0.0.1:8080/ch8/getAllUser?pageNo=aaa in this way, an exception is generated. Because the page number is not a number, exception handling is required. Modify:
Copy Code code as follows:
Ipageno = Integer.parseint (PageNo);
For:
Copy Code code as follows:
try{Ipageno = Integer.parseint (PageNo);} catch (Exception e) {}
I hope this article will help you with the JSP program design.