提问人:rickygrimes 提问时间:1/29/2014 最后编辑:rickygrimes 更新时间:4/16/2014 访问量:18409
创建一个返回 JSON 响应的简单页面
Create a simple page that returns a JSON response
问:
在我的项目中,在客户端工作的团队要求我编写一个示例测试页,并给他们一个工作 URL,他们可以点击并返回 200。他们要求我也提供一个示例请求正文。 这是我将提供给他们的请求正文。
{
"MyApp": {
"mAppHeader": {
"appId": "",
"personId": "",
"serviceName": "",
"clientIP": "",
"requestTimeStamp": "",
"encoding": "",
"inputDataFormat": "",
"outputDataFormat": "",
"environment": ""
},
"requestPayload": {
"header": {
"element": ""
},
"body": {
"request": {
"MyTestApp": {
"data": {
"AuthenticationRequestData": {
"appId": "",
"appPwd": ""
}
}
}
}
}
}
}
}
为了开发示例页面,我不知道从哪里开始。请放轻松您的反对票(以防问题似乎无关紧要),因为我没有使用 JSP Servlet 的经验。
这是我目前所拥有的。这是一个简单的登录页面 -
<%@ 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>
这是我的 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 {
}
}
我的 App 是一个简单的 Java 类,具有 appID 和 appPassword,带有 getter 和 setter,所以我不打算在这里发布。
我的问题是——我这样做是对的还是 100% 错的?请给我你的建议。
答:
在 doGet 方法中使用 Gson jarLibrary 生成 JSON 响应
如下图所示
Gson gson = new Gson();
HashMap map = new HashMap();
map.put("MyApp",object);
String jsonString = gson.toJson(map);
PrintWriter writer = response.getWriter();
writer.print(jsonString);
您可以使用 Google 的 JSON 库 GSON 来解析和形成 JSON 字符串。它减轻了你的生活。请查看以下链接以供参考。http://viralpatel.net/blogs/creating-parsing-json-data-with-java-servlet-struts-jsp-json/
您也可以参考以下链接 http://nareshkumarh.wordpress.com/2012/10/11/jquery-ajax-json-servlet-example/
您说要将一些参数从客户端传递到服务器,但同时显示 JSON 消息,然后您的 servlet 代码看起来好像这些参数是随请求传递的。
如果您打算在请求正文中传递 JSON,服务器不会自动为您解析,因此您的调用将不起作用。request.getParameter("appID")
request.getParameter("appPwd")
相反,您需要像这样解析正文(基于上面的示例消息):
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"));
一旦 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);
您可以创建一个以相同格式格式化的 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");
}
}
}
然后,您只需使 MyObject 的设置与检索到的值相同。 要么使设置的对象相同,要么如果可能的话,您可以使用与发送它的对象相同的 java 类。
对于您的,您必须有一个类 MyApp,然后具有对象 mAppHeader 和 requestPayload
public class mAppHeader(){
String appId = "";
String personId = "";
String serviceName = "";
String clientIP = "";
String requestTimeStamp = "";
String encoding = "";
String inputDataFormat = "";
String outputDataFormat = "";
String environment = "";
}
评论