【问题标题】:Set value in one servlet and access it from different servlet在一个 servlet 中设置值并从不同的 servlet 访问它
【发布时间】:2016-07-21 10:49:52
【问题描述】:

我有一个 servletOne 在本地 TOMCAT 中运行,而 servletTwo 部署在远程位置的不同 TOMCAT 中。我想访问在 servletTwo 中设置的值(Array/ArrayList)。我不知道该怎么做。我看过不同的例子,但没有任何效果。这就是我到目前为止所拥有的。这是我的doPost

 doGet(req, resp);

//doGet
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
 ArrayList al = new ArrayList();

    al.add("valOne");
    al.add("valTwo");
    //Should I use this
    PrintWriter out = resp.getWriter();
    out.println(al);
    //Or should I use this
    req.setAttribute("ArrayList", al);
}

现在我想从 servletOne 访问数组列表

在 servletOne 我有,

try
    {
        URL url = new URL("http://myhost:8080/servletTest");
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);

        BufferedReader in =
                new BufferedReader(new InputStreamReader(conn.getInputStream()));

        String response;
        while ((response = in.readLine()) != null)
        {
            System.out.println(response);

        }
        in.close();
    }
    catch (MalformedURLException ex)
    {
        // handle this exception
    }
    catch (IOException ex)
    {
        // handle this exception
    }

 } 

我不认为它会起作用,因为我从 servletOne 获取字符串而不是数组的值。任何帮助将不胜感激。 提前致谢。

【问题讨论】:

    标签: java servlets tomcat7


    【解决方案1】:

    您可以使用 JSON:

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
     ArrayList al = new ArrayList();
    
        al.add("valOne");
        al.add("valTwo");
        //Should I use this
        PrintWriter out = resp.getWriter();
        out.println(al);
        //Or should I use this
       // req.setAttribute("ArrayList", al);
    
    //create al object to JSOn and send it another servlet on another tomcat
    
    
      Gson gson=new Gson();
    
      String jsonlist=gson.toJson(al)
    
      String url = "http://example.com/query?q=" + URLEncoder.encode(jsonlist,    "UTF-8");
    
    }
    

    【讨论】:

    • 在 JAVA 中可以使用 encodeURIComponent 和 JSON.stringify 吗?
    • 可以在java中使用JSON库 JSONObject obj = ... String jsonString = obj.toString();
    • 能否请您替换,encodeURIComponent(JSON.stringify(al));使用您提出的 java 解决方案。谢谢
    • 编辑解决方案请参考,希望对你有用。
    猜你喜欢
    • 1970-01-01
    • 2015-08-12
    • 2018-03-12
    • 2016-09-23
    • 2012-10-31
    • 1970-01-01
    • 2012-05-27
    • 2012-08-19
    • 1970-01-01
    相关资源
    最近更新 更多