JavaWeb--Ajax

一,Ajax简介

1.为什么要使用Ajax技术

通过在后台与服务器进行少量数据交换,Ajax 可以使页面实现异步更新。这意味着可以在不重新加载整个页面的情况下,对页面的某部分进行更新。

2,Ajax的应用场景

01,用户名检测

注册用户时,通过 Ajax 的形式,动态检测用户名是否被占用。

02,搜索提示

当输入搜索关键字时,通过 Ajax 的形式,动态加载搜索提示列表。

03,数据分页显示

当点击页码值的时候,通过 ajax 的形式,根据页码值动态刷新表格的数据。

04,数据的增删改查

数据的添加、删除、修改、查询操作,都需要通过 ajax 的形式,来实现数据的交互。

二,JSON简介

1,为什么要使用JSON

2,XML简介

比如说我有一个学生数据: name = "zhangsan" ; age = 22; gender = "男" ;

用 XML 表示:

XML 复制代码
<student>
 <name>zhangsan</name>
 <age>22</age>
 <gender>男</gender>
 </student>

用 JSON 表示:

XML 复制代码
{
 "name":"zhangsan",
 "age":22,
 "gender":"男"
}

3,JSON格式的特征

JSON是按照特定的语法规则所生成的字符串结构。

大括号表示JSON的字符串对象。{ }

属性和值用冒号分割。{"属性":"value"}

属性和属性之间用逗号分割。{"属性":"value","属性":"value",...}

中括号表示数组。[{"属性":"value"...},{"属性":"value"...}]

4,JSON的6种数据类型

三,FastJson是什么

1,Fastjson的使用场景

Fastjson已经被广泛使用在各种场景,包括cache存储、RPC通讯、MQ通讯、网络协议通讯、Android客户端、Ajax服务器处理程序等等。

2,Fastjson优点

01,速度快

02,使用广泛

03,测试完备

3,常用的JSON解析类库

四,下载和使用FastJson

1,序列化和反序列化java对象

使用FastJson将Java对象序列化为JSON字符串很简单,只需要调用FastJson提供的静态方法JSON.toJSONString()。

java 复制代码
User user = new User();
 user.setId(1);
 user.setName("张三");
 user.setAge(18);
 String jsonStr = JSON.toJSONString(user);
 System.out.println(jsonStr);

使用FastJson将JSON字符串反序列化为Java对象也很简单,只需要 调用FastJson提供的静态方法JSON.parseObject()。

java 复制代码
String jsonStr = "{\"id\":1,\"name\":\"张三\",\"age\":18}";
 User user = JSON.parseObject(jsonStr, 
User.class);
 System.out.println(user);

2,解析JSON字符串

FastJson提供了一个JSON类,可以方便地解析JSON字符串。

java 复制代码
String jsonStr = "{\"id\":1,\"name\":\"张三\",\"age\":18}";
 JSONObject jsonObject = JSON.parseObject(jsonStr);
 int id = jsonObject.getIntValue("id");
 String name = jsonObject.getString("name");
 int age = jsonObject.getIntValue("age");
 System.out.println(id + ", " + name + ", " + age);

3,使用注解控制序列化和反序列化

FastJson提供了一些注解,可以用于控制序列化和反序列化。@JSONField注解指定了JSON字段的名称、是否序列化、日期格式等属性。

java 复制代码
public class User {
 @JSONField(name = "userId")
 private int id;
 @JSONField(serialize = false)
 private String name;
 @JSONField(format = "yyyy-MM-dd HH:mm:ss")
 private Date birthday;
 // getter和setter方法
}

五,Ajax初体验

1,XMLHttpRequest对象

2,Ajax的使用步骤

01,创建XMLHttpRequest对象

java 复制代码
var xhr = new XMLHttpRequest();

02,给定请求方式以及请求地址

后端服务 ip地址+端口号+资源路径

java 复制代码
 xhr.open("get","http://v1.yiketianqi.com/api?
 unescape=1&version=v91&appid=43656176&appsecret
 =I42og6Lm&ext=&cityid=&city=");

03,发送请求

java 复制代码
xhr.send();

04,获取服务器端给客户端的响应数据

java 复制代码
 xhr.onreadystatechange = function(){
 //0:open()没有被调用
//1:open()正在被调用
//2:send()正在被调用
//3:服务端正在返回结果
//4:请求结束,并且服务端已经结束发送数据到客户端
if (this.readyState == 4 && this.status == 
200) {
 document.getElementById("demo").innerHTML = 
this.responseText;
        }
 }

六,Ajax实战案例

1,需求说明

需求

创建User类,包含id、name、age属性。

在用户管理页面中通过Ajax技术完成对用户数据载入、添加用户、更新用户、删除用户操作。

项目结构

2,搭建环境

数据库创建用户表

sql 复制代码
# 创建用户表
CREATE TABLE `user` (
 `id` int NOT NULL AUTO_INCREMENT,
 `name` varchar(255) DEFAULT NULL,
 `age` int DEFAULT NULL,
 PRIMARY KEY (`id`)
 ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT 
CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
 DELETE FROM `user`;
 # 添加用户
INSERT INTO `user` (id, name, age) VALUES
 (1, 'Jone', 18),
 (2, 'Jack', 20),
 (3, 'Tom', 28),
 (4, 'Sandy', 21),
 (5, 'Billie', 24);

编写实体类

编写实体类 User.java

java 复制代码
 /**
 * 用户表模型
*/
 public class User {
 // 序号
private Integer id;
 // 名字
private String name;
 // 年龄
 private Integer age;
 // 邮箱
public User(Integer id, String name, 
Integer age, String email) {
 this.id = id;
 this.name = name;
 this.age = age;
    }
 public User() {
    }
 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;
    }
 @Override
 public String toString() {
 return "User{" +
 "id=" + id +
 ", name='" + name + '\'' + ", age=" + age +'}';
    }
 }

统一结果返回集

java 复制代码
public class ResultAjax {
 // 返回致态码
private Integer code ;
 // 返回消息体
private String message;
 // 返回数据
private Object data;
 public ResultAjax() {
    }
 public ResultAjax(Integer code, String 
message, Object data) {
 this.code = code;
 this.message = message;
 this.data = data;
    }
 public Integer getCode() {
 return code;
    }
 public void setCode(Integer code) {
 this.code = code;
    }
 public String getMessage() {
 return message;
    }
 public void setMessage(String message) {
 this.message = message;
    }
 public Object getData() {
 return data;
    }
 public void setData(Object data) {
 this.data = data;
    }
 public static ResultAjax success(String 
message){
 return new 
ResultAjax(200,message,null);
    }
 public static ResultAjax success(Object 
object){
 return new 
ResultAjax(200,"success",object);
    }
 public static ResultAjax error(String 
message){
 return new 
ResultAjax(500,message,null);
    }
 }

3,编写数据库连接工具

创建数据库连接信息文件

在src目录下创建 druid.properties ,基于Druid连接池获取数据库连接工具类。

java 复制代码
 driverClassName=com.mysql.jdbc.Driver
 url=jdbc:mysql://localhost:3306/test?
 useSSL=false
 username=root
 password=123456
 initialSize=10
 maxActive=20

工具类

java 复制代码
/**
 * 基于Druid连接池获取数据库连接工具类
*/
 public class JdbcDruidUtil {
 //数据库连接池对象
private static DataSource dataSource;
 static{
 try {
 //获取读取配置文件的字节输入流对象
InputStream is = 
JdbcDruidUtil.class.getClassLoader().getResourc
 eAsStream("druid.properties");
 //创建Properties对象
Properties pop = new Properties();
 //加载配置文件
pop.load(is);
 //创建连接池对象
dataSource = 
DruidDataSourceFactory.createDataSource(pop);
         }catch(Exception e){
 e.printStackTrace();
         }
     }
 //获取数据库连接对象
public static Connection getConnection(){
 Connection connection = null;
 try {
 connection = 
dataSource.getConnection();
        } 
catch (SQLException throwables) {
 throwables.printStackTrace();
        }
 return connection;
    }
 //关闭连接对象
public static void 
closeConnection(Connection connection){
 try {
 connection.close();
        } 
catch (SQLException throwables) {
 throwables.printStackTrace();
        }
    }
 //关闭Statement对象
public static void closeStatement(Statement 
statement){
 try {
 statement.close();
        } 
catch (SQLException throwables) {
 throwables.printStackTrace();
        }
    }
 //关闭ResultSet
 public static void closeResultSet(ResultSet 
resultSet) {
 try {
 resultSet.close();
        } 
catch (SQLException throwables) {
 throwables.printStackTrace();
        }
    }
 //DML操作时关闭资源
public static void closeResource(Statement 
statement,Connection connection){
 //先关闭Statement对象
closeStatement(statement);
 //在关闭Connection对象
closeConnection(connection);
    }
 //查询时关闭资源
public static void closeResource(ResultSet 
resultSet,Statement statement,Connection 
connection){
 if (resultSet != null){
 //先关闭ResultSet
 closeResultSet(resultSet);
        }
 if (statement != null){
 //在闭Statement对象
closeStatement(statement);
        }
 if (connection != null){
 //最后关闭Connection对象
closeConnection(connection);
        }
    }
 }

4,后端实现查询用户数据

用户持久层新增查询接口

新建用户持久层文件UsersDao接口。

java 复制代码
/**
 * 查询所有数据
* @return
 */
 List<User> findByAll();

用户持久层实现查询接口

新建用户持久层接口实现类UsersDaoImpl接口。

java 复制代码
/**
 * 操作用户表持久层
*/
 public class UsersDaoImpl implements UsersDao { 
/**
 * 查询所有用户
* @return
 */
 @Override
 public List<User> findByAll() {
 Connection conn =null;
 Statement s = null;
 ResultSet rs = null;
 List<User> userList = new ArrayList<>
 ();
 try{
 conn = JdbcDruidUtil.getConnection();
 String sql = "select * from user";
 s = conn.createStatement();
 rs = s.executeQuery(sql);
 while(rs.next()){
 //手动orm映射
User u = new User();
 u.setId(rs.getInt("id"));
 u.setName(rs.getString("name"));
 u.setAge(rs.getInt("age"));
 userList.add(u);
            }
        }catch(Exception e){
 e.printStackTrace();
        }finally{
 JdbcDruidUtil.closeResource(s,conn);
        }
 return userList;
    }
 }

5,编写用户管理前段页面

html 复制代码
​
 <%@ page isELIgnored="false" 
contentType="text/html;charset=UTF-8" 
language="java" %>
 <html>
 <head>
 <title>用户管理</title>
 <style>
 div{
 padding:20px 10px 0 10px;
        }
 .total_content{
 display: flex; /* 创建 Flexbox 布局 
*/
对齐 */
 */
 justify-content: center; /* 水平居中
align-items: center; /* 垂直居中对齐 
        }
 </style>
 </head>
 <body>
 <div class="total_content">
 <h1 >用户管理系统</h1>
 </div>
 <div>
 <table align="center" width="60%" 
border="0" cellspacing="1" bgcolor="#000000">
 <tr bgcolor="#FFFFFF">
 <td>ID:</td>
 <td><input type="text" 
name="id" id="userId"/></td>
 <td>姓名:</td>
 <td><input type="text" 
name="name" id="name"/></td>
 <td>年龄:</td>
 <td><input type="number" 
name="age" id="age"/></td>
 </tr>
 <tr align="center" 
bgcolor="#FFFFFF">
 <td colspan="6">
 <input type="button" 
value="添加用户" onclick="addUser()" />
 <input type="button" 
value="更新用户" onclick="updateUser()"/>
 </td>
 </tr>
 </table> <hr/>
 <table align="center" width="60%" 
bgcolor="#000000" border="0" id="myTable" 
cellpadding="0" cellspacing="1">
 <thead>
 <tr align="center" 
bgcolor="#FFFFFF">
 <td>ID</td>
 <td>姓名</td>
 <td>年龄</td>
 <td>操作</td>
 </tr>
 </thead>
 <tbody id="tBody"></tbody>
 </table>
 </div>
 </body>
 </html>

​

6,编写用户查询Servlet

用户业务层新增查询接口

创建用户业务层接口类UsersService。

java 复制代码
public interface UsersService {
 /**
 * 查询所有数据
* @return
 */
 List<User> findByAll();
 }

用户业务层实现查询接口实现类

创建用户业务层接口实现类UsersServiceImpl。

java 复制代码
/**
 * 用户业务层
*
 */
 public class UsersServiceImpl implements 
UsersService {
 /**
 * 查询全部用户
* @return
 */
 @Override
 public List<User> findByAll() {
 UsersDao usersDao = new UsersDaoImpl();
 return usersDao.findByAll();
    }
 }

用户查询控制层编写

创建UserListServlet控制器类

java 复制代码
@WebServlet("/user.do")
 public class UserListServlet extends 
HttpServlet {
 @Override
 protected void doGet(HttpServletRequest 
req, HttpServletResponse resp) throws 
ServletException, IOException {
 this.doPost(req, resp);
    }
 @Override
 protected void doPost(HttpServletRequest 
req, HttpServletResponse resp) throws 
ServletException, IOException {
 String flag = req.getParameter("flag");
 switch (flag){
 case "getData":
 this.getData(req,resp);
 break;
        }
    }
 // 获取页面初始化数据
private void getData(HttpServletRequest 
req, HttpServletResponse resp) throws 
IOException {
 UsersService usersService = new 
UsersServiceImpl();
 List<User> userList = 
usersService.findByAll();
 ResultAjax success = 
ResultAjax.success(userList);
 writerTopage(resp,success);
    }
 /**
 * 输出至页面方法
* @param resp
 * @param data
 * @throws IOException
 */
 private void 
writerTopage(HttpServletResponse resp,Object 
data) throws IOException {
 String s = JSON.toJSONString(data);
 resp.setContentType("application/json");
 resp.setCharacterEncoding("UTF-8");
 PrintWriter pw = resp.getWriter();
 pw.print(s);
 pw.flush();
 pw.close();
    }
 }

7,前段实现显示用户数据

Jquery的Ajax使用

实战用户查询功能

引入jquery-3.6.0.js

javascript 复制代码
 <script type="text/javascript" src="js/jquery
3.6.0.js"></script>

初始化页面

javascript 复制代码
<script>
 $(function() {
 //初始化用户数据
getData();
    }); 
</script>

发送get请求获取数据

javascript 复制代码
<script>
 $(function() {
 //初始化用户数据
getData();
    }); 
// 获取页面初始化数据
function getData(){
 $.getJSON("user.do",
 {flag:"getData"},function (result) {
 listUser(result);
        });
    }
 </script> 

渲染数据

javascript 复制代码
<script>
 $(function() {
 //初始化用户数据
getData();
    }); 
// 获取页面初始化数据
function getData(){
 $.getJSON("user.do",
 {flag:"getData"},function (result) {
 listUser(result);
        });
    }
 // 遍历数据生成数据
function listUser(obj){
 var str ="";
 $.each(obj.data,function(){
 str+= "<tr align='center' 
bgcolor=\"#FFFFFF\">" +
 "<td id='"+this.id+"'>"+this.id 
+"</td>"+
 "<td>"+this.name+"</td>" +
 "<td>"+this.age+"</td>" +
 "<td><a href='#' >更新
</a>&nbsp;&nbsp;<a href='#'>删除 </a></td></tr>"
        });
 $("#tBody").prepend(str);
    }
 </script>  

8,后端实现添加用户数据

用户持久层添加用户接口

新建用户持久层文件UsersDao接口。

java 复制代码
/**
 * 添加用户信息
* @param user
 * @return
 */
 int save(User user);

用户持久层实现添加接口

新建用户持久层接口实现类UsersDaoImpl接口。

java 复制代码
/**
 * 操作用户表持久层
*/
 public class UsersDaoImpl implements UsersDao { 
/**
 * 添加用户
* @param user
 * @return
 */
 @Override
 public int save(User user) {
 Connection conn =null;
 PreparedStatement ps = null;
 ResultSet rs = null;
 Integer result = 0;
 try{
 conn = JdbcDruidUtil.getConnection();
 ps = conn.prepareStatement("insert into user (name,age) value (?,?)");
 ps.setString(1,user.getName());
 ps.setInt(2,user.getAge());
 result = ps.executeUpdate();
        }catch(Exception e){
 e.printStackTrace();
        }finally{
 JdbcDruidUtil.closeResource(rs,ps,conn);
        }
 return result;
    }
 }

用户业务层新增添加接口

创建用户业务层接口类UsersService。

java 复制代码
public interface UsersService {
 /**
 * 添加用户信息
* @param user
 * @return
 */
 int save(User user);
 }

用户业务层实现查询接口实现类

创建用户业务层接口实现类UsersServiceImpl。

java 复制代码
/**
 * 用户业务层
*
 */
 public class UsersServiceImpl implements 
UsersService {
 /**
 * 添加用户
* @param user
 * @return
 */
 @Override
 public int save(User user) {
 UsersDao usersDao = new UsersDaoImpl();
 return usersDao.save(user);
    }
 } 

用户查询控制层编写

创建UserListServlet控制器类

java 复制代码
@WebServlet("/user.do")
 public class UserListServlet extends 
HttpServlet {
 @Override
 protected void doGet(HttpServletRequest 
req, HttpServletResponse resp) throws 
ServletException, IOException {
 this.doPost(req, resp);
    }
 @Override
 protected void doPost(HttpServletRequest 
req, HttpServletResponse resp) throws 
ServletException, IOException {
 String flag = req.getParameter("flag");
 switch (flag){
 case "getData":
 this.getData(req,resp);
 break;
 case "addUser":
 this.addUser(req,resp);
 break;
        }
    }
 // 获取页面初始化数据
private void getData(HttpServletRequest 
req, HttpServletResponse resp) throws 
IOException {
 UsersService usersService = new 
UsersServiceImpl();
 List<User> userList = 
usersService.findByAll();
 ResultAjax success = 
ResultAjax.success(userList);
 writerTopage(resp,success);
    }
 /**
 * 处理添加用户请求
 * @param req
 * @param resp
 * @throws ServletException
 * @throws IOException
 */
 private void addUser(HttpServletRequest 
req, HttpServletResponse resp) throws 
IOException {
 User user = this.createUser(req);
 UsersService usersService = new 
UsersServiceImpl();
 int save = usersService.save(user);
 if (save > 0){
 writerTopage(resp,ResultAjax.success("添加成
功"));
        }else {
 writerTopage(resp,ResultAjax.error("添加成
功"));
        }
    }
 }

9,前段实现新增用户数据

创建添加用户事件

java 复制代码
// 用户添加
function addUser(){
 // 从页面中获取数据
var name = $("#name").val();
 var age = $("#age").val();
 if (name == ''){
 alert("请输入名字")
 return
        }
 if ( age == ''){
 alert("请输入年龄")
 return
        }
 var data = {
 name:name,
 age:age,
 flag : "addUser"
        }
 // 发送请求
$.post("user.do",data,function(result){
 console.log(result)
 if (result.code == 200){
 alert(result.message)
 location.reload()
            }
        });
    }

绑定事件

html 复制代码
<%@ page isELIgnored="false" 
contentType="text/html;charset=UTF-8" 
language="java" %>
 <html>
 <head>
 <title>用户管理</title>
 <style>
 div{
 padding:20px 10px 0 10px;
        }
        .total_content{
 display: flex; /* 创建 Flexbox 布局 
*/
对齐 */
 */
 justify-content: center; /* 水平居中
align-items: center; /* 垂直居中对齐 
        }
 </style>
 </head>
 <body>
 <div class="total_content">
 <h1 >用户管理系统</h1>
 </div>
 <div>
 <table align="center" width="60%" 
border="0" cellspacing="1" bgcolor="#000000">
 <tr bgcolor="#FFFFFF">
 <td>ID:</td>
 <td><input type="text" 
name="id" id="userId"/></td>
 <td>姓名:</td>
 <td><input type="text" 
name="name" id="name"/></td>
 <td>年龄:</td>
 <td><input type="number" 
name="age" id="age"/></td>
 </tr>
 <tr align="center" 
bgcolor="#FFFFFF">
 <td colspan="6">
 <input type="button" 
value="添加用户" onclick="addUser()" />
 <input type="button" 
value="更新用户" onclick="updateUser()"/>
 </td>
 </tr>
 </table> <hr/>
 <table align="center" width="60%" 
bgcolor="#000000" border="0" id="myTable" 
cellpadding="0" cellspacing="1">
 <thead>
 <tr align="center" 
bgcolor="#FFFFFF">
 <td>ID</td>
 <td>姓名</td>
 <td>年龄</td>
 <td>操作</td>
 </tr>
 </thead>
 <tbody id="tBody"></tbody>
 </table>
 </div>
 </body>

10,后端实现更新用户数据

用户持久层更新用户接口

新建用户持久层文件UsersDao接口。

java 复制代码
/**
 * 根据用户Id查询用户
* @param userid
 * @return
 */
 User findUsersById(int userid);
 /**
 * 根据用户id 更新用户信息
* @param user
 * @return
 */
 int updateByUser(User user);

用户持久层实现更新接口

新建用户持久层接口实现类UsersDaoImpl接口。

java 复制代码
/**
 * 操作用户表持久层
*/
 public class UsersDaoImpl implements UsersDao { 
/**
 * 根据用户id查询用户信息
* @param userid
 * @return
 */
 @Override
 public User findUsersById(int userid) {
 Connection conn =null;
 PreparedStatement ps = null;
 ResultSet rs = null;
 User user = null;
 try{
 conn = 
JdbcDruidUtil.getConnection();
 ps = conn.prepareStatement("select 
* from user where id = ?");
 ps.setInt(1,userid);
 rs = ps.executeQuery();
 while(rs.next()){
 //手动orm映射
user = new User();
 user.setId(rs.getInt("id"));
 user.setName(rs.getString("name"));
 user.setAge(rs.getInt("age"));
            }
        }catch(Exception e){
 e.printStackTrace();
        }finally{
 JdbcDruidUtil.closeResource(rs,ps,conn);
        }
 return user;
    }
 /**
 * 更新用户
* @param user
 * @return
 */
 @Override
 public int updateByUser(User user) {
 Connection conn =null;
 PreparedStatement ps = null;
 ResultSet rs = null;
 try{
 conn = 
JdbcDruidUtil.getConnection();
 ps = conn.prepareStatement("update 
user set age = ? , name = ?  where id = ?");
 ps.setInt(1,user.getAge());
 ps.setString(2,user.getName());
 ps.setInt(3,user.getId());
 return  ps.executeUpdate();
        }catch(Exception e){
 e.printStackTrace();
        }finally{
 JdbcDruidUtil.closeResource(rs,ps,conn);
        }
 return 0;
    }
 }

用户业务层新增添加接口

创建用户业务层接口类UsersService。

java 复制代码
 public interface UsersService {
 /**
 * 添加用户信息
* @param user
 * @return
 */
 int save(User user);
}

用户业务层实现查询接口实现类

创建用户业务层接口实现类UsersServiceImpl。

java 复制代码
/**
 * 用户业务层
*
 */
 public class UsersServiceImpl implements 
UsersService {
 /**
 * 添加用户
* @param user
 * @return
 */
 @Override
 public int save(User user) {
 UsersDao usersDao = new UsersDaoImpl();
 return usersDao.save(user);
    }
 } 

11,用户更新控制层Servelt编写

创建UserListServlet控制器类

java 复制代码
@WebServlet("/user.do")
 public class UserListServlet extends 
HttpServlet {
 @Override
 protected void doGet(HttpServletRequest 
req, HttpServletResponse resp) throws 
ServletException, IOException {
 this.doPost(req, resp);
    }
 @Override
 protected void doPost(HttpServletRequest 
req, HttpServletResponse resp) throws 
ServletException, IOException {
 String flag = req.getParameter("flag");
 switch (flag){
 case "updateUser":
 this.updateUser(req,resp);
 break
 case "findByUserId":
 this.getUserId(req,resp);
 break;      
        }
    }
 // 获取页面初始化数据
private void getData(HttpServletRequest 
req, HttpServletResponse resp) throws 
IOException {
 UsersService usersService = new 
UsersServiceImpl();
 List<User> userList = 
usersService.findByAll();
 ResultAjax success = 
ResultAjax.success(userList);
 writerTopage(resp,success);
    }
 // 获取页面初始化数据
 private void getUserId(HttpServletRequest 
req, HttpServletResponse resp) throws 
IOException {
 Integer id = 
Integer.valueOf(req.getParameter("id"));
 if (id == null){
 writerTopage(resp,ResultAjax.error("查询用户,用
户id为空"));
 return;
        }
 UsersService usersService = new 
UsersServiceImpl();
 User usersById = 
usersService.findUsersById(id);
 writerTopage(resp,ResultAjax.success(usersById
 ));
    }
 /**
 * 处理更新用户请求
* @param req
 * @param resp
 * @throws IOException
 */
 private void updateUser(HttpServletRequest req,
 HttpServletResponse resp) throws IOException{
 // 获取用户信息
User user = createUser(req);
UsersService usersService = new 
UsersServiceImpl();
 // 根据用户id更新用户
int i = 
usersService.updateByUser(user);
 if (i > 0){
    }
 }
 writerTopage(resp,ResultAjax.success("更新成功"));
        }else {
 writerTopage(resp,ResultAjax.error("更新失败"));
        }
}
}

12,前段实现更新用户数据

创建更新用户事件

javascript 复制代码
// 更新之前的数据选择
function preUpdateUser(userid){
 $.post("user.do",
 {id:userid,flag:"findByUserId"},function(result
 ){
 if (result.code == 200){
 console.log(result)
 $("#userId").val(result.data.id);
 $("#name").val(result.data.name);
 $("#age").val(result.data.age);
            }
        })
    }
 // 用户更新
function updateUser(){
 // 从页面中获取数据
var userId = $("#userId").val();
 var name = $("#name").val();
 var age = $("#age").val();
 var data = {
 id : userId,
 name:name,
 age:age,
 flag:"updateUser"
        }
 // 发送请求
$.post("user.do",data,function(result){
 console.log(result)
 if (result.code == 200){
 alert(result.message)
 location.reload()
            }
        });
    }

绑定事件

javascript 复制代码
// 遍历数据生成数据
function listUser(obj){
 var str ="";
 $.each(obj.data,function(){
 str+= "<tr align='center' 
bgcolor=\"#FFFFFF\">" +
 "<td id='"+this.id+"'>"+this.id 
+"</td>"+
 "<td>"+this.name+"</td>" +
 "<td>"+this.age+"</td>" +
 "<td><a href='#' 
onclick='preUpdateUser("+this.id+")'>更新
</a>&nbsp;&nbsp;<a href='#' >删除 </a></td>
 </tr>"
        });
 $("#tBody").prepend(str);
    }

13,后端实现删除用户数据

用户持久层删除用户接口

新建用户持久层文件UsersDao接口。

java 复制代码
/**
 * 根据用户id删除用户
* @param id 用户id
 * @return
 */
 int deleteById(Integer  id);

用户持久层实现删除接口

新建用户持久层接口实现类UsersDaoImpl接口。

java 复制代码
/**
 * 操作用户表持久层
*/
 public class UsersDaoImpl implements UsersDao { 
/**
 * 根据用户id删除用户
* @param id 用户id
 * @return
 */
 @Override
 public int deleteById(Integer id) {
 Connection conn =null;
 PreparedStatement ps = null;
 ResultSet rs = null;
 try{
 conn = 
JdbcDruidUtil.getConnection();
 ps = conn.prepareStatement("delete from  user where id = ?");
 ps.setInt(1,id);
 return  ps.executeUpdate();
        }catch(Exception e){
 e.printStackTrace();
        }finally{
 JdbcDruidUtil.closeResource(rs,ps,conn);
        }
 return 0;
    }
 }

用户业务层删除接口

创建用户业务层接口类UsersService。

java 复制代码
public interface UsersService {
 /**
 * 根据用户id删除用户
* @param id 用户id
 * @return
 */
 int deleteById(Integer  id);
 }

用户业务层实现删除接口实现类

创建用户业务层接口实现类UsersServiceImpl。

java 复制代码
/**
 * 用户业务层
*
 */
 public class UsersServiceImpl implements 
UsersService {
 /**
 * 根据用户id删除用户
* @param id
 * @return
 */
 @Override
 public int deleteById(Integer id) {
 UsersDao usersDao = new UsersDaoImpl();
 return usersDao.deleteById(id);
    }
 }  

用户删除控制层编写

创建UserListServlet控制器类

java 复制代码
@WebServlet("/user.do")
 public class UserListServlet extends 
HttpServlet {
 @Override
 protected void doGet(HttpServletRequest 
req, HttpServletResponse resp) throws 
ServletException, IOException {
 this.doPost(req, resp);
    }
 @Override
 protected void doPost(HttpServletRequest 
req, HttpServletResponse resp) throws 
ServletException, IOException {
 String flag = req.getParameter("flag");
 switch (flag){
 case "getData":
 this.getData(req,resp);
 break;
 case "addUser":
 this.addUser(req,resp);
 break;
 case "updateUser":
 this.updateUser(req,resp);
 break;
 case "delete":
 this.deleteUser(req,resp);
 break;
 case "findByUserId":
 this.getUserId(req,resp);
 break;
        }
    }
 // 获取页面初始化数据
private void getData(HttpServletRequest 
req, HttpServletResponse resp) throws 
IOException {
 UsersService usersService = new 
UsersServiceImpl();
 List<User> userList = 
usersService.findByAll();
 ResultAjax success = 
ResultAjax.success(userList);
 writerTopage(resp,success);
    }
 /**
 * 处理添加用户请求
* @param req
 * @param resp
 * @throws ServletException
 * @throws IOException
 */
 private void addUser(HttpServletRequest 
req, HttpServletResponse resp) throws 
IOException {
 User user = this.createUser(req);
 UsersService usersService = new 
UsersServiceImpl();
 int save = usersService.save(user);
 if (save > 0){
 writerTopage(resp,ResultAjax.success("添加成
功"));
        }else {
 writerTopage(resp,ResultAjax.error("添加成
功"));
        }
    }
 /**
 * 处理删除用户请求
* @param req
 * @param resp
 * @throws ServletException
 * @throws IOException
 */
 private void deleteUser(HttpServletRequest 
req,
 HttpServletResponse 
resp) throws ServletException, IOException {
 Integer id = 
Integer.valueOf(req.getParameter("id"));
 if (id == null) {
 writerTopage(resp, 
ResultAjax.error("id不能为空"));
        } 
else {
 UsersService usersService = new 
UsersServiceImpl();
 int i = 
usersService.deleteById(id);
 if (i > 0){
 writerTopage(resp, 
ResultAjax.success("删除成功"));
            }else
 {
 writerTopage(resp, 
ResultAjax.success("删除失败"));
            }
        }
    }
 }

14,前段页面删除用户数据

创建删除用户事件

java 复制代码
// 删除用户
function deleteUser(userid){
 $.post("user.do",
 {id:userid,flag:"delete"},function(result){
 if (result.code == 200){
 alert(result.message)
 location.reload()
            }
        })
    }

绑定删除事件

java 复制代码
 function listUser(obj){
        var str ="";
        $.each(obj.data,function(){
            str+= "<tr align='center' 
bgcolor=\"#FFFFFF\">" +
                "<td id='"+this.id+"'>"+this.id 
+"</td>"+
                "<td>"+this.name+"</td>" +
                "<td>"+this.age+"</td>" +
                "<td><a href='#' 
onclick='preUpdateUser("+this.id+")'>更新
</a>&nbsp;&nbsp;<a href='#' 
onclick='deleteUser("+this.id+")'>删除 </a></td>
 </tr>"
        });
        $("#tBody").prepend(str);
    }
相关推荐
用户52709648744907 小时前
Git 最佳实践
前端
4_0_47 小时前
全栈视角:从零构建一个现代化的 Todo 应用
前端·node.js
BumBle8 小时前
uniapp 用css实现圆形进度条组件
前端·vue.js·uni-app
杏花春雨江南8 小时前
npm error Could not resolve dependency:
前端·npm·node.js
嫂子的姐夫8 小时前
10-七麦js扣代码
前端·javascript·爬虫·python·node.js·网络爬虫
Komorebi_99998 小时前
Vue3 + TypeScript provide/inject 小白学习笔记
前端·javascript·vue.js
少吃一口都不行8 小时前
脚手架学习
前端·javascript·学习
地方地方8 小时前
手写JavaScript 深拷贝
前端·javascript
yeyuningzi8 小时前
npm升级提示error engine not compatible with your version of node/npm: npm@11.6.2
前端·npm·node.js