json data interaction implemented by servlet+ajax

Posted by elle_girl on Sun, 21 Jul 2019 09:46:22 +0200

Need plug-in Jquery, jar packages: json-lib-2.2.3-jdk15.jar and other jar packages are as follows:

 

1. Front desk js+html code

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Sign in</title>
    <!--Introduce js-->
    <script src="./jquery-3.3.1.js"></script>
<script type="text/javascript">
function login(){
    var uname = $("#uname").val();
    var pwd = $("#pwd").val();
    alert(uname);
$.ajax({
    type : "post",
    async : false,            //Asynchronous requests (synchronous requests will lock the browser, and other user actions must wait for the request to complete before they can be executed)
    url : "UserServlet",    //Request sent to UserServlet place
    data : {"uname":uname,"pwd":pwd},
    dataType : "json",        //The return data is in the form of json
    success : function(result) {
        //When the request succeeds, the function content is executed. result That is returned to the server json object
            for(var i=0;i<result.length;i++){
                alert(result[i].id+result[i].uname+result[i].nickname+result[i].pwd);
                //Later data will be added html
                addLabel(result[i].id,result[i].uname,result[i].nickname,result[i].pwd)
            }
            //Hidden Loading Animation Sketch
    },
    error : function(errorMsg) {
        //Execute this function when the request fails
        alert("Failed to request data!");
        myChart.hideLoading();
    }
});
}
//Functions for adding elements
function addLabel(id,uname,nickname,pwd){
    $("thead").append("<tr>")
    $("thead").append("<td>"+id+"</td>");
    $("thead").append("<td>"+uname+"</td>");
    $("thead").append("<td>"+nickname+"</td>");
    $("thead").append("<td>"+pwd+"</td></tr>");
}
</script>
<style type="text/css">
*{
margin:0 auto;
padding:0;
}
#container{
width:600px;
height:500px;
border:1px solid red;
border-radius:10%;
}
/**Set in-line elements to block elements and control them separately**/
#cover_uname{
margin-top:200px;
width:300px;
height:50px;
display:block;
}
#cover_pwd{
width:300px;
height:50px;
display:block;
}
#cover_login{
width:60px;
height:50px;
display:block;
}
</style>
</head>
<body>
<div id="container">
<span id="cover_uname">account:<input type="text" id="uname"/></span>
<span id="cover_pwd">Password:<input type="text" id="pwd"/></span>
<span id="cover_login"><button onclick="login()">Sign in</button></span>
</div>
<div id="content">
<table border="1" style="border-collapse:collapse;border:1px solid red;">
<thead><tr><td colspan="4" align="center">information</td></tr></thead>
</table>
</div>
</body>
</html>

2. Serlet code:

package gc.servlet;

import gc.dao.UserDao;
import gc.json.ToJson;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author macbook
 * @see User login control/add, delete and change check control
 */
public class UserServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    public UserServlet() {
        super();
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json; charset=utf-8");
        response.setHeader("cache-control", "no-cache");
        PrintWriter out = response.getWriter();
        ToJson json = new ToJson();
        UserDao dao = new UserDao();
        //Judge according to the state
        String uname =  request.getParameter("uname");
        String pwd = request.getParameter("pwd");
        System.out.println(uname+pwd);
        //login Sign in
            String loginStatus = dao.login(uname, uname);
              if(loginStatus.equals("fail")){
                  //Transfer to Logon Failure Page
                  response.sendError(404);
              }else {
                //Describes getting nicknames, returning nicknames and user information
                  out.print(json.getAUserJson(uname));
                  System.out.println(json.getAUserJson(uname));
            }
        //reg register
        //del delete
        //update modify
        //select query
        out.flush();
        out.close();
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

}

3. Classes of other team database operations and classes transformed into json data:

Classes of database information:

package gc.util;

public class MySqlDBInfor {
    public static String  driverName = "com.mysql.jdbc.Driver";
    public static String url = "jdbc:mysql://127.0.0.1:3306/gc?useUnicode=true&characterEncoding=UTF-8";
    public static String user = "root";
    public static String pwd = "123456";
}

 

Classes connecting to databases:

package gc.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class ConnectDB {
    static Connection connection = null;//1.
    //Database Connection
    public static Connection getConnectDB(){
        try {
            Class.forName(MySqlDBInfor.driverName);//2.
            connection = DriverManager.getConnection(MySqlDBInfor.url,MySqlDBInfor.user,MySqlDBInfor.pwd);//3.
            return connection;
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return connection;
    }
    //Database Connection Closed
    public static void closeDB(){
        try {
            getConnectDB().close();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    /**
     * @see Used to insert data into a database
     * @param sql
     * @return
     */
    public static int updateData(String sql){
        try {
            Statement statement = getConnectDB().createStatement();
            int a = statement.executeUpdate(sql);
            if(a>0)return 1;
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return 0;
    }
    /**
     * @see Query data
     * @param sql
     * @return
     */
    public static ResultSet queryData(String sql){
        Statement statement;
        try {
            statement = getConnectDB().createStatement();
            ResultSet set = statement.executeQuery(sql);
            return set;
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();//Return directly if an exception occurs null
            return null;
        }
    }
    
    public static boolean insertData(String sql){
        try {
            Statement statement = getConnectDB().createStatement();
            if(statement.executeUpdate(sql)>0)return true;
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return false;
        
    }
    
    public static void main(String[] args) throws SQLException {
        String sql = "select *from user;"; 
        ResultSet set = ConnectDB.queryData(sql);
        while (set.next()) {
            System.out.println(set.getString("uname"));
        }
    }
}

Operational class:

package gc.dao;

import gc.table.User;
import gc.util.ConnectDB;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class UserDao {
    Connection connection = ConnectDB.getConnectDB();
    User user;
    //Inquiry Account
    public List<User> selectUser(String sql){
        PreparedStatement statement;
        List<User> list = new ArrayList<User>();
        ResultSet set;
        try {
            statement = connection.prepareStatement(sql);
            set = statement.executeQuery();
            while (set.next()) {
                user = new User();
                user.setId(set.getString("id"));
                user.setUname(set.getString("uname"));
                user.setPwd(set.getString("pwd"));
                user.setNickname(set.getString("nickname"));
                list.add(user);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return list;
    }
    //Insert account
    //Delete accounts
    //Modification of accounts
    //These are the basic operations, and the following are servlet Some exceptional operations during invocation
    //Log in, fight for password account, account is correct, password is incorrect. [Because no verification code is set, it must be both correct, to avoid collision with the library]
    public String login(String uname,String pwd){
        String sql = "select *from user;";
        List<User> users = selectUser(sql);
        for (int i = 0; i < users.size();) {
            User user = users.get(i);
            if (user.getUname().equals(uname)&&user.getPwd().equals(pwd)) {
                return user.getNickname();
            }else {
                return "fail";
            }
        }
        return "fail";
    }
    //test
    public static void main(String[] args) {
        UserDao dao = new UserDao();
        String sql = "select *from user;";
        List<User> list = dao.selectUser(sql);
        for (int i = 0; i < list.size(); i++) {
            User user = list.get(i);
            System.out.println(user.getUname());
        }
        //test json The data of transformation is already in use. ToJson Call when testing in class
    }
}

Convert data into json classes:

package gc.json;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;





import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import gc.dao.UserDao;
import gc.table.User;
import gc.util.ConnectDB;

//Convert the query results of all tables into json Classes of data
public class ToJson {
    //Firstly, the values of some fields in the table are counted, and then handed over to this class.
    public void json(String countType,int countNum){
        
    }
    public void json(){
        
    }
    /**
     * This class is used for testing json data directly to html
     */
    public List<FakeForms> getJsonTest(){
        //1,Obtain database data and make statistics
        //2,Data processing json conversion
        //3,Implement baseband type statistics and then digitalize it
        //4,x Represents the card type. y Representation statistics
        String sql = "select count(if(basebandBoard='BPN2',basebandBoard,null)) BPN2,count(if(basebandBoard='CCE1',basebandBoard,null)) CCE1,count(if(basebandBoard='BPP1',basebandBoard,null)) BPP1,count(if(basebandBoard='FA4',basebandBoard,null)) FA4,count(if(basebandBoard='FA4A',basebandBoard,null)) FA4A,count(if(basebandBoard='FA6',basebandBoard,null)) FA6,count(if(basebandBoard='PM10',basebandBoard,null)) PM10,count(if(basebandBoard='PM10B',basebandBoard,null)) PM10B,count(if(basebandBoard='SA0',basebandBoard,null)) SA0 from four;";
        Connection connection = ConnectDB.getConnectDB();
        List<FakeForms> fours = new ArrayList<>();
        try {
            PreparedStatement statement = connection.prepareStatement(sql);
            ResultSet set = statement.executeQuery();
            while (set.next()) {
                FakeForms fakeForms = new FakeForms();
                fakeForms.setBPN2(set.getString("BPN2"));
                fakeForms.setBPP1(set.getString("BPP1"));
                fakeForms.setCCE1(set.getString("CCE1"));
                fakeForms.setFA4(set.getString("FA4"));
                fakeForms.setFA4A(set.getString("FA4A"));
                fakeForms.setFA6(set.getString("FA6"));
                fakeForms.setPM10(set.getString("PM10"));
                fakeForms.setPM10B("PM10B");
                fakeForms.setSA0(set.getString("SA0"));
                fours.add(fakeForms);
            }
            
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
        return fours;
        
    }
    
    //Getting Users json data
    public JSONArray getUserJson(){
        UserDao dao2  = new UserDao();
        String sql = "select *from user;";
        List<User> list = dao2.selectUser(sql);
        JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < list.size(); i++) {
            User user = list.get(i);
            //data json turn
            JSONObject jsonObject = JSONObject.fromObject(user);
            jsonArray.add(jsonObject);
        }
        //test
        //System.out.println(jsonArray);
        return jsonArray;
    }
    //Getting a single user json data
    public JSONArray getAUserJson(String uname){
        UserDao dao2  = new UserDao();
        String sql = "select *from user where uname='"+uname+"';";
        List<User> list = dao2.selectUser(sql);
        JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < list.size(); i++) {
            User user = list.get(i);
            //data json turn
            JSONObject jsonObject = JSONObject.fromObject(user);
            jsonArray.add(jsonObject);
        }
        //test
        //System.out.println(jsonArray);
        return jsonArray;
    }
    //test
    public static void main(String[] args) {
        ToJson dao = new ToJson();
        JSONArray array = new JSONArray();
        List<FakeForms> fours = dao.getJsonTest();
        for (int i = 0; i < fours.size(); i++) {
            FakeForms four = fours.get(i);
            //json turn
            JSONObject jsonObject = JSONObject.fromObject(four);
            array.add(jsonObject);
            System.out.println(four.getBPN2());
            System.out.println(array.toString());
        }
        //The following is the result of the query. json Format
        //Here's the right one User Data json turn
        System.out.println(dao.getUserJson());
        System.out.println(dao.getAUserJson("cisco"));
    }
}

Mapping table:

package gc.table;

/** Account sheet for login system**/
public class User {
    private String id;
    private String uname;
    private String pwd;
    private String nickname;//Nickname?
    /**
     * @return the id
     */
    public String getId() {
        return id;
    }
    /**
     * @param id the id to set
     */
    public void setId(String id) {
        this.id = id;
    }
    /**
     * @return the uname
     */
    public String getUname() {
        return uname;
    }
    /**
     * @param uname the uname to set
     */
    public void setUname(String uname) {
        this.uname = uname;
    }
    /**
     * @return the pwd
     */
    public String getPwd() {
        return pwd;
    }
    /**
     * @param pwd the pwd to set
     */
    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
    /**
     * @return the nickname
     */
    public String getNickname() {
        return nickname;
    }
    /**
     * @param nickname the nickname to set
     */
    public void setNickname(String nickname) {
        this.nickname = nickname;
    }
}

 

This article is mainly used to record JSON data conversion. Most of the functions mentioned in the annotations are not implemented. Here, we mainly record the process of JSON data conversion and interaction before and after implementation.

Basic ideas:

The foreground sends json data to the servlet and requests the servlet to give json data. Regardless of the background processing process, it is such an interactive, two-way interactive process. What about the details?

First, html sends a JSON data request and requests JSON data. At this time, the servlet receives the data, and then handles it to the Dao class / ToJson class for processing. ToJson, on the other hand, calls the Dao class to achieve code reuse while quickly converting data to json. Ordinary data requests, such as additions, deletions and alterations, can be done with dao, and those involving JSON are handled by Tojson. When the data arrives at dao, Dao calls the database connection object for operation.

According to the data flow direction, I gave him the data hierarchy of personal understanding:

html/js.ajax request layer

Serlet Data Receiving Layer/Sending

dao/ToJson/table mapping class Data processing/transformation layer

ConnectionDB Data Persistence Layer

Topics: Python JSON SQL Java Database