Create a simple page that returns a JSON response

The team that works on the client side in my project asked me to write a sample test page and give them a working URL that they can put in and return 200. They asked me to also provide a sample request body. Here is the request body that I will give them .

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

To create a sample page, I have no idea where to start. Goodbye, please, on your downvotes (if the question seems inappropriate), since I have no experience with JSP servlets.

Here is what I have at the moment. His simple login page is

  <%@ 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 -

  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 application is a simple Java class with appID and appPassword with getters and setters, so I will not post it here.

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

+6
source share
4 answers

You can create a Java object that is formatted in the same format, and then just use the built-in methods

 @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 need to make MyObject the same setting as your recovered values. Either create an object that is configured the same way, or if you can use the same java class as the one that sends it, if possible.

For you, you must have the MyApp class, and then there are mAppHeader and requestPayload objects

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

In the doGet method, use the Gson jarLibrary to generate a JSON response

as 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); 
+1
source

You can use the Google JSON GSON library to parse and form a JSON string. It makes your life easier. Have a look at the following link for reference. 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/

0
source

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

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

Instead, you will need to parse the body this way (based on the above example):

 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 that you want to use to create the response, you can simply generate JSON and write it with HttpServletResponse.getWriter() as follows:

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

All Articles