Java 创建一个返回 JSON 响应的简单页面

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21427383/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 08:41:00  来源:igfitidea点击:

Create a simple page that returns a JSON response

javajsp

提问by rickygrimes

The team that works on the client side in my project has asked me to write a sample test page, and give them a working URL that they can hit and get back 200. They have asked me to also give a sample request body. Here is the request body I will be giving to them.

在我的项目中在客户端工作的团队要求我编写一个示例测试页面,并给他们一个工作 URL,他们可以点击并返回 200。他们还要求我提供一个示例请求正文。这是我将提供给他们的请求正文。

{
"MyApp": {
    "mAppHeader": {
        "appId": "",
        "personId": "",
        "serviceName": "",
        "clientIP": "",
        "requestTimeStamp": "",     
        "encoding": "",
        "inputDataFormat": "",
        "outputDataFormat": "",
        "environment": ""
    },
   "requestPayload": {
        "header": {
            "element": ""
        },
        "body": {
            "request": {
                "MyTestApp": {
                    "data": {
                        "AuthenticationRequestData": {
                            "appId": "",
                            "appPwd": ""
                        }
                    }
                }
            }
        }
    }
    }
}

To develop the sample page, I have no idea where to start. Please go easy on your downvotes (in case the question seems irrelevant) as I have no experience working on JSP Servlets.

要开发示例页面,我不知道从哪里开始。由于我没有处理 JSP Servlet 的经验,因此请放轻松地反对(以防问题看起来无关紧要)。

Here is what I have as of now. Its a simple login page -

这是我目前所拥有的。它是一个简单的登录页面 -

    <%@ page language="java" 
    contentType="text/html; charset=windows-1256"
    pageEncoding="windows-1256"
%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=windows-1256">
        <title>Login Page</title>
    </head>

    <body>
        <form action="TestClient">

            AppId       
            <input type="text" name="appID"/><br>       

            AppPassword
            <input type="text" name="appPwd"/>

            <input type="submit" value="submit">            

        </form>
    </body>
</html>

And this is my servlet class -

这是我的 servlet 类 -

 package com.test;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TestClient extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public TestClient() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/json");
        App app = new App();
        app.setAppID(request.getParameter("appID"));
        app.setAppPassword(request.getParameter("appPwd"));     
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

}

My App is a simple Java class that has appID, and appPassword with getters and setters, so I am not going to post that here.

我的应用程序是一个简单的 Java 类,它具有 appID 和带有 getter 和 setter 的 appPassword,所以我不打算在这里发布它。

My question is - Am I doing this right or 100% wrong? Please give me your advice.

我的问题是 - 我这样做是对还是 100% 错?请给我你的建议。

回答by Shiva Kumar

In doGet Method use Gson jarLibrary to generate JSON response

在 doGet 方法中使用 Gson jarLibrary 生成 JSON 响应

like below

像下面

Gson gson = new Gson();
HashMap map = new HashMap();

map.put("MyApp",object);

String jsonString = gson.toJson(map);
PrintWriter writer = response.getWriter();
writer.print(jsonString);

回答by suchitra nair

You can make use of Google's JSON library GSON, for parsing and forming of the JSON string.It eases your life. Look at the following link for reference. http://viralpatel.net/blogs/creating-parsing-json-data-with-java-servlet-struts-jsp-json/

您可以使用谷歌的 JSON 库 GSON 来解析和形成 JSON 字符串。它让您的生活更轻松。查看以下链接以供参考。 http://viralpatel.net/blogs/creating-parsing-json-data-with-java-servlet-struts-jsp-json/

You can also refer to the following link http://nareshkumarh.wordpress.com/2012/10/11/jquery-ajax-json-servlet-example/

您也可以参考以下链接http://nareshkumarh.wordpress.com/2012/10/11/jquery-ajax-json-servlet-example/

回答by Nick Holt

You say you want to pass some parameters from the client to the server, but show both a JSON message and then your servlet code looks as though the parameters are passed with request.

您说您想将一些参数从客户端传递到服务器,但同时显示 JSON 消息,然后您的 servlet 代码看起来好像参数是随请求传递的。

If you intend to pass JSON in the request body, the server will not automatically parse this for you, so your calls request.getParameter("appID")and request.getParameter("appPwd")won't work.

如果您打算通过JSON的请求体,则服务器将不会自动解析这个给你,所以你的电话request.getParameter("appID")request.getParameter("appPwd")将无法正常工作。

Instead you'll need to parse the body like this (based on the example message above):

相反,您需要像这样解析正文(基于上面的示例消息):

JsonObject jsonRequest = Json.createReader(request.getInputStream()).readObject();

JsonObject authenticationRequestData = jsonRequest
  .getJsonObject("MyApp")
  .getJsonObject("requestPayload")
  .getJsonObject("body")
  .getJsonObject("request")
  .getJsonObject("MyTestApp")
  .getJsonObject("data")
  .getJsonObject("AuthenticationRequestData");

App app = new App();
app.setAppID(authenticationRequestData.getJsonString("appID"));
app.setAppPassword(authenticationRequestData.getJsonString("appPwd"));     

Once your servlet has the object you want to use to create a response, you can simply generate the JSON and write it using HttpServletResponse.getWriter()like this:

一旦您的 servlet 拥有您想要用来创建响应的对象,您就可以简单地生成 JSON 并使用HttpServletResponse.getWriter()如下方式编写它:

SomeObject someObject = app.doSomething();

JsonObject jsonObject = Json.createObjectBuilder()
 .add("someValue", someObject.getSomeValue())
 .add("someOtherValue", someObject.getSomeOtherValue())
 .build();

response.setContentType("application/json");
Json.createJsonWriter(response.getWriter()).writeObject(jsonObject);

回答by Final

You could create a Java Object that is formatted in the same format and then just use the built in methods

您可以创建一个格式相同的 Java 对象,然后只使用内置方法

@WebServlet(urlPatterns = {"/BasicWebServices"})
public class BasicWebServices extends HttpServlet{

    private static final long serialVersionUID = 1L;
    private static GsonBuilder gson_builder = new GsonBuilder().serializeNulls().setDateFormat("MM/dd/yyyy");
    public BasicWebServices(){
        super();
    }
    @Override
    public void destroy(){
          super.destroy();
    }
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        doPost(request, response);
    }
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        try{
            Gson gson = BasicWebServices.gson_builder.create();
            MyObject myObject = new MyObject();
            response.getWriter().write(gson.toJson(myObject));
        }
        catch(Exception e){
            response.getWriter().write("ERROR");
        }
    }
 }

Then you just have to make your MyObject the same setup as your retrieved values. Either make an object that is setup the same, or if you can use the same java class as the one sending it if possible.

然后,您只需将 MyObject 设置为与检索到的值相同的设置。要么创建一个设置相同的对象,要么尽可能使用与发送它相同的 java 类。

For your's you would have to have a class MyApp and then have the objects mAppHeader and requestPayload

对于你的,你必须有一个 MyApp 类,然后有对象 mAppHeader 和 requestPayload

public class mAppHeader(){
    String appId = "";
    String personId = "";
    String serviceName = "";
    String clientIP = "";
    String requestTimeStamp = "";     
    String encoding = "";
    String inputDataFormat = "";
    String outputDataFormat = "";
    String environment = "";
}