简体   繁体   English

如何加载JSP页面并同时在json文件上写入数据?

[英]How to load a JSP page and write data on a json file simultaneously?

Could someone give me an example of a JSP page which will contain an array variable with some data and every time when the JSP page will be loaded, those data in the array will be written in a json file in a specific directory. 有人可以给我一个JSP页面的示例,该示例包含一个包含一些数据的数组变量,并且每次加载JSP页面时,数组中的那些数据都将写入特定目录下的json文件中。 Then I will process with the data in the json file using another html page. 然后,我将使用另一个html页面处理json文件中的数据。

Later, I would make a connection with my DB to the JSP page. 稍后,我将与数据库连接到JSP页面。 But, firstly i have to handle it without any database. 但是,首先我必须在没有任何数据库的情况下进行处理。 So, the idea is when my DB will be updated; 因此,想法是何时更新我的​​数据库; JSP page will automatically update the json file (As per my expected scenario) and with every load of the JSP page (or clicking some button), I could process with different set of data every time. JSP页面将自动更新json文件(根据我的预期情况),并且随着JSP页面的每次加载(或单击某些按钮),我每次都可以使用不同的数据集进行处理。

I am little bit confused though.. this kind of scenario is possible or not? 我有点困惑..这种情况是否可能?

And, I also tried some codes like:- 而且,我还尝试了一些代码,例如:

<%-- 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}
]

But, I couldn't able to write data in a json file through any of these codes rather it shows data on the page. 但是,我无法通过任何这些代码在json文件中写入数据,而是在页面上显示数据。

Could someone give me any idea that how can I implement the scenario?? 有人可以告诉我如何实施该方案吗?

I have solved the problem . 我已经解决了问题。

Suppose you want to write some column values in a jsp page. 假设您要在jsp页面中写入一些列值。 Simply use... json.dumps() and json.load function. 只需使用... json.dumps()和json.load函数。

Here's the exapmple 这是个例子

 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) 

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

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