【问题标题】:How to load a JSP page and write data on a json file simultaneously?如何同时加载 JSP 页面并在 json 文件中写入数据?
【发布时间】:2017-02-19 19:44:37
【问题描述】:

谁能给我一个 JSP 页面的示例,该页面将包含一个包含一些数据的数组变量,并且每次加载 JSP 页面时,数组中的这些数据将写入特定目录中的 json 文件中。然后我将使用另一个 html 页面处理 json 文件中的数据。

稍后,我会将我的数据库连接到 JSP 页面。但是,首先我必须在没有任何数据库的情况下处理它。所以,我的想法是什么时候更新我的数据库; JSP 页面将自动更新 json 文件(根据我的预期场景),并且每次加载 JSP 页面(或单击某个按钮)时,我每次都可以处理不同的数据集。

虽然我有点困惑..这种情况是否可能?

而且,我还尝试了一些代码,例如:-

<%-- Set the content type header with the JSP directive --%>
<%@ page contentType="application/json" %>

<%-- Set the content disposition header --%>
<%
// Returns all employees (active and terminated) as json.
response.setContentType("application/json");
response.setHeader("Content-Disposition", "inline");
%>

<%@ page language="java"%>
<%@ page import="java.sql.*"%>
<%@ page import="java.util.*"%>
<%@ page import="java.text.*"%>
<%@ page import="javax.servlet.http.*"%>


[
{"label":"item 1", "value":"item 1", "id": 1},
{"label":"item 2", "value":"item 2", "id": 2},
{"label":"item 3", "value":"item 1", "id": 3}
]

但是,我无法通过任何这些代码将数据写入 json 文件,而是在页面上显示数据。

有人可以告诉我如何实现该场景吗?

【问题讨论】:

    标签: java json jsp


    【解决方案1】:

    我已经解决了这个问题。

    假设你想在一个jsp页面中写入一些列值。只需使用... json.dumps() 和 json.load 函数。

    举个例子

    import json
    
    data = {
       'name' : 'ACME',
       'shares' : 100,
       'price' : 542.23
    }
    
    json_str = json.dumps(data)
    
    data = json.loads(json_str)
    
    # Writing JSON data
    with open('data.json', 'w') as f:
         json.dump(data, f)
    
    # Reading data back
    with open('data.json', 'r') as f:
         data = json.load(f)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-21
      • 2013-03-27
      • 2021-01-27
      相关资源
      最近更新 更多