EM8H
EM8H

Reputation: 23

Passing object array from jsp to java servlet using JSON

the following codes are what i'm trying to figure out.Hope you guys can help me !

jsp :

<input name="test" type="text" /><br/>
<input name="test" type="text" /><br/>
<input name="test" type="text" /><br/>
<input id="query" type="button" value="query" onClick="doajax()"/>

js :

function doajax(){
    var dataSet = $("input[type='text'][name='test']").serializeArray();

    $.ajax({
            type: "post",
            url: "<%=request.getContextPath()%>/testJson",
            dataType: "json",
            data:dataSet,
            error:function(){   
                alert("error occured!!!");   
            },
            success:function(data){
                alert("success");
            }  
    });
}

* [Update] *

I'm using Struts 2.0. I usually get the parameters by " get and set " instead of request.getParameters().

How can i get the dataSet in Java Servlet ?

Thank you for reading !

Upvotes: 2

Views: 9332

Answers (3)

user1049135
user1049135

Reputation:

you can try this example for getting it right :-

first pass name and age to onclick event through getUserDetails() method in js file from jsp then

  function getUserDetails() {      
       var name = document.getElementById('name');      
       var age = document.getElementById('age');

       // alert("hi " + name.value);
   $.getJSON("../webresources/myresource",
           {
                    name: name.value,
                    age: age.value
                },
                function(json) {

                    alert("name is= "+json.name+ " and age is ="+json.age);

                });
   }

and in servlet it should be like below :-

public class MyResource {

  @GET
  @Produces("application/json; charset=UTF-8")
  public Response getIt(
        @QueryParam("name") String name,
        @QueryParam("age") String age) {

    Person person = new Person();
    person.setName(name);
    person.setAge(Integer.parseInt(age));

//  Person persons = personService.findPerson(person);
    String temp1 = person.getName();
    int temp = person.getAge();
    String temp2 = Integer.toString(temp);

    StringBuffer buffer = new StringBuffer();

    buffer.append(" { 'name':'");
    buffer.append(temp1);
    buffer.append(" ','age': ");
    buffer.append(temp2);
    buffer.append(" } ");
    String json = buffer.toString();

        // for example constructed string looks like
      // String json = "{'name':'ravi','age':21}";

    return Response.ok(json, MediaType.APPLICATION_JSON).build();

}

Upvotes: 2

Bozho
Bozho

Reputation: 597016

dataSet is a regular POST parameter, so get it the regular way.

Then use a JSON library like Jackson or gson to transform the JSON to an object. You'll need to define the structure as a class, however. So, if you have a DataSet class that maps exactly to the json you sent, you can fill it with (Jackson):

ObjectMapper mapper = new ObjectMapper();
DataSet object = mapper.readValue(dataSet, DataSet.class);

Then if you want to send some JSON ase response, either convert the response data and write it to the response.getWriter(), or if the library allows this, write the output directly to the writer.

Jackson for example has writeValue(writer, object). So in a servlet:

ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(response.getWriter(), yourData);

response.setContentType("application/json");

Upvotes: 1

KishoreK
KishoreK

Reputation: 962

Use request.getParameterMap() and display all the request parameters. You may find your desired parameter there.

Upvotes: 0

Related Questions