码迷,mamicode.com
首页 > 数据库 > 详细

java连接MySQL数据库 json数据前后端交互

时间:2016-05-03 18:13:10      阅读:214      评论:0      收藏:0      [点我收藏+]

标签:

先在下图文件夹中导入相应的jar包,其中第一个红框中的是使用json数据必须导入的两个包,上面5个jar包也是json包,看情况添加,第二个红框是用JDBC连接MySQL数据库必须的包。
技术分享

连接MySQL的工具类:

package com.XXXXXX.util;

import java.sql.Connection;
import java.sql.DriverManager;

public class MysqlUtil
{
    private static Connection conn = null; //数据库连接
    private static String server = "localhost"; //服务ip
    private static String port = "3306"; //服务端口
    public static String dbname = "XXXXX"; //数据库名
    private static String user = "root"; //数据库用户名
    private static String pass = "XXXXX"; //数据库密码
    private static String drivername = "com.mysql.jdbc.Driver"; //MySql驱动类名
    private static String url = "jdbc:mysql://" + server + ":" + port + "/" + dbname + "?user=" + user + "&password=" + pass + "&useUnicode=true&characterEncoding=UTF-8"; //连接地址

    public static Connection getConn()
    {
        try
        {
            Class.forName(drivername).newInstance(); //加载JDBC驱动
            conn = DriverManager.getConnection(url); //建立连接
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        return conn;
    }
}

服务端上的查询Servlet:

package com.XXXXX.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

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

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.webmappoi.util.MysqlUtil;

public class GetPoiInfoServlet extends HttpServlet
{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    /**
     * The doGet method of the servlet. <br>
     * 
     * This method is called when a form has its tag value method equals to get.
     * 
     * @param request
     *            the request send by the client to the server
     * @param response
     *            the response send by the server to the client
     * @throws ServletException
     *             if an error occurred
     * @throws IOException
     *             if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {

        /*
         * response.setContentType("text/html"); PrintWriter out =
         * response.getWriter();out.println(
         * "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
         * out.println("<HTML>");
         * out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
         * out.println("  <BODY>"); out.print("    This is ");
         * out.print(this.getClass()); out.println(", using the GET method");
         * out.println("  </BODY>"); out.println("</HTML>"); out.flush();
         * out.close();
         */

        this.doPost(request, response);
    }

    /**
     * The doPost method of the servlet. <br>
     * 
     * This method is called when a form has its tag value method equals to
     * post.
     * 
     * @param request
     *            the request send by the client to the server
     * @param response
     *            the response send by the server to the client
     * @throws ServletException
     *             if an error occurred
     * @throws IOException
     *             if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {

        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        JSONArray array = new JSONArray();
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        String sql = "select * from university";
        try
        {
            con = MysqlUtil.getConn();
            ps = con.prepareStatement(sql);
            rs = ps.executeQuery();
            while (rs.next())
            {
                JSONObject temp = new JSONObject().element("id", rs.getInt("U_ID")).element("point", rs.getString("U_Point")).element("title", rs.getString("U_Title")).element("address", rs.getString("U_Addr")).element("tel", rs.getString("U_Tel"));
                array.add(temp);
            }
            out.print(array.toString()); //将array对象传到前端
            System.out.println(array.toString());
            out.flush();
            out.close();
        } catch (SQLException e)
        {
            e.printStackTrace();
        } finally
        {
            try
            {
                //依次关闭连接
                if (rs != null)
                {
                    rs.close();
                    rs = null;
                }
                if (ps != null)
                {
                    ps.close();
                    ps = null;
                }
                if (con != null)
                {
                    con.close();
                    con = null;
                }
            } catch (SQLException e)
            {
                e.printStackTrace();
            }
        }
    }
}

前端js接收array对象并解析:

$.getJSON("./servlet/GetPoiInfoServlet",function(json)
{  
for(var i=0;i<json.length;i++)
        {
        //var json = eval(json);
            //console.log(JSON.stringify(json));
            //获取经纬度
            ulng = parseFloat(json[i].point.split(",")[0]); //以,分割成数组
            ulat = parseFloat(json[i].point.split(",")[1]);  
            var uid = parseFloat(json[i].id);
            var title = json[i].title;
            var address = json[i].address;
            var point = json[i].point;
            var tel = json[i].tel;
        }
});

/********************************************************************
getJSON函数所接收的数据就是json格式,所以可以不用eval函数转化。function中参数json就是后台Servlet传来的array对象。getJSON函数还有一个问题就是,用它从前端传数据到后台时,如果有中文的话,传到后台的数据就会乱码。(网上有解决办法,但我没试过,我就用post方法将就了,post方法不会乱码,但是在接收是需要用eval函数转化。)
********************************************************************/

前端js中封装表单成json数据:

function GetJsonData() 
{
    var json = 
    {
            "point": GID("point").value,
            "title": GID("title").value,
            "address": $("#address").val(),
            "tel": $("#tel").val()
        };
        return json;
}

前端js中封装document.getElementById方法:

function GID(id) 
{
    return document.getElementById(id);
}

前端js中用Jquery post方法提交表单json数据:

function post()
{
/*$("#status").html("正在提交数据,请勿关闭当前窗口...");
    var url = GID("form1").action;
        //alert(JSON.stringify(GetJsonData()));
        $.ajax(
        {
            type: "POST",
            //url: "./servlet/AddPoiDataServlet",
            url: url,
            //contentType: "application/json; charset=utf-8",
            data: {data: JSON.stringify(GetJsonData())},
            //dataType: "json",
            success: function (json) 
            {
                if (json.length > 0) 
                {
                    alert("提交成功!");
                }
            },
            error: function (json) 
            {
                $("#status").html("提交数据失败!");
            }
        });*/

    var url = GID("form1").action;
    //alert(url);
    $("#status").html("正在提交数据,请勿关闭当前窗口...");
    $.post(url,{data:JSON.stringify(GetJsonData())},function (msg) 
{
    //alert("提交成功!");
            $("#status").html("提交成功!");
     });
}

/*******************************************************************************
JSON.stringify()函数是为了将json数据字符串化。Jquery ajax和post方法都能将表单传到后端,post方法封装了ajax,用起来更简单。
******************************************************************************/

后台Servlet接收前端传来的json数据并保存到MySQL数据库中:

//System.out.println("地名:" + request.getParameter("title") + "<br>");
        JSONObject json = JSONObject.fromObject(request.getParameter("data")); //获取前端传来的data
        System.out.println(json.toString());
        Connection con = null;
        PreparedStatement ps = null;
        int result = 0;
        String sql = "insert into university(U_Point,U_Title,U_Addr,U_Tel) values(?,?,?,?)";
        try
        {
            con = MysqlUtil.getConn();
            ps = con.prepareStatement(sql);
            ps.setString(1, json.getString("point"));
            ps.setString(2, json.getString("title"));
            ps.setString(3, json.getString("address"));
            ps.setString(4, json.getString("tel"));
            result = ps.executeUpdate();
            out.print(json.toString());
            System.out.println(json.toString());
            out.flush();
            out.close();
        } catch (SQLException e)
        {
            e.printStackTrace();
        } finally
        {
            try
            {
                if (ps != null)
                {
                    ps.close();
                    ps = null;
                }
                if (con != null)
                    con.close();
                    con = null;
            } catch (SQLException e)
            {
                e.printStackTrace();
            }
        }

其它的修改,删除Servlet:
删除servlet:

String sql = "delete from university where U_ID=?";
try
{
    con = MysqlUtil.getConn();
    ps = con.prepareStatement(sql);
    ps.setInt(1, json.getInt("id"));
    result = ps.executeUpdate();
    json.put("result", true);
    out.print(json.toString());
    System.out.println(json.toString());
    out.flush();
    out.close();
}

修改servlet:

String sql = "update university set U_Title=?,U_Addr=?,U_Tel=? where U_Point=?";
try
{
    con = MysqlUtil.getConn();
    ps = con.prepareStatement(sql);
    ps.setString(1, json.getString("title"));
    ps.setString(2, json.getString("address"));
    ps.setString(3, json.getString("tel"));
    ps.setString(4, json.getString("point"));
    result = ps.executeUpdate();
    //json.put("result", true);
    out.print(json.toString());
    System.out.println(json.toString());
    out.flush();
    out.close();
}

模糊查询:
前端js传输查询条件并接受后台查询数据库之后传过来的json数据:

function selectInfo()  //模糊查询
{
    var json =
    {
        "title": GID("info").value
    };
    //alert(JSON.stringify(json));
    $.post("./servlet/SelectPoiInfoServlet",{data:JSON.stringify(json)},function(json)
    {  
         for(var i=0;i<json.length;i++)
         {
            var json = eval(json);
             //获取经纬度
             ulng = parseFloat(json[i].point.split(",")[0]);
             ulat = parseFloat(json[i].point.split(",")[1]);    

             var uid = parseFloat(json[i].id);
             var title = json[i].title;
             var address = json[i].address;
             var point = json[i].point;
             var tel = json[i].tel;
           }
    });
}   

/*****************************************************************************************
这里不能用getJSON方法,因为如果前端传过来json数据有中文,到后台就会乱码,所以就用post方法。
******************************************************************************************/

后台模糊查询的servlet:

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

        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        JSONObject json = JSONObject.fromObject(request.getParameter("data"));
        System.out.println(json.toString());
        JSONArray array = new JSONArray();
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        String sql = "select * from university where U_Title like ?";
        try
        {
            con = MysqlUtil.getConn();
            ps = con.prepareStatement(sql);
            ps.setString(1, "%" + json.getString("title") + "%");
            rs = ps.executeQuery();
            while (rs.next())
            {
                JSONObject temp = new JSONObject().element("id", rs.getInt("U_ID")).element("point", rs.getString("U_Point")).element("title", rs.getString("U_Title")).element("address", rs.getString("U_Addr")).element("tel", rs.getString("U_Tel"));
                array.add(temp);
            }
            out.print(array.toString()); //将array对象传到前端
            System.out.println(array.toString());
            out.flush();
            out.close();
        }

关于模糊查询:
参考JDBC 模糊查询 传参问题,附文如下:
错误写法:String sql = “select * from tableName where column like ‘%?%’”;
这样写,?是不能传参进来的,因为编译的时候?没被编译成传参标识,所以执行时会抛出SQLException。
正确写法有两种:
1、String sql = “select * from tableName where column like ‘%” + columnValue + “%’”; //可以直接将变量值写进sql语句
2、String sql = “select * from tableName where column like ?”; //可以利用jdbc的传参函数传进
PreparedStatement ps = conn.PreparedStatement(sql);
ps.setString(1, “%” + columnValue + “%”);

其中遇到的问题:
1. 使用自己安装的jdk时会报错(如下图),只有用Myeclipse自带的版本才可以。
技术分享
我所使用的JDK版本及MyEclipse的JDK版本如下:
技术分享
只有选中下面那个Sun JDK 1.6.0_13才不会报错,不知道why?
 
2. 在Servlet中修改doPost()或doGet()方法,发布到浏览器时,仍出现This is class XXXXXXXX, using the POST method的字样,如图:
技术分享
解决办法是:重启Tomcat,重新发布。

参考资料:
[1] http://blog.163.com/jackswu@yeah/blog/static/140629123201161810168361/

java连接MySQL数据库 json数据前后端交互

标签:

原文地址:http://blog.csdn.net/qq_20828113/article/details/51302203

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!