2

I have a controller for AngularJS Framework. I use a Http Post Request to send an array to a server. How to get this array in a java method?

This is my controller

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {

var indici = new Array();

indici.push(1);
indici.push(2);

$http.post("http://localhost:8080/SistemiDistribuiti/rest/Point/Trovati", indici, {
              headers: { 'Content-Type': 'application/json' }
            }).success(function(receivedData, status) {
                $scope.someData = receivedData;
            });

And this is my java class but i don't know how to get my array.

import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.POST;
import javax.ws.rs.Consumes;

@Path("Point")
public class PointService {


@POST
@Path("Trovati")
@Consumes(MediaType.APPLICATION_JSON)
public void RetrieveData() {
     //how print my array?
}
legolas07
  • 79
  • 1
  • 7
  • If your problem is to retrieve the data on the server side, then please update your client code to actually send something. – lex82 Nov 30 '15 at 13:48
  • My problem is that i have an array (indici) in my controller. I want to send this array to server side (i use tomcat), but i don't know if the http request is correct e and how to retrieve this array in my java code. – legolas07 Nov 30 '15 at 13:52

3 Answers3

1

You have to use @GET as below:

@GET
@Path("/blabla")
public Response receiveListOfStrings(@QueryParam("list") final List<String> list){
    log.info("receieved list of size="+list.size());
    return Response.ok().build();
}

And request:

GET http://example.com/services/echo?list=balbla&list=asdasd&list=BYE

Post doesn't support this. Or you can use @PUT with complex type.

Put example:

@PUT
public Response putExample(MyObject obj) {
    log.info("receieved list of size="+obj.getList().size());
    return Response.ok().build();
}

In this put example you can see I used a custom MyObject Here's its codes:

public class MyObject{

    private List<String> list = new ArrayList<String>();

    public List<String> getList(){
        return list;
    }

    public void setList( List<String> list ){
        this.list = list;
    }

    @Override
    public String toString(){
        return "MyObject [list=" + list + "]";
    }

}

As you can see there's a list property in your MyObject class. So you can print anything by calling getList as my example above.

Sercan Ozdemir
  • 4,641
  • 3
  • 34
  • 64
  • How to use a put request? I change post with put in the controller, but in the java class? – legolas07 Nov 30 '15 at 09:52
  • Please see I've edited my answer, you can create a class and put an array in it then you can use it like above. – Sercan Ozdemir Nov 30 '15 at 09:59
  • Thanks for reply but in your code where is my array? why the method putexample has a object parameter? how get my array, and print with the normal system.out.print? Sorry but i am a noob with http request. – legolas07 Nov 30 '15 at 10:19
  • Please see the answer here: http://stackoverflow.com/questions/2697541/convert-json-query-parameters-to-objects-with-jax-rs – Sercan Ozdemir Nov 30 '15 at 12:10
1

I agree with @lex82, you don't send the payload within your request. See the documentation for $http.post: https://docs.angularjs.org/api/ng/service/$http#post. Be sure to understand what promises are and how they are used within the HTTP support of Angular.

Here is a sample:

var dataToSend = {
  // some JSON data
};
$http.post("/some-url", dataToSend, {
  headers: { 'Content-Type': 'application/json' }
}).success(function(receivedData, status) {
        $scope.someData = receivedData;
});

That said, you say that you don't receive the data on the server. The first to do is to check your raw request. This can be done within Chrome using the Chrome Developer Tools (CRTL + SHIFT + i). This will give you access to a Network tab containing every request. Click on the request corresponding to your AJAX request and check if there is a payload in your request. If so, it's a problem on your server side within your JAXRS application.

Do you some exceptions within your JAXRS application?

Hope it helps you, Thierry

Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
  • Perhaps, you forgot to set the `Content-Type` header in the AJAX request... I updated my answer regarding this in the Angular snippet. – Thierry Templier Nov 30 '15 at 14:02
  • Ok, i understand the http request but i don't know how to retrieve this data on the java class. – legolas07 Nov 30 '15 at 14:31
  • It's just the parameter you specify in the annotated method with `@POST`... You should have in the classpath a tool like Jackson to convert the payload content from string to object... – Thierry Templier Nov 30 '15 at 14:33
  • Ok, i found this http://www.mkyong.com/java/jackson-2-convert-java-object-to-from-json/ Now try it. – legolas07 Nov 30 '15 at 14:59
1

Apache has an http library that can be used to make various http requests.

<dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
      <version>4.3.2</version>
  </dependency>

You will also need a library that can be used to transform your json objects into Java object. Google has created a library called gson that I will use in my example.

<dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.2.4</version>
  </dependency>

You are also going to have to create a Java object that represents your data. This will be used to map your json object to a java object or "pojo". I'm not sure what your JSON objects look like, but I'm going to use a generic example called Response.

public class Response
{
    private List<Example> examples;
    private double total;
    private String someString;

    public QuoteResponse()
    {
        super();
    }

    public List<Examples> getExamples() {
        return examples;
    }

    public void setExamples(List<Examples> examples)
    {
        this.examples = examples;
    }

    public double getTotal() {
        return total;
    }

    public void setTotal(double total) {
        this.total = total;
    }

    public String getSomeString() {
        return someString;
    }

    public void setPrint_type(String someString) {
        this.someString = someString;
    }
}

Your java object has to have the same number of fields with the same type and same name as your JSON object.

Next, you will have to write a function that calls your angular api. See an example below:

public Response getJsonData()
{
    params = new Params();
    String url = "https://www.yoururl.com/controller/function_you_want;
    Response response = null;
    HttpGet httpGet = new HttpGet(url);

    try
    {
        response = httpClient.execute(httpGet);

        //check to make sure that everything is ok
        if(response.getStatusLine().getStatusCode() == 200)
        {
            entity = response.getEntity();
            jsonResponse = EntityUtils.toString(entity);
            JsonNode root = mapper.readTree(jsonResponse).get("result");
            response = gson.fromJson(root.toString(),Response.class);
        }
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }

    return response;
}

That's about it. Let me know if you have any questions.

j.jerrod.taylor
  • 1,120
  • 1
  • 13
  • 33
  • My array indici ( in the controller angular) is an array of int. With your code how to save my array to an array of int in java? – legolas07 Nov 30 '15 at 15:28
  • @legolas07 You just have to add the type to the java class. For example, instead of having a List example you would have List example. – j.jerrod.taylor Nov 30 '15 at 18:59
  • I changed the name of constructor because it was different from the name of class. Tomorrow i'll test the code! – legolas07 Nov 30 '15 at 23:04
  • Are you sure that this code (getJsonData) is correct? I'm trying to compile it, but there are many errors. – legolas07 Dec 01 '15 at 09:06
  • @legolas07 It was meant to be more of a guide as opposed to being code that you could just copy into your application and run as is. With that being said, yes it is correct. I took that example from an earlier project that I did, though I did delete some things for simplicity. My project compiles and I'm able to read and parse the json response from the api that I'm calling. Any errors that you are having are on your end and without looking at your code, I can't tell you why it isn't working for you. – j.jerrod.taylor Dec 01 '15 at 14:16