servlet+ajax实现json数据交互

需要插件 Jquery、jar包:json-lib-2.2.3-jdk15.jar及其他jar包如下:

完成结果:【这种写法只能用数据库中id=1的第一条数据登录,是什么原因呢?还在实验中】

                                                         

 

 具体代码:

 

1、前台js+html代码

<%@ 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>登录</title>
    <!--引入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,            //异步请求(同步请求将会锁住浏览器,用户其他操作必须等待请求完成才可以执行)
    url : "UserServlet",    //请求发送到UserServlet处
    data : {"uname":uname,"pwd":pwd},
    dataType : "json",        //返回数据形式为json
    success : function(result) {
        //请求成功时执行该函数内容,result即为服务器返回的json对象
            for(var i=0;i<result.length;i++){
                alert(result[i].id+result[i].uname+result[i].nickname+result[i].pwd);
                //后期将获得的数据加入html
                addLabel(result[i].id,result[i].uname,result[i].nickname,result[i].pwd)
            }
            //隐藏加载动画略
    },
    error : function(errorMsg) {
        //请求失败时执行该函数
        alert("请求数据失败!");
        myChart.hideLoading();
    }
});
}
//实现添加元素的函数
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%;
}
/**将行内元素设置为块元素,并分行控制**/
#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">账户:<input type="text" id="uname"/></span>
<span id="cover_pwd">密码:<input type="text" id="pwd"/></span>
<span id="cover_login"><button onclick="login()">登录</button></span>
</div>
<div id="content">
<table border="1" style="border-collapse:collapse;border:1px solid red;">
<thead><tr><td colspan="4" align="center">信息</td></tr></thead>
</table>
</div>
</body>
</html>

2、servlet代码:

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 用户登录控制/增删改查控制
 */
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();
        //根据状态,进行判断
        String uname =  request.getParameter("uname");
        String pwd = request.getParameter("pwd");
        System.out.println(uname+pwd);
        //login登录
            String loginStatus = dao.login(uname, uname);
              if(loginStatus.equals("fail")){
                  //调转到登录失败页面
                  response.sendError(404);
              }else {
                //说明获取到昵称,返回昵称和用户信息
                  out.print(json.getAUserJson(uname));
                  System.out.println(json.getAUserJson(uname));
            }
        //reg注册
        //del删除
        //update修改
        //select查询
        out.flush();
        out.close();
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

}

3、其他队数据库操作的类和转化为json数据的类:

数据库信息的类:

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";
}

 

连接数据库的类:

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.
    //数据库连接
    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;
    }
    //数据库连接关闭
    public static void closeDB(){
        try {
            getConnectDB().close();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    /**
     * @see 用于向数据库插入数据
     * @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 查询数据
     * @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();//出现异常就直接返回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"));
        }
    }
}

操作类:

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;
    //查询账户
    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;
    }
    //插入账户
    //删除账户
    //修改账户
    //以上是基本操作,下面是servlet调用时的一些特例操作
    //登录,密码账号争取,账号正确,密码不正确【由于不设置验证码,故必须二者均要正确才行,避免撞库】
    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";
    }
    //测试
    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());
        }
        //测试json化的数据,已在ToJson类内进行测试使用时调用即可
    }
}

将数据转化为json的类:

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;

//将所有表的查询到的结果转化为json数据的类
public class ToJson {
    //首先对表中某些字段的值进行统计,然后再交给本类
    public void json(String countType,int countNum){
        
    }
    public void json(){
        
    }
    /**
     * 本类用于将json数据直接交给html的测试
     */
    public List<FakeForms> getJsonTest(){
        //1、获取数据库数据,并进行统计
        //2、对数据进行json转化
        //3、实现基带板类型统计,然后将之数据化
        //4、x表示板卡类型,y表示统计
        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;
        
    }
    
    //获取用户json数据
    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);
            //数据json化
            JSONObject jsonObject = JSONObject.fromObject(user);
            jsonArray.add(jsonObject);
        }
        //测试
        //System.out.println(jsonArray);
        return jsonArray;
    }
    //获取单个用户json数据
    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);
            //数据json化
            JSONObject jsonObject = JSONObject.fromObject(user);
            jsonArray.add(jsonObject);
        }
        //测试
        //System.out.println(jsonArray);
        return jsonArray;
    }
    //测试
    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化
            JSONObject jsonObject = JSONObject.fromObject(four);
            array.add(jsonObject);
            System.out.println(four.getBPN2());
            System.out.println(array.toString());
        }
        //下面是将查询出的结果进行json格式化
        //下面是对User的数据json化
        System.out.println(dao.getUserJson());
        System.out.println(dao.getAUserJson("cisco"));
    }
}

映射表:

package gc.table;

/** 登录系统的账户表 **/
public class User {
    private String id;
    private String uname;
    private String pwd;
    private String 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;
    }
}

 

本篇文章主要用于记录json数据转化,注释中提到的功能多没实现,这里主要是记录JSON数据转化及前后交互,实现的过程。

基本思路:

前台发送json数据给servlet,同时请求servlet给予json数据。不考虑后台处理流程,就是这样的交互,双向交互的过程。那么具体细节呢?

首先html发送json数据请求,并请求json数据,此时servlet接收数据后,交由dao类/ToJson类进行处理,根据需要选择。而ToJson则会调用Dao类,实现代码重用,同时快速转化数据为json。即普通的数据请求,如增删改,使用dao即可,牵涉到json则交由Tojson处理。当数据到了dao这里,dao又去调用数据库连接对象进行操作。

按数据流向,我给他按【个人理解的数据分层】:

html/js          ajax请求层

servlet          数据接收层/发送

dao/ToJson/table映射类            数据处理/转化层    

ConnectionDB 数据持久层

 

posted @ 2019-07-21 15:35  CiscoLee  阅读(10135)  评论(0编辑  收藏  举报