简体   繁体   中英

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.

I have decided to do that using JSON and speficially GSON and a JSP front end. My java program did the xml read and printed to a JSON file and it was all valid JSON. I then took this page and tried to create a web service (my first time doing this!):

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?

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

  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. I'm guessing something is going wrong in the call or assignment of the JSONObject, but not sure what?

Any help is appreciated, initially I was working with Jackson JSON, but after some research decided to move to 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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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