How to persist a record in the database through Java restful webservice?

Asked

Viewed 1,474 times

4

I already have a method that takes a json and persists in the Mysql database. I can test it by the interface created by Netbeans, which has a field for inserting a json, but how do I make an http request within a java application by passing the json as a parameter to be persisted?

Method used for data persistence:

@PUT
@Consumes("application/json")
public void putJson(String json) throws Exception{
    Cliente cliente;
    Gson gson = new Gson();

    java.lang.reflect.Type tipo = new TypeToken<Cliente>(){}.getType();

    cliente = gson.fromJson(json, tipo);

    Conexao con = new Conexao();
    con.conexao();

    PreparedStatement ps = con.con.prepareStatement("insert into cliente values(?,?)");
    ps.setString(1, cliente.getCnpj());
    ps.setString(2, cliente.getRazao_social());
    ps.execute();

}

Thanks in advance!

  • Marco, I advise you to use the Angularjs $http for this is super simple and quick to do, if you are interested put a code here for you ;)

  • Opa, por favor Fábio!

1 answer

2


I advise you to use Angularjs, it is very practical and easy to learn, I made an example for you on Jsfiddle.

In this example I showed you how to consume a REST API by the GET method, I know you need a POST, but I couldn’t find an ENDPOINT POST available to make an example, but I believe that the code of a GET example will help you conceptualize about angular, At the end I give an example of POST. OK?

Here’s the code and its explanations:

Javascript file

var app = angular.module('myApp', []);
app.controller('HtmlController',['$scope', '$http', function ($scope, $http) {
    var endpoint = 'http://162.243.233.191:3000/api/ip';
    $scope.buscarJson = function () {
        $http.get(endpoint).success(function (data) {
            $scope.json = data;
        }).error(function (error) {
            console.error(error);
        });
    };
}]);

Here we create our angular module called myapp, then we create a controller that we will use in our HTML screen called Htmlcontroller.

Angular works with dependency injection control $Scope and $http are angular dependencies that we are injecting to use in our controller.

The $Scope is an object that is available to be used in HTML, any function or variable that you create in it you can use on your screen (as long as the screen is using this controller).

We have the function fetch, use this function to fetch the user’s IP, this function uses the $http and searches for an IP address on enpoint http://162.243.233.191:3000/api/ip, if success is saved in the variable json, Error case print error message in console.

HTML file

<body>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.js"></script>
    <div ng-app="myApp">
        <div ng-controller="HtmlController">
            <button type="button" ng-click="buscarJson()">
                Verificar IP
            </button>
            <h4> Seu IP Address é: </h4>
            <p>
                {{json.ip}}
            </p>
        </div>
    </div>
</body>

In HTML we include the angular JS so we can use it in our Htmlcontroller.

We need to inform our HTML the angular module we create, we do this using the attribute ng-app, then we also need to inform our HTML controller in our ng-controller our Htmlcontroller.

Then we use the function fetch that we create in our controller, passes this we add in our button ng-click.

Finally, the angle is seeing the variable json through the markers {{}}, note that we are showing the field ip contained in the variable json. Magically when the variable is filled (by clicking the button) your IP will appear on the screen.

Now in your case, just change the endpoint we specified to your endpoint, and change the $http get. for $http post., the only difference would be this:

var cliente = {
    cnpj: 45057131000143,
    razao_social: 'Stackoverflow'
};
$http.post('/seu_end_point', cliente).success(function(data) {
     console.log(data);
}).error(function(error) {
     console.log(error);
});

I hope I helped!!! Any doubt I’m available. :-)

ps: In Jsfiddle I did not import the JS file that contains the Htmlcontroller we created, as it already does this automatically. When making the example don’t forget to import js into your HTML.

  • Thank you very much!

  • Mark one more thing, you are using the PUT method, the correct use of the PUT method is when changing a record. Ok? POST is for saving new records.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.