• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

form表单和ajax提供的JSON格式保存数据的区别更为标准的前后端分离格式

武飞扬头像
weixin_52904103
帮助1

学新通

1.利用form表单

/bbq-v1/index2.html

  1.  
    <!DOCTYPE html>
  2.  
    <html lang="en">
  3.  
    <head>
  4.  
    <meta charset="UTF-8">
  5.  
    <title>表白墙</title>
  6.  
    </head>
  7.  
    <body>
  8.  
    <div>
  9.  
    <form method="post" action="/hello/bbq-v1/save">
  10.  
    <label for="who"></label>
  11.  
    <input type="text" id="who" name="who">
  12.  
    <label for="target">对谁</label>
  13.  
    <input type="text" id="target" name="target">
  14.  
    <label for="what">说什么</label>
  15.  
    <input type="text" id="what" name="what">
  16.  
    <button>保存</button>
  17.  
    </form>
  18.  
     
  19.  
    </div>
  20.  
     
  21.  
    <table border="1">
  22.  
    <thead>
  23.  
    <tr>
  24.  
    <th></th>
  25.  
    <th>对谁</th>
  26.  
    <th>说什么</th>
  27.  
    </tr>
  28.  
    </thead>
  29.  
    <tbody></tbody>
  30.  
    </table>
  31.  
     
  32.  
    <!-- script.js 的目标:通过ajax 去后端,查询所有的消息,并展示到tbody中 -->
  33.  
    <script>
  34.  
    var tbody = document.querySelector("tbody")
  35.  
    var xhr = new XMLHttpRequest();
  36.  
    xhr.open("get", "/hello/bbq-v1/message-list.json");
  37.  
    xhr.onload = function () {
  38.  
    var messageList = JSON.parse(xhr.responseText);
  39.  
    for (var i in messageList) {
  40.  
    var msg = messageList[i];
  41.  
     
  42.  
    var html = `<tr><td>${msg.who}</td><td>${msg.target}</td><td>${msg.what}</td></tr>`;
  43.  
     
  44.  
    tbody.innerHTML = html;
  45.  
    }
  46.  
    }
  47.  
    xhr.send();
  48.  
     
  49.  
    </script>
  50.  
    </body>
  51.  
    </html>
学新通

 链接数据库(/bbqv1/DBUtil)(因为会被用到多次,所以单独拿出来,节约数据库被调用的次数)

  1.  
    package com.MXC.servlet.bbqv1;
  2.  
     
  3.  
    import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
  4.  
     
  5.  
    import javax.sql.DataSource;
  6.  
    import java.sql.Connection;
  7.  
    import java.sql.SQLException;
  8.  
     
  9.  
    public class DBUtil {
  10.  
    public final static DataSource dataSource;
  11.  
     
  12.  
    static {
  13.  
    MysqlDataSource db = new MysqlDataSource();
  14.  
    db.setServerName("127.0.0.1");
  15.  
    db.setPort(3306);
  16.  
    db.setUser("root");
  17.  
    db.setPassword("123456");
  18.  
    db.setDatabaseName("db_12_29");
  19.  
    db.setCharacterEncoding("utf8");
  20.  
    db.setUseSSL(false);
  21.  
    db.setServerTimezone("Asia/Shanghai");
  22.  
     
  23.  
    dataSource = db;
  24.  
    }
  25.  
     
  26.  
    public static Connection connection() throws SQLException {
  27.  
    return dataSource.getConnection();
  28.  
    }
  29.  
    }
学新通

数据库内容(/bbqv1/Message)

  1.  
    package com.MXC.servlet.bbqv1;
  2.  
     
  3.  
    public class Message {
  4.  
    public String who;
  5.  
    public String target;
  6.  
    public String what;
  7.  
     
  8.  
     
  9.  
     
  10.  
    }

前端设置(/bbqv1/MessageListServlet)

  1.  
    package com.MXC.servlet.bbqv1;
  2.  
     
  3.  
    import com.fasterxml.jackson.core.JsonProcessingException;
  4.  
    import com.fasterxml.jackson.databind.ObjectMapper;
  5.  
     
  6.  
    import javax.servlet.ServletException;
  7.  
    import javax.servlet.annotation.WebServlet;
  8.  
    import javax.servlet.http.HttpServlet;
  9.  
    import javax.servlet.http.HttpServletRequest;
  10.  
    import javax.servlet.http.HttpServletResponse;
  11.  
    import java.io.IOException;
  12.  
    import java.sql.Connection;
  13.  
    import java.sql.PreparedStatement;
  14.  
    import java.sql.ResultSet;
  15.  
    import java.sql.SQLException;
  16.  
    import java.util.ArrayList;
  17.  
    import java.util.List;
  18.  
     
  19.  
    @WebServlet("/bbq-v1/message-list.json")
  20.  
    public class MessageListServlet extends HttpServlet {
  21.  
    @Override
  22.  
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  23.  
    //1.从数据库中查询所有的消息
  24.  
    List<Message> messageList = queryFromDB();
  25.  
    //2.把消息序列化JSON格式
  26.  
    String jsonText = toJson(messageList);
  27.  
    //3.填充响应对象
  28.  
    resp.setCharacterEncoding("utf-8");
  29.  
    resp.setContentType("application/json");
  30.  
    resp.getWriter().println(jsonText);
  31.  
    }
  32.  
     
  33.  
     
  34.  
    // Servlet 对象在Tomcat 内部是单例的
  35.  
    // 所以 Servlet 对象的属性 om 也只有一份
  36.  
    private final ObjectMapper om = new ObjectMapper();
  37.  
     
  38.  
    private String toJson(List<Message> messageList){
  39.  
    try {
  40.  
    return om.writeValueAsString(messageList);
  41.  
    } catch (JsonProcessingException exc) {
  42.  
    throw new RuntimeException(exc);
  43.  
    }
  44.  
     
  45.  
    }
  46.  
     
  47.  
    private List<Message> queryFromDB() {
  48.  
    List<Message> messageList = new ArrayList<>();
  49.  
    try (Connection c = DBUtil.connection()) {
  50.  
    String sql = "SELECT who, target, what FROM messages ORDER BY id DESC";
  51.  
    try (PreparedStatement ps = c.prepareStatement(sql)) {
  52.  
    try (ResultSet rs = ps.executeQuery()) {
  53.  
    while (rs.next()) {
  54.  
    Message msg = new Message();
  55.  
    msg.who = rs.getString("who");
  56.  
    msg.target = rs.getString("target");
  57.  
    msg.what = rs.getString("what");
  58.  
     
  59.  
    messageList.add(msg);
  60.  
     
  61.  
    }
  62.  
    }
  63.  
    }
  64.  
    } catch (SQLException exc) {
  65.  
    throw new RuntimeException(exc);
  66.  
    }
  67.  
    return messageList;
  68.  
    }
  69.  
    }
学新通

 后端设置(/bbqv1/SaveServlet)

  1.  
    package com.MXC.servlet.bbqv1;
  2.  
     
  3.  
     
  4.  
    import javax.servlet.ServletException;
  5.  
    import javax.servlet.annotation.WebServlet;
  6.  
    import javax.servlet.http.HttpServlet;
  7.  
    import javax.servlet.http.HttpServletRequest;
  8.  
    import javax.servlet.http.HttpServletResponse;
  9.  
    import java.io.IOException;
  10.  
    import java.sql.Connection;
  11.  
    import java.sql.PreparedStatement;
  12.  
    import java.sql.SQLException;
  13.  
     
  14.  
    @WebServlet("/bbq-v1/save")
  15.  
    public class SaveServlet extends HttpServlet {
  16.  
    @Override
  17.  
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  18.  
    //1.从响应中读取数据
  19.  
    req.setCharacterEncoding("utf-8");
  20.  
    String who = req.getParameter("who");
  21.  
    String target = req.getParameter("target");
  22.  
    String what = req.getParameter("what");
  23.  
     
  24.  
    //2.保存到数据库当中
  25.  
    saveToDB(who, target, what);
  26.  
     
  27.  
    //3.重定向回展示页面
  28.  
    resp.sendRedirect("/hello/bbq-v1/index2.html");
  29.  
    }
  30.  
     
  31.  
    private void saveToDB(String who, String target, String what) {
  32.  
    try(Connection c = DBUtil.connection()) {
  33.  
    String sql = "INSERT INTO messages (who, target, what) VALUES (?, ?, ?)";
  34.  
    try (PreparedStatement ps = c.prepareStatement(sql)){
  35.  
    ps.setString(1,who);
  36.  
    ps.setString(2,target);
  37.  
    ps.setString(3,what);
  38.  
     
  39.  
    ps.executeUpdate();
  40.  
    }
  41.  
     
  42.  
    }catch (SQLException exc) {
  43.  
    throw new RuntimeException(exc);
  44.  
    }
  45.  
     
  46.  
    }
  47.  
    }
学新通

2.利用ajax提供JSON格式保存数据(更为标准的前后分离方案)(相对性能更好)

/bbq-v2/index2.html

  1.  
    <!DOCTYPE html>
  2.  
    <html lang="en">
  3.  
    <head>
  4.  
    <meta charset="UTF-8">
  5.  
    <title>表白墙</title>
  6.  
    </head>
  7.  
    <body>
  8.  
    <div>
  9.  
    <label for="who"></label>
  10.  
    <input type="text" id="who" name="who">
  11.  
    <label for="target">对谁</label>
  12.  
    <input type="text" id="target" name="target">
  13.  
    <label for="what">说什么</label>
  14.  
    <input type="text" id="what" name="what">
  15.  
    <button>保存</button>
  16.  
    </div>
  17.  
     
  18.  
    <table border="1">
  19.  
    <thead>
  20.  
    <tr>
  21.  
    <th></th>
  22.  
    <th>对谁</th>
  23.  
    <th>说什么</th>
  24.  
    </tr>
  25.  
    </thead>
  26.  
    <tbody></tbody>
  27.  
    </table>
  28.  
     
  29.  
    <!-- script.js 的目标:通过ajax 去后端,查询所有的消息,并展示到tbody中 -->
  30.  
    <script>
  31.  
    var tbody = document.querySelector("tbody")
  32.  
    var xhr = new XMLHttpRequest();
  33.  
    xhr.open("get", "/hello/bbq-v2/message-list.json");
  34.  
    xhr.onload = function () {
  35.  
    var messageList = JSON.parse(xhr.responseText);
  36.  
    for (var i in messageList) {
  37.  
    var msg = messageList[i];
  38.  
     
  39.  
    var html = `<tr><td>${msg.who}</td><td>${msg.target}</td><td>${msg.what}</td></tr>`;
  40.  
     
  41.  
    tbody.innerHTML = html;
  42.  
    }
  43.  
    }
  44.  
    xhr.send();
  45.  
     
  46.  
    //通过ajax提交JSON数据到后端进行保存,不在使用form表单的形式
  47.  
    var whoInput = document.querySelector("#who");
  48.  
    var targetInput = document.querySelector("#target");
  49.  
    var whatInput = document.querySelector("#what");
  50.  
    document.querySelector("button").onclick = function() {
  51.  
    //1. 从input 中读取用户的数据
  52.  
    var msg = {
  53.  
    who: whoInput.value,
  54.  
    target: targetInput.value,
  55.  
    what: whatInput.value
  56.  
    };
  57.  
     
  58.  
    whoInput.value = targetInput.value = whatInput.value = '';
  59.  
     
  60.  
    //2.通过ajax发送数据到后端进行保存
  61.  
    var jsonText = JSON.stringify(msg);
  62.  
     
  63.  
    var xhr = new XMLHttpRequest();
  64.  
    xhr.open("post", "/hello/bbq-v2/save.json");
  65.  
    xhr.setRequestHeader("Content-Type", "application/json")
  66.  
    xhr.onload = function () {
  67.  
    var result = JSON.parse(xhr.responseText);
  68.  
    if (result.success === true) {
  69.  
    //保存成功,我们在前端,自己更新页面
  70.  
    var html = `<tr><td>${msg.who}</td><td>${msg.target}</td><td>${msg.what}</td></tr>`;
  71.  
    tbody.innerHTML = html tbody.innerHTML;
  72.  
    }
  73.  
     
  74.  
    };
  75.  
    xhr.send(jsonText);
  76.  
    };
  77.  
     
  78.  
     
  79.  
    </script>
  80.  
    </body>
  81.  
    </html>
学新通

 链接数据库(/bbqv2/DBUtil)(因为会被用到多次,所以单独拿出来,节约数据库被调用的次数)

  1.  
    package com.MXC.servlet.bbqv2;
  2.  
     
  3.  
    import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
  4.  
     
  5.  
    import javax.sql.DataSource;
  6.  
    import java.sql.Connection;
  7.  
    import java.sql.SQLException;
  8.  
     
  9.  
    public class DBUtil {
  10.  
    public final static DataSource dataSource;
  11.  
     
  12.  
    static {
  13.  
    MysqlDataSource db = new MysqlDataSource();
  14.  
    db.setServerName("127.0.0.1");
  15.  
    db.setPort(3306);
  16.  
    db.setUser("root");
  17.  
    db.setPassword("123456");
  18.  
    db.setDatabaseName("db_12_29");
  19.  
    db.setCharacterEncoding("utf8");
  20.  
    db.setUseSSL(false);
  21.  
    db.setServerTimezone("Asia/Shanghai");
  22.  
     
  23.  
    dataSource = db;
  24.  
    }
  25.  
     
  26.  
    public static Connection connection() throws SQLException {
  27.  
    return dataSource.getConnection();
  28.  
    }
  29.  
    }
学新通

数据库内容(/bbqv2/Message)

  1.  
    package com.MXC.servlet.bbqv2;
  2.  
     
  3.  
    public class Message {
  4.  
    public String who;
  5.  
    public String target;
  6.  
    public String what;
  7.  
     
  8.  
     
  9.  
     
  10.  
    }
  11.  
     

前端设置(/bbqv2/MessageListServlet)

  1.  
    package com.MXC.servlet.bbqv2;
  2.  
     
  3.  
    import com.fasterxml.jackson.core.JsonProcessingException;
  4.  
    import com.fasterxml.jackson.databind.ObjectMapper;
  5.  
     
  6.  
    import javax.servlet.ServletException;
  7.  
    import javax.servlet.annotation.WebServlet;
  8.  
    import javax.servlet.http.HttpServlet;
  9.  
    import javax.servlet.http.HttpServletRequest;
  10.  
    import javax.servlet.http.HttpServletResponse;
  11.  
    import java.io.IOException;
  12.  
    import java.sql.Connection;
  13.  
    import java.sql.PreparedStatement;
  14.  
    import java.sql.ResultSet;
  15.  
    import java.sql.SQLException;
  16.  
    import java.util.ArrayList;
  17.  
    import java.util.List;
  18.  
     
  19.  
    @WebServlet("/bbq-v2/message-list.json")
  20.  
    public class MessageListServlet extends HttpServlet {
  21.  
    @Override
  22.  
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  23.  
    //1.从数据库中查询所有的消息
  24.  
    List<Message> messageList = queryFromDB();
  25.  
    //2.把消息序列化JSON格式
  26.  
    String jsonText = toJson(messageList);
  27.  
    //3.填充响应对象
  28.  
    resp.setCharacterEncoding("utf-8");
  29.  
    resp.setContentType("application/json");
  30.  
    resp.getWriter().println(jsonText);
  31.  
    }
  32.  
     
  33.  
     
  34.  
    // Servlet 对象在Tomcat 内部是单例的
  35.  
    // 所以 Servlet 对象的属性 om 也只有一份
  36.  
    private final ObjectMapper om = new ObjectMapper();
  37.  
     
  38.  
    private String toJson(List<Message> messageList){
  39.  
    try {
  40.  
    return om.writeValueAsString(messageList);
  41.  
    } catch (JsonProcessingException exc) {
  42.  
    throw new RuntimeException(exc);
  43.  
    }
  44.  
     
  45.  
    }
  46.  
     
  47.  
    private List<Message> queryFromDB() {
  48.  
    List<Message> messageList = new ArrayList<>();
  49.  
    try (Connection c = DBUtil.connection()) {
  50.  
    String sql = "SELECT who, target, what FROM messages ORDER BY id DESC";
  51.  
    try (PreparedStatement ps = c.prepareStatement(sql)) {
  52.  
    try (ResultSet rs = ps.executeQuery()) {
  53.  
    while (rs.next()) {
  54.  
    Message msg = new Message();
  55.  
    msg.who = rs.getString("who");
  56.  
    msg.target = rs.getString("target");
  57.  
    msg.what = rs.getString("what");
  58.  
     
  59.  
    messageList.add(msg);
  60.  
     
  61.  
    }
  62.  
    }
  63.  
    }
  64.  
    } catch (SQLException exc) {
  65.  
    throw new RuntimeException(exc);
  66.  
    }
  67.  
    return messageList;
  68.  
    }
  69.  
    }
  70.  
     
学新通

后端设置(/bbqv2/SaveServlet)

  1.  
    package com.MXC.servlet.bbqv2;
  2.  
     
  3.  
     
  4.  
    import com.MXC.servlet.bbqv1.DBUtil;
  5.  
    import com.fasterxml.jackson.databind.ObjectMapper;
  6.  
     
  7.  
    import javax.servlet.ServletException;
  8.  
    import javax.servlet.annotation.WebServlet;
  9.  
    import javax.servlet.http.HttpServlet;
  10.  
    import javax.servlet.http.HttpServletRequest;
  11.  
    import javax.servlet.http.HttpServletResponse;
  12.  
    import java.io.IOException;
  13.  
    import java.sql.Connection;
  14.  
    import java.sql.PreparedStatement;
  15.  
    import java.sql.SQLException;
  16.  
    import java.util.HashMap;
  17.  
    import java.util.Map;
  18.  
     
  19.  
    @WebServlet("/bbq-v2/save.json")
  20.  
    public class SaveServlet extends HttpServlet {
  21.  
    private final ObjectMapper om = new ObjectMapper();
  22.  
     
  23.  
    @Override
  24.  
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  25.  
    // 读取并解析请求体中的JSON格式的消息
  26.  
    Message message = om.readValue(req.getInputStream(), Message.class);
  27.  
     
  28.  
    //保存打数据库中
  29.  
    saveToDB(message);
  30.  
     
  31.  
    // 告诉前端返回成功了,通过返回一个固定的JSON数据
  32.  
    //{success: true}
  33.  
    Map<String, Object> result = new HashMap<>();
  34.  
    result.put("success",true);
  35.  
    String jsonText = om.writeValueAsString(result);
  36.  
     
  37.  
    //发送JSON数据
  38.  
    resp.setCharacterEncoding("utf-8");
  39.  
    resp.setContentType("application/json");
  40.  
    resp.getWriter().println(jsonText);
  41.  
    }
  42.  
     
  43.  
    private void saveToDB(Message message) {
  44.  
    try(Connection c = DBUtil.connection()) {
  45.  
    String sql = "INSERT INTO messages (who, target, what) VALUES (?, ?, ?)";
  46.  
    try (PreparedStatement ps = c.prepareStatement(sql)){
  47.  
    ps.setString(1,message.who);
  48.  
    ps.setString(2,message.target);
  49.  
    ps.setString(3,message.what);
  50.  
     
  51.  
    ps.executeUpdate();
  52.  
    }
  53.  
     
  54.  
    }catch (SQLException exc) {
  55.  
    throw new RuntimeException(exc);
  56.  
    }
  57.  
    }
  58.  
     
  59.  
     
  60.  
    }
学新通

3.两者之间的区别

学新通

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgkicaj
系列文章
更多 icon
同类精品
更多 icon
继续加载