如何使用jQuery Post和Java在PostgreSQL中保存json数据?

时间:2022-10-22 22:57:22

I would like to save my json data object into my Postgresql using jQuery(ajax call on post request) and Java after clicking Submit button, Please help me to do this ? Thanks in advance.

我想在点击提交按钮后使用jQuery(发布请求时调用ajax)和Java将我的json数据对象保存到我的Postgresql中,请帮我这样做?提前致谢。

html:

(function() {
  var testValue;
  testValue = {};
  $('input[id=buttonId]').click(function() {
    var name;
    name = $(this).attr('name');
    testValue[name] = $(this).val();
  });
  $('#submit').click(function() {
    $('input[id=fileId]').each(function($i) {
      var name;
      name = $(this).attr('name');
      testValue[name] = $(this).val();
    });
    console.log(JSON.stringify(testValue));//it gives the json data object, after clicking on Submit button`[ex: {"firstButton":"button1","secondButton":"button2","file":"test.txt"} ]`
  });
})();

Postgresql table: create table savedata(id integer primary key, content json);

Postgresql表:create table savedata(id整数主键,内容json);

credentials:

db.default.driver=org.postgresql.Driver
db.default.url="jdbc:postgresql://localhost:5432/dbname"
db.default.user=test
db.default.password=test

html:

<input type='button' value='button1' class='button' id="buttonId" name='firstButton'/>
<input type='button' value='button2' class='button' id="buttonId" name='secondButton'/>
<input type='file' name='file' id="fileId" value='file upload'/>
<input type='submit' value='submit' id='submit'>

1 个解决方案

#1


0  

I would start by writing a HTTP server in java which accepts POST requests from javascript later. You would be smart to also add some form of authentication in it so not everybody can add records. You can also use a framwork which I would use.

我首先在java中编写一个HTTP服务器,它接受来自javascript的POST请求。您也可以在其中添加某种形式的身份验证,因此并非每个人都可以添加记录。你也可以使用我会使用的框架。

As soon as a POST request comes in with JSON data and the required authorisation you can let Java parse the JSON to Insert statements for the database.

一旦POST请求带有JSON数据和所需的授权,您就可以让Java将JSON解析为数据库的Insert语句。

Now the Javascript part: you can best send JSON encoded data with ajax using jQuery. Use a POST request.

现在Javascript部分:你可以使用jQuery最好用ajax发送JSON编码数据。使用POST请求。

In this case it would look like using:

在这种情况下,它看起来像使用:

  • http://www.tutorialspoint.com/postgresql/postgresql_java.htm

  • How to parse a JSON and turn its values into an Array?

    如何解析JSON并将其值转换为数组?

  • http://restx.io/docs/ref-core.html

    // Create a method that handles a POST request. In this case to "/message"
    @POST("/message/}")
    public Message insertInDb(Message msg // body param
                            ) {
        // Decode the JSON to an array object so you can loop it for insert statement(s)           
       JSONArray json = new JSONArray(msg);
        /////////////////////////////////////////////////////////////////////
      // Create the postgre connection
      Connection c = null;
      Statement stmt = null;
      try {
         Class.forName("org.postgresql.Driver");
         c = DriverManager
            .getConnection("jdbc:postgresql://localhost:5432/testdb",
            "manisha", "123");
         c.setAutoCommit(false);
         System.out.println("Opened database successfully");
    
         stmt = c.createStatement();
    
         // Use the JSON data instead below for the INSERT statement:
         String sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) "
               + "VALUES (1, 'Paul', 32, 'California', 20000.00 );";
         stmt.executeUpdate(sql);
    
    
         stmt.close();
         c.commit();
         c.close();
      } catch (Exception e) {
       return  e.getClass().getName()+": "+ e.getMessage();
    
      }
        return "success";
    }
    
  • http://restx.io/docs/ref-core.html //创建一个处理POST请求的方法。在这种情况下“/ message” @POST( “/消息/}”) public message insertInDb(Message msg // body param                         ){     //将JSON解码为数组对象,以便为循环语句循环它    JSONArray json = new JSONArray(msg);     ////////////////////////////////////////////////// ///////////////////   //创建postgre连接   连接c = null;   语句stmt = null;   尝试{      的Class.forName( “org.postgresql.Driver”);      c = DriverManager         .getConnection( “JDBC:在PostgreSQL://本地主机:5432 / TESTDB”,         “manisha”,“123”);      c.setAutoCommit(假);      System.out.println(“已成功打开数据库”);      stmt = c.createStatement();      //使用下面的JSON数据作为INSERT语句:      String sql =“INSERT INTO COMPANY(ID,NAME,AGE,ADDRESS,SALARY)”            +“VALUES(1,'Paul',32,'California',20000.00);”;      stmt.executeUpdate(SQL);      stmt.close();      c.commit();      c.close();   } catch(例外e){    return e.getClass()。getName()+“:”+ e.getMessage();   }     回归“成功”; }

jQuery

    //POST JSON data to the API
    $.post( "youdomain.com/message", JSON.stringify(yourDataObjectOrArray));

#1


0  

I would start by writing a HTTP server in java which accepts POST requests from javascript later. You would be smart to also add some form of authentication in it so not everybody can add records. You can also use a framwork which I would use.

我首先在java中编写一个HTTP服务器,它接受来自javascript的POST请求。您也可以在其中添加某种形式的身份验证,因此并非每个人都可以添加记录。你也可以使用我会使用的框架。

As soon as a POST request comes in with JSON data and the required authorisation you can let Java parse the JSON to Insert statements for the database.

一旦POST请求带有JSON数据和所需的授权,您就可以让Java将JSON解析为数据库的Insert语句。

Now the Javascript part: you can best send JSON encoded data with ajax using jQuery. Use a POST request.

现在Javascript部分:你可以使用jQuery最好用ajax发送JSON编码数据。使用POST请求。

In this case it would look like using:

在这种情况下,它看起来像使用:

  • http://www.tutorialspoint.com/postgresql/postgresql_java.htm

  • How to parse a JSON and turn its values into an Array?

    如何解析JSON并将其值转换为数组?

  • http://restx.io/docs/ref-core.html

    // Create a method that handles a POST request. In this case to "/message"
    @POST("/message/}")
    public Message insertInDb(Message msg // body param
                            ) {
        // Decode the JSON to an array object so you can loop it for insert statement(s)           
       JSONArray json = new JSONArray(msg);
        /////////////////////////////////////////////////////////////////////
      // Create the postgre connection
      Connection c = null;
      Statement stmt = null;
      try {
         Class.forName("org.postgresql.Driver");
         c = DriverManager
            .getConnection("jdbc:postgresql://localhost:5432/testdb",
            "manisha", "123");
         c.setAutoCommit(false);
         System.out.println("Opened database successfully");
    
         stmt = c.createStatement();
    
         // Use the JSON data instead below for the INSERT statement:
         String sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) "
               + "VALUES (1, 'Paul', 32, 'California', 20000.00 );";
         stmt.executeUpdate(sql);
    
    
         stmt.close();
         c.commit();
         c.close();
      } catch (Exception e) {
       return  e.getClass().getName()+": "+ e.getMessage();
    
      }
        return "success";
    }
    
  • http://restx.io/docs/ref-core.html //创建一个处理POST请求的方法。在这种情况下“/ message” @POST( “/消息/}”) public message insertInDb(Message msg // body param                         ){     //将JSON解码为数组对象,以便为循环语句循环它    JSONArray json = new JSONArray(msg);     ////////////////////////////////////////////////// ///////////////////   //创建postgre连接   连接c = null;   语句stmt = null;   尝试{      的Class.forName( “org.postgresql.Driver”);      c = DriverManager         .getConnection( “JDBC:在PostgreSQL://本地主机:5432 / TESTDB”,         “manisha”,“123”);      c.setAutoCommit(假);      System.out.println(“已成功打开数据库”);      stmt = c.createStatement();      //使用下面的JSON数据作为INSERT语句:      String sql =“INSERT INTO COMPANY(ID,NAME,AGE,ADDRESS,SALARY)”            +“VALUES(1,'Paul',32,'California',20000.00);”;      stmt.executeUpdate(SQL);      stmt.close();      c.commit();      c.close();   } catch(例外e){    return e.getClass()。getName()+“:”+ e.getMessage();   }     回归“成功”; }

jQuery

    //POST JSON data to the API
    $.post( "youdomain.com/message", JSON.stringify(yourDataObjectOrArray));