基于servlet和ajax的前后台交互完整例子(通过json交互)

以前一直不太清楚web后台和前端是如何进行交互的。经过这几天的捣腾大概已经搞明白了之间是如何进行数据传递的了。

项目的目录结构:

基于servlet和ajax的前后台交互完整例子(通过json交互)_第1张图片

前端部分

add.html


<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB2312">
<title>testtitle>
<script src="https://cdn.bootcss.com/jquery/2.1.1/jquery.min.js">script>  
<script type="text/javascript">
     var xml_data = {"tag":"2","sql":"select * from tableA limit 1;","base":"4"}
    $(function(){
        $("#btn").click(function(){
            $.ajax({

                url: "http://localhost:8080/HtmlProject/servlet/addServlet",
                type:"POST",//请求方式POST
                data:"json1="+JSON.stringify(xml_data),//传过去后台的json 这里注意前面加一个"json1="
                dataType:"json", //预期从服务器中接受的数据类型
                error:function(XMLHttpRequest, textStatus, errorThrown){
                    alert(XMLHttpRequest);
                    alert(textStatus);
                    alert(errorThrown);
                },
                success:function(data){
                    alert("success");
                }
            });
        });

    });
script>
head>
<body>
<form id="form1"  method="post">
      <input type="button" value="查询" id="btn"/> 
    <ul id="ul1">ul>

    form>

body>
html>

前端的html页面有几点要注意的:

  1. 要记得引入jQuery文件 苦逼的我好几次忘了引入这个js文件,导致ajax提交请求的时候没有任何反应
  2. var xml_data = {"tag":"2","sql":"select * from tableA limit 1;","base":"4"} 这个是要向后台发送请求时发送过去的json,在ajax中的申明data时注意加个“json1=”,这样子在后台接收时通过request.getParameter(“json1”)就可以获得前端传过来的json了。

这里前端的html只是做了一个简单的按钮进行验证,其实可以把后台获取得到的json进行解析然后将对应的数据显示出来,但是在这里就不进行这一步操作了。


后台部分


数据库结构(需要操作多个数据库)
基于servlet和ajax的前后台交互完整例子(通过json交互)_第2张图片

web.xml的配置

version="1.0" encoding="UTF-8"?>
"http://www.w3.org/2001/XMLSchema-instance" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> 
    
        This is the description of my J2EE component
        name>This is the description of my J2EE componentname>
        name>addServletname>
        class>com.cn.add.addServletclass>
    
  
        This is the description of my J2EE component
        name>This is the display name of my J2EE componentname>
        name>SearchEmployeename>
        class>com.cn.query.SearchEmployeeclass>
  
  
        This is the description of my J2EE component
        name>This is the display name of my J2EE componentname>
        name>DeptListname>
        class>com.cn.query.DeptListclass>
  
  
        name>addServletname>
        /servlet/addServlet
  

 file-list>
        file>index.jspfile>
 file-list>


需要导入的包

fastjson-1.2.47.jar
mysql-connector-java-5.1.46.jar
mysql-connector-java-5.1.46-bin.jar

上面的三个jar包的资源下载链接
导入包时要特别注意的一点除了要将上面三个jar包导入eclipse中之外还需要复制一份放在WEB-INF下面的lib目录下,不然会显示找不到相关的类。


addServlet.java

package com.cn.add;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cn.bean.SqlBean;
import com.cn.dao.ConnectDatabase;

public class addServlet extends HttpServlet{

    /**
     * Constructor of the object.
     */
    public addServlet(){
        super();
    }

    /**
     * DEstruction of the servlet
     */
    public void destory(){
        super.destroy();
    }


    public void doGet(HttpServletRequest request,HttpServletResponse response)
    throws ServletException,IOException{

    }

    public void doPost(HttpServletRequest request,HttpServletResponse response)
    throws ServletException,IOException{
        response.setHeader("Access-Control-Allow-Origin", "*");//设置允许跨域访问
        int status = -2;
        String database1="database1",database2="database2",database3="database3";
        ArrayList databeseList = new ArrayList<>();


        //获取前端传递过来的json 进行处理
        String jsonStr = request.getParameter("json1");
        SqlBean sqlBean = JSON.parseObject(jsonStr,SqlBean.class);

         //操作多个数据库 判断要操作哪些数据库
        if(sqlBean.getBase() == 1) {
            databeseList.add(database1);
        }else if(sqlBean.getBase() == 2) {
            databeseList.add(database2);
        }else if(sqlBean.getBase() == 3) {
            databeseList.add(database3);
        }else if(sqlBean.getBase() == 4) {
            databeseList.add(database1);
            databeseList.add(database2);
        }else if(sqlBean.getBase() == 5) {
            databeseList.add(database1);
            databeseList.add(database3);
        }else if(sqlBean.getBase() == 6) {
            databeseList.add(database2);
            databeseList.add(database3);
        }else if(sqlBean.getBase() == 7) {
            databeseList.add(database1);
            databeseList.add(database2);
            databeseList.add(database3);
        }
        if(sqlBean.getTag()==1) {
            //增删改操作
            StringBuffer json = new StringBuffer();
            ConnectDatabase connectDB = new ConnectDatabase();
            json = connectDB.operateOfAddDeleteModify(sqlBean.getSql(),sqlBean.getBase());
             System.out.println(json);
            response.setCharacterEncoding("UTF-8");
            PrintWriter out = response.getWriter();
            out.print(json);//将状态传会给前端  json格式
        }

        if(sqlBean.getTag()==2) {
            //查询操作
            //查询返回的值自己封装就好了 因为查询的字段不确定 没办法通过类去封装
            StringBuffer json = new StringBuffer();
            ConnectDatabase connectDB = new ConnectDatabase();
            json = connectDB.operateOfQuery(sqlBean.getSql(),sqlBean.getBase());
             System.out.println(json);
            response.setCharacterEncoding("UTF-8");
            PrintWriter out = response.getWriter();
            out.print(json);//将状态传会给前端  json格式
        }      
    }

    public void init() throws ServletException{

    }
}

在doPost方法中设置了允许跨域访问 response.setHeader("Access-Control-Allow-Origin", "*") 在ajax中经常会遇到跨域无法访问问题,只要这样设置一下就可以了。这样子无论你的html放在哪里(本机的任何一个位置或者放在网络上都可以向服务器正常发送请求)。另外,前台传过来的json数据通过FastJson封装成对应的类。

//获取前端传递过来的json 进行处理
 String jsonStr = request.getParameter("json1");
 SqlBean sqlBean = JSON.parseObject(jsonStr,SqlBean.class);


sqlBean.java

package com.cn.bean;

public class SqlBean {
    /*
     * 这个类的作用是将前端传过来的json转换为javabean
     * */
    private int tag;//定义要操作的类型 1表示增删改 2表示查
    private String sql;
    private int base;

    public int getTag() {
        return tag;
    }
    public void setTag(int tag) {
        this.tag = tag;
    }
    public String getSql() {
        return sql;
    }
    public void setSql(String sql) {
        this.sql = sql;
    }
    public int getBase() {
        return base;
    }
    public void setBase(int base) {
        this.base = base;
    } 
}


ConnectDatabase.java

package com.cn.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

public class ConnectDatabase {
    /*
     * 数据库的相关操作
     * */
    Connection conn = null;
    private String databaseName;
    private String sql;

    public ConnectDatabase() {

    }

    public ConnectDatabase(String databaseName, String sql) {
        this.databaseName = databaseName;
        this.sql = sql;

    }

    public int initDatabase(String databaseName) {
        // 连接数据库
        // PreparedStatement pstmt = null;
        int databaseStatus;// 1表示连接成功 0表示连接失败
        try {
            try {
                Class.forName("com.mysql.jdbc.Driver");
                System.out.println("成功加载sql驱动");
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                System.out.println("找不到sql驱动");
                e.printStackTrace();
            }
            // String url="jdbc:mysql://10.2.17.209:3306/"+databaseName;
            String url = "jdbc:mysql://10.2.17.209:3306/" + databaseName;
            // 创建一个Statement对象
            // conn = (Connection) DriverManager.getConnection(url,"root","root");
            conn = (Connection) DriverManager.getConnection(url, "root", "root");
            Statement stmt = (Statement) conn.createStatement(); // 创建Statement对象
            System.out.print("成功连接到数据库!");
            databaseStatus = 1;// 数据库连接成功
            return databaseStatus;

        } catch (SQLException ex) {
            databaseStatus = -1;// 连接失败 可能的情况是数据库名是错误的 数据库没开
            return databaseStatus;
        }

    }

    public StringBuffer operateOfAddDeleteModify(String sql,int base) {
        // 执行增删改相关的操作
        //服务器上的数据库
        String database1 = "database_1", database2 = "database_2", database3 = "database_3";
        ArrayList databeseList = new ArrayList<>();
        if (base == 1) {
            databeseList.add(database1);
        } else if (base == 2) {
            databeseList.add(database2);
        } else if (base == 3) {
            databeseList.add(database3);
        } else if (base == 4) {
            databeseList.add(database1);
            databeseList.add(database2);
        } else if (base == 5) {
            databeseList.add(database1);
            databeseList.add(database3);
        } else if (base == 6) {
            databeseList.add(database2);
            databeseList.add(database3);
        } else if (base == 7) {
            databeseList.add(database1);
            databeseList.add(database2);
            databeseList.add(database3);
        }


        boolean statusAfterOperate = false;// 插入操作后的状态
        StringBuffer statusJson = new StringBuffer();//{"status":"
        Statement stmt;

        //遍历查询数据库
        for (int k = 0; k < databeseList.size(); k++) {
            String database = (databeseList.get(k));
            initDatabase(database);
            try {

                stmt = conn.createStatement();
                System.out.println("执行在这儿1");
                stmt.executeUpdate(sql);//
                statusAfterOperate = true;
                conn.close();// 关闭连接

            } catch (SQLException e) {
                // TODO Auto-generated catch block
                System.out.println("执行在这儿2");
                statusAfterOperate = false;// 如果抛出异常 则返回-1 证明没有正确插入
            }
        }
        if(statusAfterOperate) {
            statusJson.append(" {\"status\":\"1\"} ");//{"status":"1"}
        }
        else {
            statusJson.append(" {\"status\":\"0\"} ");//{"status":"0"}
        }
        return statusJson;
    }

    public StringBuffer operateOfQuery(String sql, int base) {
        // 服务器上的数据库
        String database1 = "database_1", database2 = "database_2", database3 = "database_3";
        ArrayList databeseList = new ArrayList<>();
        StringBuffer error = new StringBuffer("{\"status\":\"0\"}");// {"status":"0"}
        // 判断要操作哪些数据库
        if (base == 1) {
            databeseList.add(database1);
        } else if (base == 2) {
            databeseList.add(database2);
        } else if (base == 3) {
            databeseList.add(database3);
        } else if (base == 4) {
            databeseList.add(database1);
            databeseList.add(database2);
        } else if (base == 5) {
            databeseList.add(database1);
            databeseList.add(database3);
        } else if (base == 6) {
            databeseList.add(database2);
            databeseList.add(database3);
        } else if (base == 7) {
            databeseList.add(database1);
            databeseList.add(database2);
            databeseList.add(database3);
        }

        Statement stmt;
        try {
            StringBuffer resultAsJson = new StringBuffer("{\"status\":\"1\",\"value\":[");

            for (int k = 0; k < databeseList.size(); k++) {

                String database = (databeseList.get(k));
                initDatabase(database);
                ArrayList columnNameList = new ArrayList<>();
                stmt = conn.createStatement();
                ResultSet rs = stmt.executeQuery(sql);
                ResultSetMetaData data = rs.getMetaData();

                for (int i = 1; i <= data.getColumnCount(); i++) {
                    columnNameList.add(data.getColumnName(i));
                }
                while (rs.next()) {
                    // System.out.println(database);
                    for (int i = 1; i <= columnNameList.size(); i++) {
                        if (i == 1) {
                            resultAsJson.append("{");
                        }
                        resultAsJson.append("\"");// "
                        resultAsJson.append(columnNameList.get(i - 1));
                        resultAsJson.append("\":\"");// ":"

                        resultAsJson.append(rs.getString(i) + "\"");
                        if (!(i == columnNameList.size())) {
                            resultAsJson.append(",");
                        }
                    }
                    resultAsJson.append(",\"database\":\"");
                    resultAsJson.append(database);
                    resultAsJson.append("\"}");//
                    if (rs.isLast()) {
                    } else {
                        resultAsJson.append(",");// ",
                    }

                }
                if (!(k == databeseList.size() - 1))
                    resultAsJson.append(",");
            }
            resultAsJson.append("]}");

            return resultAsJson;
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            return error;

        }

    }

}




直到这里,相关的代码和配置都已经完成,在eclipse启动一下tomcat,运行一下效果如下:
基于servlet和ajax的前后台交互完整例子(通过json交互)_第3张图片

后台返回给前端的json格式(这里我没有在前端显示出来但是打印出来了):

{"status":"1","value":[{"id":"1","attrA":"1","database":"database_1"},{"id":"1","attrA":"hellwwo","database":"database_2"}]}

如果需要将web项目放到服务器上,在eclipse那里将web项目打包成war包放在服务器tomcat目录下的webapps下面就可以了。不过前端html通过ajax请求时的url的localhost记得改为服务器的ip。至此,一个前后端成功连接的例子就完成了。

你可能感兴趣的:(java)