代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户注册</title>
</head>
<body>
<form autocomplete="off">
姓名:<input type="text" id="username">
<span id="uSpan"></span>
<br>
密码:<input type="password" id="password">
<br>
<input type="submit" value="注册">
</form>
</body>
<script>
//1.为姓名绑定失去焦点事件
document.getElementById("username").onblur = function() {
//2.创建XMLHttpRequest核心对象
let xmlHttp = new XMLHttpRequest();
//3.打开链接
let username = document.getElementById("username").value;
xmlHttp.open("GET","userServlet?username="+username,true);
//xmlHttp.open("GET","userServlet?username="+username,false);
//4.发送请求
xmlHttp.send();
//5.处理响应
xmlHttp.onreadystatechange = function() {
//判断请求和响应是否成功
if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
//将响应的数据显示到span标签
document.getElementById("uSpan").innerHTML = xmlHttp.responseText;
}
}
}
</script>
</html>
package com.itheima01;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/userServlet")
public class UserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设置请求和响应的乱码
req.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=UTF-8");
//1.获取请求参数
String username = req.getParameter("username");
//模拟服务器处理请求需要5秒钟
/*try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}*/
//2.判断姓名是否已注册
if("zhangsan".equals(username)) {
resp.getWriter().write("用户名已注册");
}else {
resp.getWriter().write("用户名可用");
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户注册</title>
</head>
<body>
<form autocomplete="off">
姓名:<input type="text" id="username">
<span id="uSpan"></span>
<br>
密码:<input type="password" id="password">
<br>
<input type="submit" value="注册">
</form>
</body>
<script src="js/jquery-3.3.1.min.js"></script>
<script>
//1.为用户名绑定失去焦点事件
$("#username").blur(function () {
let username = $("#username").val();
//2.jQuery的GET方式实现AJAX
$.get(
//请求的资源路径
"userServlet",
//请求参数
"username=" + username,
//回调函数
function (data) {
//将响应的数据显示到span标签
$("#uSpan").html(data);
},
//响应数据形式
"text"
);
});
</script>
</html>
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户注册</title>
</head>
<body>
<form autocomplete="off">
姓名:<input type="text" id="username">
<span id="uSpan"></span>
<br>
密码:<input type="password" id="password">
<br>
<input type="submit" value="注册">
</form>
</body>
<script src="js/jquery-3.3.1.min.js"></script>
<script>
//1.为用户名绑定失去焦点事件
$("#username").blur(function () {
let username = $("#username").val();
//2.jQuery的POST方式实现AJAX
$.post(
//请求的资源路径
"userServlet",
//请求参数
"username=" + username,
//回调函数
function (data) {
//将响应的数据显示到span标签
$("#uSpan").html(data);
},
//响应数据形式
"text"
);
});
</script>
</html>
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户注册</title>
</head>
<body>
<form autocomplete="off">
姓名:<input type="text" id="username">
<span id="uSpan"></span>
<br>
密码:<input type="password" id="password">
<br>
<input type="submit" value="注册">
</form>
</body>
<script src="js/jquery-3.3.1.min.js"></script>
<script>
//1.为用户名绑定失去焦点事件
$("#username").blur(function () {
let username = $("#username").val();
//2.jQuery的通用方式实现AJAX
$.ajax({
//请求资源路径
url:"userServlet",
//是否异步
async:true,
//请求参数
data:"username="+username,
//请求方式
type:"POST",
//数据形式
dataType:"text",
//请求成功后调用的回调函数
success:function (data) {
//将响应的数据显示到span标签
$("#uSpan").html(data);
},
//请求失败后调用的回调函数
error:function () {
alert("操作失败...");
}
});
});
</script>
</html>
json转换代码:
User类:
package com.itheima02;
public class User {
private String name;
private Integer age;
public User() {
}
public User(String name, Integer age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
测试类:
package com.itheima02;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import java.util.ArrayList;
import java.util.HashMap;
/*
JSON转换工具的使用
*/
public class ObjectMapperTest {
private ObjectMapper mapper = new ObjectMapper();
/*
1.User对象转json, json转User对象
json字符串 = {"name":"张三","age":23}
user对象 = User{name='张三', age=23}
*/
@Test
public void test01() throws Exception{
//User对象转json
User user = new User("张三",23);
String json = mapper.writeValueAsString(user);
System.out.println("json字符串:" + json);
//json转User对象
User user2 = mapper.readValue(json, User.class);
System.out.println("java对象:" + user2);
}
/*
2.map转json, json转map
json字符串 = {"姓名":"张三","性别":"男"}
map对象 = {姓名=张三, 性别=男}
*/
@Test
public void test02() throws Exception{
//map转json
HashMap<String,String> map = new HashMap<>();
map.put("姓名","张三");
map.put("性别","男");
String json = mapper.writeValueAsString(map);
System.out.println("json字符串:" + json);
//json转map
HashMap<String,String> map2 = mapper.readValue(json, HashMap.class);
System.out.println("java对象:" + map2);
}
/*
3.map转json, json转map
json字符串 = {"黑马一班":{"name":"张三","age":23},"黑马二班":{"name":"李四","age":24}}
map对象 = {黑马一班=User{name='张三', age=23}, 黑马二班=User{name='李四', age=24}}
*/
@Test
public void test03() throws Exception{
//map转json
HashMap<String,User> map = new HashMap<>();
map.put("一班",new User("张三",23));
map.put("二班",new User("李四",24));
String json = mapper.writeValueAsString(map);
System.out.println("json字符串:" + json);
//json转map
//HashMap map2 = mapper.readValue(json,new TypeReference>(){});
HashMap<String,User> map2 = mapper.readValue(json, new TypeReference<HashMap<String, User>>() {
});
System.out.println("java对象:" + map2);
}
/*
4.List转json, json转 List
json字符串 = ["张三","李四"]
list对象 = [张三, 李四]
*/
@Test
public void test04() throws Exception{
//List转json
ArrayList<String> list = new ArrayList<>();
list.add("张三");
list.add("李四");
String json = mapper.writeValueAsString(list);
System.out.println("json字符串:" + json);
//json转 List
ArrayList<String> list2 = mapper.readValue(json,ArrayList.class);
System.out.println("java对象:" + list2);
}
/*
5.List转json, json转List
json字符串 = [{"name":"张三","age":23},{"name":"李四","age":24}]
list对象 = [User{name='张三', age=23}, User{name='李四', age=24}]
*/
@Test
public void test05() throws Exception{
//List转json
ArrayList<User> list = new ArrayList<>();
list.add(new User("张三",23));
list.add(new User("李四",24));
String json = mapper.writeValueAsString(list);
System.out.println("json字符串:" + json);
//json转List
// ArrayList list2 = mapper.readValue(json,new TypeReference>(){});
ArrayList<User> list2 = mapper.readValue(json, new TypeReference<ArrayList<User>>() {
});
System.out.println("java对象:" + list2);
}
}
-- 创建db10数据库
CREATE DATABASE db10;
-- 使用db10数据库
USE db10;
-- 创建user表
CREATE TABLE USER(
id INT PRIMARY KEY AUTO_INCREMENT, -- 主键id
NAME VARCHAR(20), -- 姓名
age INT, -- 年龄
search_count INT -- 搜索数量
);
-- 插入测试数据
INSERT INTO USER VALUES (NULL,'张三',23,25),(NULL,'李四',24,5),(NULL,'王五',25,3)
,(NULL,'赵六',26,7),(NULL,'张三丰',93,20),(NULL,'张无忌',18,23),(NULL,'张强',33,21),(NULL,'张果老',65,6);
代码:
User类:
package com.itheima.bean;
/*
用户的实体类
*/
public class User {
private Integer id; // 主键id
private String name; // 姓名
private Integer age; // 年龄
private Integer search_count; //搜索数量
public User() {
}
public User(Integer id, String name, Integer age, Integer search_count) {
this.id = id;
this.name = name;
this.age = age;
this.search_count = search_count;
}
public Integer getSearch_count() {
return search_count;
}
public void setSearch_count(Integer search_count) {
this.search_count = search_count;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
控制层(servlet):
package com.itheima.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.bean.User;
import com.itheima.service.UserService;
import com.itheima.service.impl.UserServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
@WebServlet("/userServlet")
public class UserServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设置请求和响应的编码
req.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=UTF-8");
//1.获取请求参数
String username = req.getParameter("username");
//2.调用业务层的模糊查询方法得到数据
UserService service = new UserServiceImpl();
List<User> users = service.selectLike(username);
//3.将数据转成JSON,响应到客户端
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(users);
resp.getWriter().write(json);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req,resp);
}
}
业务层:
package com.itheima.service.impl;
import com.itheima.bean.User;
import com.itheima.mapper.UserMapper;
import com.itheima.service.UserService;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class UserServiceImpl implements UserService {
@Override
public List<User> selectLike(String username) {
List<User> users = null;
SqlSession sqlSession = null;
InputStream is = null;
try {
//加载核心配置文件
is = Resources.getResourceAsStream("MyBatisConfig.xml");
//获取sqlSession工厂对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
//获取sqlSession对象
sqlSession = sqlSessionFactory.openSession(true);
//获取UserMapper的实现类对象
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//调用实现类的模糊查询方法
users = mapper.selectLike(username);
} catch (IOException e) {
e.printStackTrace();
}finally {
//释放资源
if(sqlSession != null){
sqlSession.close();
}
if(is != null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//返回结果到控制层
return users;
}
}
DAO层(UserMapper):
package com.itheima.mapper;
import com.itheima.bean.User;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface UserMapper {
/*
模糊查询
*/
@Select("SELECT * FROM USER WHERE name LIKE CONCAT('%',#{username},'%') ORDER BY search_count DESC LIMIT 0,4")
public abstract List<User> selectLike(String username);
}
html页面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户搜索</title>
<style type="text/css">
.content {
width: 643px;
margin: 100px auto;
text-align: center;
}
input[type='text'] {
width: 530px;
height: 40px;
font-size: 14px;
}
input[type='button'] {
width: 100px;
height: 46px;
background: #38f;
border: 0;
color: #fff;
font-size: 15px
}
.show {
position: absolute;
width: 535px;
height: 100px;
border: 1px solid #999;
border-top: 0;
display: none;
}
</style>
</head>
<body>
<form autocomplete="off">
<div class="content">
<img src="img/logo.jpg">
<br/><br/>
<input type="text" id="username">
<input type="button" value="搜索一下">
<!--用于显示联想的数据-->
<div id="show" class="show"></div>
</div>
</form>
</body>
<script src="js/jquery-3.3.1.min.js"></script>
<script>
//1.为用户名输入框绑定鼠标点击事件
$("#username").mousedown(function () {
//2.获取用户输入的用户名
let username = $("#username").val();
//3.判断用户名是否为空
if(username == null || username == ""){
//4.如果为空,将联想框隐藏
$("#show").hide();
return;
}
//5.如果不为空,发送ajax请求,并将数据显示到联想框中
$.ajax({
//请求的资源路径
url:"userServlet",
//请求参数
data:{"username":username},
//请求方式
type:"POST",
//响应数据类型
dataType:"json",
//响应成功后的回调函数
success:function (data) {
//将返回的数据显示到show的div中
let names = "";
for(let i = 0; i < data.length; i++){
names += ""+data[i].name+"";
}
$("#show").html(names);
$("#show").show();
}
})
})
</script>
</html>
-- 创建db11数据库
CREATE DATABASE db11;
-- 使用db11数据库
USE db11;
-- 创建数据表
CREATE TABLE news(
id INT PRIMARY KEY AUTO_INCREMENT, -- 主键id
title VARCHAR(999) -- 新闻标题
);
-- 插入数据
DELIMITER $$
CREATE PROCEDURE create_data()
BEGIN
DECLARE i INT;
SET i=1;
WHILE i<=100 DO
INSERT INTO news VALUES (NULL,CONCAT('奥巴马罕见介入美国2020大选,警告民主党参选人须“基于现实”',i));
SET i=i+1;
END WHILE;
END
$$
-- 调用存储过程
CALL create_data();
代码:
News类:
package com.itheima.bean;
/*
新闻实体类
*/
public class News {
private Integer id; //主键id
private String title; //新闻标题
public News() {
}
public News(Integer id, String title) {
this.id = id;
this.title = title;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
控制层NewsServlet类:
package com.itheima.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.Page;
import com.itheima.service.NewsService;
import com.itheima.service.impl.NewsServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/newsServlet")
public class NewsServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设置请求和响应的编码
req.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=UTF-8");
//获取请求参数
String start = req.getParameter("start");
String pageSize = req.getParameter("pageSize");
//根据当前参数调用业务层的查询方法,得到分页page对象
NewsServiceImpl service = new NewsServiceImpl();
Page page = service.pageQuery(Integer.parseInt(start), Integer.parseInt(pageSize));
//将得到的数据转成json
String json = new ObjectMapper().writeValueAsString(page);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//将数据相应给客户
resp.getWriter().write(json);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req,resp);
}
}
业务层service类:
package com.itheima.service.impl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.mapper.NewsMapper;
import com.itheima.service.NewsService;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
public class NewsServiceImpl implements NewsService {
@Override
public Page pageQuery(Integer start, Integer pageSize) {
InputStream is = null;
SqlSession sqlSession = null;
Page page = null;
try{
//1.加载核心配置文件
is = Resources.getResourceAsStream("MyBatisConfig.xml");
//2.获取SqlSession工厂对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
//3.通过SqlSession工厂对象获取SqlSession对象
sqlSession = sqlSessionFactory.openSession(true);
//4.获取NewsMapper接口的实现类对象
NewsMapper mapper = sqlSession.getMapper(NewsMapper.class);
//5.封装Page对象 start:当前页码 pageSize:每页显示的条数
page = PageHelper.startPage(start,pageSize);
//6.调用实现类对象的查询全部方法,此时底层执行的就是MySQL的limit分页查询语句
mapper.selectAll();
} catch (Exception e) {
e.printStackTrace();
} finally {
//7.释放资源
if(sqlSession != null) {
sqlSession.close();
}
if(is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//8.返回page对象到控制层
return page;
}
}
DAO层NewsMapper类:
package com.itheima.mapper;
import com.itheima.bean.News;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface NewsMapper {
/*
查询全部
*/
@Select("SELECT * FROM news")
public abstract List<News> selectAll();
}
html页面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>网站首页</title>
<link rel="stylesheet" href="css/tt.css">
</head>
<body>
<div class="top">
<span class="top-left">下载APP</span>
<span class="top-left"> 北京 晴天</span>
<span class="top-right">更多产品</span>
</div>
<div class="container">
<div class="left">
<a>
<img src="img/logo.png"><br/>
</a>
<ul>
<li>
<a class="channel-item active" href="#">
<span>
推荐
</span>
</a>
</li>
<li><a class="channel-item" href="#">
<span>
视频
</span>
</a></li>
<li><a class="channel-item" href="#">
<span>
热点
</span>
</a></li>
<li><a class="channel-item" href="#">
<span>
直播
</span>
</a></li>
<li><a class="channel-item" href="#">
<span>
图片
</span>
</a></li>
<li><a class="channel-item" href="#">
<span>
娱乐
</span>
</a></li>
<li><a class="channel-item" href="#">
<span>
游戏
</span>
</a></li>
<li><a class="channel-item" href="#">
<span>
体育
</span>
</a></li>
</ul>
</div>
<div class="center">
<ul class="news_list">
<li>
<div class="title-box">
<a href="#" class="link">
奥巴马罕见介入美国2020大选,警告民主党参选人须“基于现实11”
<hr>
</a>
</div>
</li>
<li>
<div class="title-box">
<a href="#" class="link">
奥巴马罕见介入美国2020大选,警告民主党参选人须“基于现实22”
<hr>
</a>
</div>
</li>
<li>
<div class="title-box">
<a href="#" class="link">
奥巴马罕见介入美国2020大选,警告民主党参选人须“基于现实33”
<hr>
</a>
</div>
</li>
<li>
<div class="title-box">
<a href="#" class="link">
奥巴马罕见介入美国2020大选,警告民主党参选人须“基于现实44”
<hr>
</a>
</div>
</li>
<li>
<div class="title-box">
<a href="#" class="link">
奥巴马罕见介入美国2020大选,警告民主党参选人须“基于现实55”
<hr>
</a>
</div>
</li>
<li>
<div class="title-box">
<a href="#" class="link">
奥巴马罕见介入美国2020大选,警告民主党参选人须“基于现实66”
<hr>
</a>
</div>
</li>
<li>
<div class="title-box">
<a href="#" class="link">
奥巴马罕见介入美国2020大选,警告民主党参选人须“基于现实77”
<hr>
</a>
</div>
</li>
<li>
<div class="title-box">
<a href="#" class="link">
奥巴马罕见介入美国2020大选,警告民主党参选人须“基于现实88”
<hr>
</a>
</div>
</li>
<li>
<div class="title-box">
<a href="#" class="link">
奥巴马罕见介入美国2020大选,警告民主党参选人须“基于现实99”
<hr>
</a>
</div>
</li>
<li>
<div class="title-box">
<a href="#" class="link">
奥巴马罕见介入美国2020大选,警告民主党参选人须“基于现实1010”
<hr>
</a>
</div>
</li>
</ul>
<div class="loading" style="text-align: center; height: 80px">
<img src="img/loading2.gif" height="100%">
</div>
<div class="content">
<div class="pagination-holder clearfix">
<div id="light-pagination" class="pagination"></div>
</div>
</div>
<div id="no" style="text-align: center;color: red;font-size: 20px"></div>
</div>
</div>
</body>
<script src="js/jquery-3.3.1.min.js"></script>
<script>
//1.定义发送请求标记
let send = true;
//2.定义当前页码和每页显示的条数
let start = 1;
let pageSize = 10;
//3.定义滚动条距底部的距离
let battom = 1;
//4.设置页面加载事件
$(function () {
//5.为当前窗口绑定滚动条滚动事件
$(window).scroll(function () {
//6.获取必要信息,用于计算当前展示数据是否浏览完毕
//当前窗口的高度
let windowHeight = $(window).height();
//滚动条从上到下滚动距离
let scrollTop = $(window).scrollTop();
//当前文档的高度
let docHeight = $(document).height();
//7.计算当前展示数据是否浏览完毕
//当 滚动条距底部的距离 + 当前滚动条滚动的距离 + 当前窗口的高度 >= 当前文档的高度
if((battom + scrollTop + windowHeight) >= docHeight){
//8.判断请求标记是否为true
if(send == true){
//9.将请求标记置为false,当前异步操作完成前,不能重新发起请求。
send = false;
//10.根据当前页和每页显示的条数来 请求查询分页数据
queryByPage(start,pageSize);
//11.当前页码+1
start++;
}
}
});
});
//定义查询分页数据的函数
function queryByPage(start,pageSize){
//加载动图显示
$(".loading").show();
//发起AJAX请求
$.ajax({
//请求的资源路径
url:"newsServlet",
//请求的参数
data:{"start":start,"pageSize":pageSize},
//请求的方式
type:"POST",
//响应数据形式
dataType:"json",
//请求成功后的回调函数
success:function (data) {
if(data.length == 0) {
$(".loading").hide();
$("#no").html("我也是有底线的...");
return;
}
//加载动图隐藏
$(".loading").hide();
//将数据显示
let titles = "";
for(let i = 0; i < data.length; i++) {
titles += "\n" +
" \n" +
" ";
}
//显示到页面
$(".news_list").append(titles);
//将请求标记设置为true
send = true;
}
});
}
</script>
</html>
代码:
html页面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>网站首页</title>
<link rel="stylesheet" href="css/tt.css">
<link rel="stylesheet" href="css/simplePagination.css">
</head>
<body>
<div class="top">
<span class="top-left">下载APP</span>
<span class="top-left"> 北京 晴天</span>
<span class="top-right">更多产品</span>
</div>
<div class="container">
<div class="left">
<a>
<img src="img/logo.png"><br/>
</a>
<ul>
<li>
<a class="channel-item active" href="#">
<span>
推荐
</span>
</a>
</li>
<li><a class="channel-item" href="#">
<span>
视频
</span>
</a></li>
<li><a class="channel-item" href="#">
<span>
热点
</span>
</a></li>
<li><a class="channel-item" href="#">
<span>
直播
</span>
</a></li>
<li><a class="channel-item" href="#">
<span>
图片
</span>
</a></li>
<li><a class="channel-item" href="#">
<span>
娱乐
</span>
</a></li>
<li><a class="channel-item" href="#">
<span>
游戏
</span>
</a></li>
<li><a class="channel-item" href="#">
<span>
体育
</span>
</a></li>
</ul>
</div>
<div class="center">
<ul class="news_list">
</ul>
<div class="content">
<div class="pagination-holder clearfix">
<div id="light-pagination" class="pagination"></div>
</div>
</div>
</div>
</div>
</body>
<script src="js/jquery-3.3.1.min.js"></script>
<script src="js/jquery.simplePagination.js"></script>
<script>
//1.定义当前页码和每页显示的条数
let start = 1;
let pageSize = 10;
//2.调用查询数据的方法
queryByPage(start,pageSize);
//3.定义请求查询分页数据的函数,发起AJAX异步请求,将数据显示到页面
function queryByPage(start,pageSize) {
$.ajax({
//请求的资源路径
url:"newsServlet2",
//请求的参数
data:{"start":start,"pageSize":pageSize},
//请求的方式
type:"post",
//响应数据形式
dataType:"json",
//请求成功后的回调函数
success:function (pageInfo) {
//将数据显示到页面
let titles = "";
for(let i = 0; i < pageInfo.list.length; i++) {
titles += "\n" +
" \n" +
" ";
}
$(".news_list").html(titles);
//4.为分页按钮区域设置页数参数(总页数和当前页)
$("#light-pagination").pagination({
pages:pageInfo.pages,
currentPage:pageInfo.pageNum
});
//5.为分页按钮绑定单击事件,完成上一页下一页查询功能
$("#light-pagination .page-link").click(function () {
//获取点击按钮的文本内容
let page = $(this).html();
//如果点击的是Prev,调用查询方法,查询当前页的上一页数据
if(page == "Prev") {
queryByPage(pageInfo.pageNum - 1,pageSize);
}else if (page == "Next") {
//如果点击的是Next,调用查询方法,查询当前页的下一页数据
queryByPage(pageInfo.pageNum + 1,pageSize);
} else {
//调用查询方法,查询当前页的数据
queryByPage(page,pageSize);
}
});
}
});
}
</script>
</html>
控制层:
package com.itheima.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.itheima.bean.News;
import com.itheima.service.NewsService;
import com.itheima.service.impl.NewsServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
@WebServlet("/newsServlet2")
public class NewsServlet2 extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设置请求和响应的编码
req.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=UTF-8");
//1.获取请求参数
String start = req.getParameter("start");
String pageSize = req.getParameter("pageSize");
//2.根据当前页码和每页显示的条数来调用业务层的查询方法,得到分页Page对象
NewsService service = new NewsServiceImpl();
Page page = service.pageQuery(Integer.parseInt(start), Integer.parseInt(pageSize));
//3.封装PageInfo对象
PageInfo<List<News>> info = new PageInfo<>(page);
//4.将得到的数据转为JSON
String json = new ObjectMapper().writeValueAsString(info);
//5.将数据响应给客户端
resp.getWriter().write(json);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req,resp);
}
}
业务层:
package com.itheima.service.impl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.mapper.NewsMapper;
import com.itheima.service.NewsService;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
public class NewsServiceImpl implements NewsService {
@Override
public Page pageQuery(Integer start, Integer pageSize) {
InputStream is = null;
SqlSession sqlSession = null;
Page page = null;
try{
//1.加载核心配置文件
is = Resources.getResourceAsStream("MyBatisConfig.xml");
//2.获取SqlSession工厂对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
//3.通过SqlSession工厂对象获取SqlSession对象
sqlSession = sqlSessionFactory.openSession(true);
//4.获取NewsMapper接口的实现类对象
NewsMapper mapper = sqlSession.getMapper(NewsMapper.class);
//5.封装Page对象 start:当前页码 pageSize:每页显示的条数
page = PageHelper.startPage(start,pageSize);
//6.调用实现类对象的查询全部方法,此时底层执行的就是MySQL的limit分页查询语句
mapper.selectAll();
} catch (Exception e) {
e.printStackTrace();
} finally {
//7.释放资源
if(sqlSession != null) {
sqlSession.close();
}
if(is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//8.返回page对象到控制层
return page;
}
}
DAO层:
package com.itheima.mapper;
import com.itheima.bean.News;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface NewsMapper {
/*
查询全部
*/
@Select("SELECT * FROM news")
public abstract List<News> selectAll();
}