简体   繁体   English

将JSONObject从java Web服务传递到JSP页面

[英]Passing JSONObject from a java webservice to a JSP page

I am trying to read a number of XML files from a variety of directories and pass this information from my java program using a web service to a web page front end. 我试图从各种目录中读取大量XML文件,并使用Web服务将这些信息从我的java程序传递到网页前端。

I have decided to do that using JSON and speficially GSON and a JSP front end. 我决定使用JSON和特殊的GSON以及JSP前端来做到这一点。 My java program did the xml read and printed to a JSON file and it was all valid JSON. 我的java程序执行了xml读取并打印到JSON文件,它都是有效的JSON。 I then took this page and tried to create a web service (my first time doing this!): 然后我拿了这个页面并尝试创建一个Web服务(我第一次这样做!):

package myweb;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;

public class WeblogicConfig
{
static DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
static String Path = "*****server path here*****";
//static String Path = "/apps/wls/dev";
static File directory = new File(Path);

static JSONObject fileObject = new JSONObject();
static JSONArray appArray = new JSONArray();
static JSONArray serverArray = new JSONArray();
static JSONArray JNDIArray = new JSONArray();

static FileWriter file;

 public WeblogicConfig()
 {
 }
 @SuppressWarnings({ "unchecked"})
 public static JSONObject setWLServerInfo() throws Exception
 {
File[] files = directory.listFiles();   
try
{   
    for (File file : files) 
    {
        if (file.isDirectory() && !file.getCanonicalPath().toString().contains("tmp") 
                && !file.getCanonicalPath().toString().contains("config_prev")) 
        {
            setWLServerInfo();
        } 
        else 
        {
            if(file.isFile() && file.getName().equals("config.xml"))
            {
                    Path = file.getCanonicalPath().toString();
                    displayManagedServerProp(directory,Path);
                    fileObject.put("Server Details",serverArray);
                    fileObject.get("Region");
            }
        }
    }
}
catch(FileNotFoundException e)
    {
        e.printStackTrace();
    }

return fileObject;
 }
 @SuppressWarnings("unchecked")
 public static void displayManagedServerProp(File file, String Path)
 {
try 
{
    File currentFile = new File(Path);
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(currentFile);
    doc.getDocumentElement().normalize();

    NodeList serverNodeList = doc.getElementsByTagName("server");   
    NodeList domainNodeList = doc.getElementsByTagName("security-configuration");
    NodeList regionNodeList = doc.getElementsByTagName("server-start");

    Node domainNode = domainNodeList.item(0);
    Element domainElement = (Element) domainNode;

    Node regionNode = regionNodeList.item(0);
    Element regionElement = (Element) regionNode;

    for (int temp2 = 0; temp2 < serverNodeList.getLength(); temp2++) 
        {
            JSONObject serverObject= new JSONObject();
            JSONObject portObject= new JSONObject();
            JSONObject addressObject= new JSONObject();
            JSONObject pathObject = new JSONObject();


            Node serverNode = serverNodeList.item(temp2);

        if(temp2 == 1) //run for first loop for each file only
            {
                pathObject.put("Domain",domainElement.getElementsByTagName("name").item(0).getTextContent());
                pathObject.put("WL Version", doc.getElementsByTagName("domain-version").item(0).getTextContent());
                pathObject.put("Path ",Path);
                pathObject.put("Region ", regionElement.getElementsByTagName("root-directory").item(0).getTextContent().substring(10,13));
            }

        if (serverNode.getNodeType() == Node.ELEMENT_NODE && serverNode.hasChildNodes()) 
        {

            Element serverElement = (Element) serverNode;
            if(serverElement.getElementsByTagName("name").item(0).getTextContent().equals("AdminServer"))
            {

            }
            else
            {
                serverObject.put("Managed Server: ", serverElement.getElementsByTagName("name").item(0).getTextContent());
                portObject.put("Listen Port: ",serverElement.getElementsByTagName("listen-port").item(0).getTextContent());
                addressObject.put("Listen Address: ", serverElement.getElementsByTagName("listen-address").item(0).getTextContent());

                serverArray.add(pathObject);
                serverArray.add(serverObject);
                serverArray.add(portObject);
                serverArray.add(addressObject);
            }
        }
        }
}   

catch (Exception e) 
    {
        e.printStackTrace();
    }
}

} }

From this I have the following JSP calling it, however I am unsure how to parse the JSON object, should I do it in the webservice before I send the object or should I continue doing it in the JSP? 从这里我有以下JSP调用它,但是我不确定如何解析JSON对象,我应该在发送对象之前在webservice中执行它还是应该继续在JSP中执行它?

<%@page import="javax.jws.WebMethod"%>
<%@page import="javax.jws.WebService"%>
<%@page import="myweb.*" %>
<%@page import="org.json.simple.*" %>
<%@page import="com.google.gson.JsonParser"%>
<%@page import="com.google.gson.JsonElement"%>
<%@page import="com.google.gson.JsonObject"%>
<%@page import="com.google.gson.*"%>
<%@page import="java.io.StringReader"%>

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Weblogic Server Config</title>
</head>
<body>
<form action="index.jsp">
<input type="hidden" value="submit" id="submit" name="submit" />
<input type="submit" value="Weblogic Config" />
<% WeblogicConfig myWeblogicConfig = new WeblogicConfig();
if(request.getParameter("submit") !=null)
{
JSONObject json = myWeblogicConfig.setWLServerInfo().toString;
JsonParser parser = new JsonParser();
JsonElement jsonTree = parser.parse(json);
    //String json = "{ \"f1\":\"Hello\",\"f2\":{\"f3:\":\"World\"}}";

if(jsonTree.isJsonObject())
{
    JsonObject jsonObject = jsonTree.getAsJsonObject();
    JsonElement f1 = jsonObject.get("Server Detail:");
    out.println("  JSONElement is:   " + json );
        //out.println("  JSONElement is:   " + f1);
}
 }
 %>
</form> 
</body>
</html>

This code creates the button but once the button is pressed a DefaultErrorHandler.javacError error occurs: 此代码创建按钮,但按下按钮后会发生DefaultErrorHandler.javacError错误:

  Stacktrace:
org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:103)
org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:366)
org.apache.jasper.compiler.JDTCompiler.generateClass(JDTCompiler.java:468)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:378)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:353)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:340)
org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:646)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:357)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)

It does work if I use the commented string, ie the basic functionality without reading from the web service. 如果我使用注释字符串,即没有从Web服务读取的基本功能,它确实有效。 I'm guessing something is going wrong in the call or assignment of the JSONObject, but not sure what? 我猜测在JSONObject的调用或赋值中出现了问题,但不确定是什么?

Any help is appreciated, initially I was working with Jackson JSON, but after some research decided to move to GSON. 任何帮助表示赞赏,最初我与杰克逊JSON合作,但经过一些研究决定转移到GSON。

**The issue came from my webservice, in my haste I delete a file type I was originally passing into the setWLServerInfo() method which now looks a little like this: **问题来自我的webservice,我急忙删除了一个我最初传入setWLServerInfo()方法的文件类型,现在看起来有点像这样:

public static JSONObject setWLServerInfo(File dir) throws Exception

I then created another method to call. 然后我创建了另一种方法来调用。

public JSONObject getJSONObject() throws Exception
 {
   JSONObject WLConfigJsonObject = setWLServerInfo(directory);
   return WLConfigJsonObject;
 } 

Now that I am successfully passing the object and currently just printing it to the screen and it seems to be valid JSON, I just need to parse it also. 现在我成功传递了对象并且当前只是将其打印到屏幕上并且它似乎是有效的JSON,我只需要解析它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM