如何将对象从java类传递给servlet? [英] How to pass an object from a java class to servlet?

查看:227
本文介绍了如何将对象从java类传递给servlet?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Apache的HttpClient从Java类调用servlet。我想向servlet发送一个对象,该对象应使用Serialization保存对象。如何将对象发送到servlet?

I am using Apache's HttpClient to call a servlet from a Java class. I want to send an object to the servlet which should save the object using Serialization. How to send the object to the servlet?

public static void main(String[] args) {

        Names names = new Names();
        names.setName("ABC");
        names.setPlace("Bangalore");
        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet("http://localhost:9080/HttpClientPractice/FirstServlet");
//Rest of the code

在上面的代码片段中,我有另一个类Names我想将一个Names对象发送到servlet。现在我只用URI调用servlet,但我想传递对象。

In the above code snippet, I have another class Names and I want to send an object of Names to the servlet. Right now I am only calling the servlet with the URI, but I want to pass the object.

谢谢!

推荐答案

使用像已经显示的类中的Gson 并将此字符串添加为查询参数 - 向您展示如何使用Gson。

Convert the object to a Json String using a Library like Gson in the class you have shown and add this string as a query parameter - showing you how to do it with Gson.

Gson gson = new Gson();
String json = gson.toJson(names);
HttpGet httpget = new HttpGet("http://localhost:9080/HttpClientPractice/FirstServlet?obj="+json);

在您要存储此对象的类中,执行fromJson(Gson库中的方法)

In the class you are going to store this object, do a fromJson (method in the Gson library)

Gson gson = new Gson();
Names names = fromJson(json, Names.class);

这篇关于如何将对象从java类传递给servlet?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆