search
HomeWeb Front-endJS TutorialIntroduction to json implementation of jsp paging examples

json has been introduced in detail in the previous article. JSON is easy to understand and fast to transmit. And it can be integrated well with javascript.
The jsp paging problem can be solved very well without adding jar.
The following is a detailed introduction to paging examples:

Introduction to json implementation of jsp paging examples

##The effect is as shown in the figure, using jsp+servlet technology

First: write a javaBean User.java

package bean; 
public class User { 
private int id; 
private String name; 
private String password; 
private int age; 
public User() { 
super(); 
} 
public User(int id, String name, String password, int age) { 
super(); 
this.id = id; 
this.name = name; 
this.password = password; 
this.age = age; 
} 
public int getId() { 
return id; 
} 
public void setId(int id) { 
this.id = id; 
} 
public String getName() { 
return name; 
} 
public void setName(String name) { 
this.name = name; 
} 
public String getPassword() { 
return password; 
} 
public void setPassword(String password) { 
this.password = password; 
} 
public int getAge() { 
return age; 
} 
public void setAge(int age) { 
this.age = age; 
} 
@Override 
public String toString() { 
//{'id':1,'name':'zhangsan','password':'123','age':1} 
return "{'id':"+id+",'name':'"+name+"','password':'"+password+"','age':"+age+"}"; 
} 

}

What you need to pay attention to here is the change of toString method

Then: let’s write its control layer and Dao layer
In order to simplify the code and facilitate value acquisition, the database is temporarily written as a collection
You can see To,
1.service receives the request request to get the current page to be displayed (page page)
2.Create a string, add the user obtained from the database DB in sequence, and encapsulate all data

[{},{},{}]

3. Return this string to the request page

package servlet; 
import java.io.IOException; 
import java.io.PrintWriter; 
import java.util.LinkedList; 
import java.util.List; 
import javax.servlet.ServletException; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
import bean.User; 
public class Paging extends HttpServlet { 
public static final int PER_PAGE = 3; 
@Override 
protected void service(HttpServletRequest request, HttpServletResponse response) 
throws ServletException, IOException { 
//分页 数据源 当前得到第几页的记录 每页显示多少条 
int page = Integer.parseInt(request.getParameter("page")); 
// page = 1 i = 0 
//page = 2 3 
int length = 0;//记录当前拿了多少条 
StringBuffer sb = new StringBuffer(); 
sb.append("["); 
//[{},{},{}] 
String message = null; 
if(page >= 1 && page <= 3){ 
for (int i = (page-1)*PER_PAGE; i < DB.list.size()&&length < PER_PAGE; i++) { 
User u = DB.list.get(i); 
sb.append(u.toString()+","); 
length++; 
} 
if(length > 0){ 
message = sb.substring(0, sb.length()-1)+"]"; 
}else{ 
message = sb.toString()+"]"; 
} 
}else{ 
response.setContentType("text/html;charset=utf-8"); 
response.getWriter().println("捣乱"); 
return; 
} 
response.setContentType("text/html;charset=utf-8"); 
response.getWriter().println(message); 
} 
} 
class DB{ 
public static List<User> list = new LinkedList<User>(); 
static{ 
list.add(new User(1,"zhangsan","zs",34)); 
list.add(new User(2,"lisi","ls",34)); 
list.add(new User(3,"a","h",34)); 
list.add(new User(4,"b","d",34)); 
list.add(new User(5,"c","g",34)); 
list.add(new User(6,"d","a",34)); 
list.add(new User(7,"e","d",34)); 
list.add(new User(8,"f","e",34)); 
list.add(new User(9,"g","a",34)); 
} 
}

After filling in the jsp, submit the page asynchronously through ajax, and then get the corresponding string

var mgs = xmlHttpRequest.responseText; 
var persons = mgs.evalJSON();

Convert json The data is parsed and added to the displayed area

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> 
<% 
String path = request.getContextPath(); 
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 
%> 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html> 
<head> 
<base href="<%=basePath%>"> 
<title>My JSP &#39;regist.jsp&#39; starting page</title> 
<meta http-equiv="pragma" content="no-cache"> 
<meta http-equiv="cache-control" content="no-cache"> 
<meta http-equiv="expires" content="0"> 
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 
<meta http-equiv="description" content="This is my page"> 
<script type="text/javascript" src="js/prototype1.6.js"></script> 
<script type="text/javascript" src="js/jquery-1.4.4.js"></script> 
<script type="text/javascript"> 
var paging = 0; 
// 
function page(p){ 
/*if(p == &#39;next&#39; && paging < 3){ 
paging ++; 
}else if(p == &#39;last&#39; && paging > 1) { 
paging --; 
}else{ 
alert(&#39;错误&#39;); 
}*/ 
if(p == &#39;next&#39; && paging < 3){ 
paging ++; 
if(paging > 1){ 
$(":button:eq(0)").removeAttr(&#39;disabled&#39;); 
} 
if(paging == 3){ 
$(":button:eq(1)").attr(&#39;disabled&#39;,&#39;disabled&#39;); 
} 
}else if(p == &#39;last&#39; && paging > 1){ 
paging --; 
$(":button:eq(1)").removeAttr(&#39;disabled&#39;); 
if(paging == 1){ 
$(":button:eq(0)").attr(&#39;disabled&#39;,&#39;disabled&#39;); 
} 
} 
createXmlHttpRequest(); 
xmlHttpRequest.onreadystatechange=back; 
var url = encodeURI("/json_page/Paging?page="+paging); 
xmlHttpRequest.open("GET",url,true); 
xmlHttpRequest.send(null); 
} 
//假设名字为xmlHttpRequest 
function createXmlHttpRequest(){ 
if(window.ActiveXObject){ 
xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP"); 
}else{ 
xmlHttpRequest = new XmlHttpRequest(); 
} 
} 
//回调函数 
function back(){ 
if( xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200){ 
var mgs = xmlHttpRequest.responseText; 
var persons = mgs.evalJSON(); 
//alert(mgs); 
$("table").empty(); 
$("table").append( $("<tr><td>id</td><td>用户名</td><td>密码</td><td>age</td></tr>")); 
for(var i = 0 ; i < persons.length;i++){ 
var person = persons[i]; 
var $tr = $("<tr><td>"+person.id+"</td><td>"+person.name+"</td><td>"+person.password+"</td><td>"+person.age+"</td></tr>"); 
$("table").append($tr); 
} 
} 
} 
</script> 
</head> 
<body> 
<input type="button" disabled="disabled" value="上一页" onclick="page(&#39;last&#39;);"/><input type="button" value="下一页" onclick = "page(&#39;next&#39;);"/> 
<table> 
<tr><td>id</td><td>用户名</td><td>密码</td><td>age</td></tr> 
</table> 
</body> 
</html>

In addition: these two js are required

<script type="text/javascript" src="js/prototype1.6.js"></script> 
<script type="text/javascript" src="js/jquery-1.4.4.js"></script>


More examples of json implementation of jsp paging (attached) Renderings) Please pay attention to the PHP Chinese website for related articles!


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Replace String Characters in JavaScriptReplace String Characters in JavaScriptMar 11, 2025 am 12:07 AM

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

jQuery Check if Date is ValidjQuery Check if Date is ValidMar 01, 2025 am 08:51 AM

Simple JavaScript functions are used to check if a date is valid. function isValidDate(s) { var bits = s.split('/'); var d = new Date(bits[2] '/' bits[1] '/' bits[0]); return !!(d && (d.getMonth() 1) == bits[1] && d.getDate() == Number(bits[0])); } //test var

jQuery get element padding/marginjQuery get element padding/marginMar 01, 2025 am 08:53 AM

This article discusses how to use jQuery to obtain and set the inner margin and margin values ​​of DOM elements, especially the specific locations of the outer margin and inner margins of the element. While it is possible to set the inner and outer margins of an element using CSS, getting accurate values ​​can be tricky. // set up $("div.header").css("margin","10px"); $("div.header").css("padding","10px"); You might think this code is

10 jQuery Accordions Tabs10 jQuery Accordions TabsMar 01, 2025 am 01:34 AM

This article explores ten exceptional jQuery tabs and accordions. The key difference between tabs and accordions lies in how their content panels are displayed and hidden. Let's delve into these ten examples. Related articles: 10 jQuery Tab Plugins

10 Worth Checking Out jQuery Plugins10 Worth Checking Out jQuery PluginsMar 01, 2025 am 01:29 AM

Discover ten exceptional jQuery plugins to elevate your website's dynamism and visual appeal! This curated collection offers diverse functionalities, from image animation to interactive galleries. Let's explore these powerful tools: Related Posts: 1

HTTP Debugging with Node and http-consoleHTTP Debugging with Node and http-consoleMar 01, 2025 am 01:37 AM

http-console is a Node module that gives you a command-line interface for executing HTTP commands. It’s great for debugging and seeing exactly what is going on with your HTTP requests, regardless of whether they’re made against a web server, web serv

Custom Google Search API Setup TutorialCustom Google Search API Setup TutorialMar 04, 2025 am 01:06 AM

This tutorial shows you how to integrate a custom Google Search API into your blog or website, offering a more refined search experience than standard WordPress theme search functions. It's surprisingly easy! You'll be able to restrict searches to y

jquery add scrollbar to divjquery add scrollbar to divMar 01, 2025 am 01:30 AM

The following jQuery code snippet can be used to add scrollbars when the div content exceeds the container element area. (No demonstration, please copy it directly to Firebug) //D = document //W = window //$ = jQuery var contentArea = $(this), wintop = contentArea.scrollTop(), docheight = $(D).height(), winheight = $(W).height(), divheight = $('#c

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.