使用 JSON 将对象数组从 jsp 传递到 java servlet

发布于 2024-10-01 06:12:21 字数 1009 浏览 2 评论 0原文

以下代码是我想要弄清楚的。希望你们能帮助我!

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");
            }  
    });
}

* [更新] *

我正在使用 Struts 2.0。 我通常通过“ get and set ”而不是request.getParameters()来获取参数。

如何在 Java Servlet 中获取 dataSet

感谢您的阅读!

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 !

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

屋顶上的小猫咪 2024-10-08 06:12:21

你可以尝试这个例子来获得正确的结果:-

首先通过jsp中的js文件中的getUserDetails()方法将姓名和年龄传递给onclick事件,然后

  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);

                });
   }

在servlet中它应该如下所示:-

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();

}

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();

}
顾冷 2024-10-08 06:12:21

dataSet 是常规的 POST 参数,因此请按常规方式获取它。

然后使用 JSON 库,例如 Jacksongson 将 JSON 转换为对象。但是,您需要将结构定义为类。因此,如果您有一个完全映射到您发送的 json 的 DataSet 类,您可以用 (Jackson) 填充它:

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

然后,如果您想发送一些 JSON ase 响应,请转换响应数据并将其写入 response.getWriter(),或者如果库允许,则将输出直接写入写入器。

例如 Jackson 有 writeValue(writer, object)。所以在 servlet 中:

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

response.setContentType("application/json");

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");
喜爱皱眉﹌ 2024-10-08 06:12:21

使用 request.getParameterMap() 并显示所有请求参数。您可以在那里找到您想要的参数。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文