Analysis of JSP Adding Function and Paging Display Example
- 2021-08-12 03:16:45
- OfStack
In this paper, an example is given to describe the method of adding functions and paging display in JSP. Share it for your reference. The details are as follows:
Learning objectives:
① Take one step to master MVC design pattern;
Grasp the realization of adding function;
③ Master the realization of paging display function.
Main contents:
(1) Introduce MVC mode in one step through the user information addition function;
2. Introduce the principle and realization of paging display function through 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 user name and password, and an interface for feedback.
Then consider how to realize the function: we need to add a method in User class to complete the addition of user information.
Finally, consider the controller: obtain information; Call JavaBean; Value transfer; Select the interface response.
2. Add user interface
There are many information items in practical application, and it is necessary to verify the information input by users. The emphasis here is on the addition process, so the problem is simplified. It 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">
Users 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. Adding methods to User
public boolean addUser()
{
Connection con = null;
Statement stmt = null;
boolean b; // Indicates whether the addition was successful or not
try{
// Indicate the drivers needed to connect to the database
Class.forName("oracle.jdbc.driver.OracleDriver");
// Establish a connection with the database
// Need to put myserver To modify to your own database server IP Address
// Put mydb Modify to your own database)
con = DriverManager.getConnection("jdbc:oracle:thin:@myserver:1521:mydb","scott","tiger");
// Object for querying database information SQL Statement
String sql="insert into usertable(username,userpass) values('"+username+"','"+userpass+"')";
// Creates a statement object for executing SQL Statement
stmt = con.createStatement();
// Execute a statement that returns no result set, which returns the number of records in the affected database table
int n = stmt.executeUpdate(sql);
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 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");
// No. 1 1 Step: Get the user's input information
String username = request.getParameter("username");
String userpass = request.getParameter("userpass");
// No. 1 2 Step: Call JavaBean
User user = new User();
user.setUsername(username);
user.setUserpass(userpass);
boolean b = user.addUser();
// No. 1 3 Step: Pass the value
String info;
if(b)
info=" Add successfully! ";
else
info=" Add failed! ";
request.setAttribute("addinfo",info);
// No. 1 4 Step: Select 1 Interfaces respond to users
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 here, jump to userlist. jsp file processing, but need to get data before displaying, so need to execute Servlet first, so it is dedicated to 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 prompt information in the list interface
Modify the userlist. jsp code 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
Enter the correct user name and password to test;
Output the existing user name for testing.
8. Add paging display
After continuous addition, there are already a large number of records in the database tables. When there are many records, they should be paged. Paging can be displayed in many ways:
(1) Control in SQL, only query the required records;
When traversing the result set, only the related records are encapsulated;
③ Control when displaying.
The first method requires a high level of SQL for developers, and the third method transmits a large amount of data, so we introduce the second method.
To complete the paging display, you need to make three modifications:
(1) Add hyperlinks displayed by paging on the interface;
② Modify User. java to control when traversing the result set, and increase the method of obtaining the number of page numbers;
③ Pass the required page number and total page number in the controller.
9. Add paging display function to 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"> No. 1 1 Page </a>
<a href="getAllUser?pageNo=${pageNo-1}"> Upper 1 Page </a>
<a href="getAllUser?pageNo=${pageNo+1}"> Under 1 Page </a>
<a href="getAllUser?pageNo=${pageCount}"> Finally 1 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 and pageCount represents the total number of pages.
10. Add the method of obtaining the total page number in User. java
public int getPageCount()
{
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try{
// Indicate the drivers needed to connect to the database
Class.forName("oracle.jdbc.driver.OracleDriver");
// Establish a connection with the database
con = DriverManager.getConnection("jdbc:oracle:thin:@myserver:1521:mydb","scott","tiger");
// Object for querying database information SQL Statement
String sql="select count(*) from usertable";
// Creates a statement object for executing SQL Statement
stmt = con.createStatement();
// Execute SQL Statement to get the result set
rs = stmt.executeQuery(sql);
rs.next();
// Get the total number of records
int number = 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 method of obtaining information by page number
public ArrayList getUserByPage(int pageNo)
{
int number=10;
// Every 1 Number of records displayed on the 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{
// Indicate the drivers needed to connect to the database
Class.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");
// Object for querying database information SQL Statement
String sql="select * from usertable";
// Creates a statement object for executing SQL Statement
stmt = con.createStatement();
// Execute SQL Statement to get the result set
rs = stmt.executeQuery(sql);
// Traversing the result set
while(rs.next())
{
// In begin Previous records are not displayed
if(index<begin){
index++;
continue;
}
// In end Subsequent records are not displayed either
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 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
{
// No. 1 1 Step: Get the user's input information
String pageNo=request.getParameter("pageNo");
int iPageNo=1;
if(pageNo!=null)
{
iPageNo = Integer.parseInt(pageNo);
}
// No. 1 2 Step: Call JavaBean
User user = new User();
ArrayList users=null;
users = user.getUserByPage(iPageNo);
int pageCount=user.getPageCount();
// No. 1 3 Step: Pass the value
request.setAttribute("users",users);
request.setAttribute("pageNo",new Integer(iPageNo));
request.setAttribute("pageCounter",new Integer(pageCount));
// No. 1 4 Step: Select 1 Interfaces respond to users
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, and then run the test
14. Increase control over page 1 and last page
If you are already on Page 1, you can no longer click on Page 1 or Home. If you are already on the last page, you can't click on 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"> No. 1 1 Page </a>
<a href="getAllUser?pageNo=${pageNo-1}"> Upper 1 Page </a>
</c:if>
<c:if test="${pageNo!=pageCounter}">
<a href="getAllUser?pageNo=${pageNo+1}"> Under 1 Page </a>
<a href="getAllUser?pageNo=${pageCounter}"> Finally 1 Page </a>
</c:if>
It is set to not display here, or it can be set to not add hyperlinks.
15. Increase the handling of exceptions
If the user accesses in this way: http://127.0.0.1: 8080/ch8/getAllUser? pageNo = aaa, an exception will be generated. Because the page number is not a number, exception handling is required. Modification:
iPageNo = Integer.parseInt(pageNo);
Is:
try{ iPageNo = Integer.parseInt(pageNo); }catch(Exception e){}
I hope this article is helpful to everyone's JSP programming.