15.5. Json 内容展示

Struts框架与JSON交互
本文介绍了一个使用Struts框架处理JSON数据的例子,包括配置文件、Action类和JSP页面的具体实现方式,并讨论了如何在JSP页面中解析并显示JSON数据。

Struts 配置文件

		
	<package name="information" extends="main" namespace="/inf">
		<action name="Information" class="com.example.action.Infomation">
			<result type="tiles">information</result>
		</action>
	</package>
		
		

Action 文件

		
package cn.netkiller.action;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;

import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonReader;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;

public class Infomation extends ActionSupport{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;


	private JsonObject jsonObject = null;
	private String jsonString = "";

	@Override
	public String execute() throws IOException {
		
		String URL = "http://inf.example.com/list/json/93/20/0.html";
		System.out.printf("%s Requeted URL is %s", this.getClass().getName(), URL);
		
		StringBuilder sb = new StringBuilder();
		URLConnection urlConn = null;
		InputStreamReader in = null;
		try {
			URL url = new URL(URL);
			urlConn = url.openConnection();
			if (urlConn != null)
				urlConn.setReadTimeout(60 * 1000);
			if (urlConn != null && urlConn.getInputStream() != null) {
				in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset());
				BufferedReader bufferedReader = new BufferedReader(in);
				if (bufferedReader != null) {
					int cp;
					while ((cp = bufferedReader.read()) != -1) {
						sb.append((char) cp);
					}
					bufferedReader.close();
				}
			}
			in.close();

			jsonString = sb.toString();

			System.out.println(jsonString);

			JsonReader reader = Json.createReader(new StringReader(jsonString));

			JsonObject jsonObject = reader.readObject();
			this.setJsonObject(jsonObject);

			reader.close();

			// System.out.println(jsonObject.size());

			/*for (int i = 0; i < jsonObject.size() - 2; i++) {
				JsonObject rowObject = jsonObject.getJsonObject(Integer.toString(i));
				// System.out.println(rowObject.toString());
				System.out.printf("%s\t%s\t%s\n", rowObject.getJsonString("id"), rowObject.getJsonString("title"),
						rowObject.getJsonString("ctime"));
			}*/
			
			

		} catch (Exception e) {
			throw new RuntimeException("Exception while calling URL:" + URL, e);
		}

		return Action.SUCCESS;
	}

	public JsonObject getJsonObject() {
		return jsonObject;
	}

	public void setJsonObject(JsonObject jsonObject) {
		this.jsonObject = jsonObject;
	}

	public String getJsonString() {
		return jsonString;
	}

	public void setJsonString(String jsonString) {
		this.jsonString = jsonString;
	}
}
		
		

JSP 文件

		
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<table>
	<c:forEach items="${jsonObject.entrySet()}" var="json"
		varStatus="status">
		<c:if test="${not status.last}">
			<tr>
				<td>${json.key+1}</td>
				<td>${json.value.getJsonString("id")}</td>
				<td>${json.value.getJsonString("title")}</td>
				<td>${json.value.getJsonString("ctime")}</td>
			</tr>
		</c:if>
	</c:forEach>
</table>
===================

<c:forEach items="${jsonObject.entrySet()}" var="json">
      ${json.value.toString()}
</c:forEach>

===========

<s:property value="jsonString" />
		
		

解决双引号问题

		
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>

<%@ taglib prefix="s" uri="/struts-tags"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>

<table>
	<c:forEach items="${jsonObject.entrySet()}" var="json"
		varStatus="status">
		<c:if test="${not status.last}">

			<c:set var="id"
				value="${fn:replace(json.value.getJsonString('id'),'\"', '')}" />
			<c:set var="title" value="${fn:replace(json.value.getJsonString('title'),'\"', '')}" />
			<c:set var="ctime"
				value="${fn:replace(json.value.getJsonString('ctime'),'\"', '')}" />
			<tr>
				<td><c:out value="${status.count}" /></td>
				<td><a href="/inf/Detail.do?id=<c:out value="${id}"/>"><c:out
							value="${title}" /></a></td>
				<td><c:out value="${ctime}" /></td>
			</tr>
		</c:if>
	</c:forEach>
</table>

<c:set var="pages" value="${jsonObject.getJsonObject('pages')}" />


<a href="${pages.first}">首页</a>
<a href="${pages.before}">上一页</a>
<a href="${pages.next}">下一页</a>
<a href="${pages.last}">尾页</a>

<span>Count: ${pages.count}, Total: ${pages.total}</span>
		
		

15.5.1. 禁止方法

			
	@JSON(serialize = false)
	public String getDatas() {
		return datas;
	}
			

使用 excludeProperties 在 Action 中排除

			
	<action name="withdraw" class="cn.netkiller.api.action.Report" method="getHistory">
		<interceptor-ref name="defaultStack" />
		<interceptor-ref name="json">
			<param name="enableSMD">true</param>
		</interceptor-ref>
		<result name="success" type="json">
			<param name="enableGZIP">true</param>
			<param name="excludeProperties">.*direction</param>
		</result>
	</action>
			
			

15.5.2. 格式化日期

@JSON(format="yyyy-MM-dd") 
public Date getDate(){ 
	return date; 
}			
			

15.5.3. 重命名变量名

@JSON(name="mypassword") 
public String getPassword() { 
	return password; 
}
			

15.5.4. org.apache.struts2.json

JSONUtil.serialize(sb.toString());
JSONUtil.deserialize(sb.toString());			




原文出处:Netkiller 系列 手札
本文作者:陈景峯
转载请与作者联系,同时请务必标明文章原始出处和作者信息及本声明。

{ "name": "lowcode-demo", "version": "1.0.10", "description": "Low-Code Engine 低代码搭建引擎 Demo 项目", "scripts": { "eslint": "eslint \"./src/**/*.{vue,html,js,jsx,ts,tsx}\"", "build": "set NODE_OPTIONS=--openssl-legacy-provider && build-scripts build && sh ./scripts/delete.sh", "build:AUI": "set NODE_OPTIONS=--max_old_space_size=8096 && build-scripts build --config build.aurora-vue.json", "prepublishOnly": "npm run build", "pub": "node ./scripts/watchdog.js && npm pub", "start": "set NODE_OPTIONS=--max_old_space_size=9896 && build-scripts start --disable-reload --port 5556", "stylelint": "stylelint \"./src/**/*.{vue,htm,html,css,sss,less,scss,sass}\" --cache --cache-location node_modules/.cache/stylelint/", "analyz": "set NODE_ENV=production && set npm_config_report=true && npm run build" }, "main": "index.js", "files": [ "build" ], "dependencies": { "@aurora/service": "~2.5.0", "@aurora/vue": "5.0.38", "@aurora/vue-cli-plugin-aurora-theme": "~3.0.13", "@aurora/vue-icon": "~5.0.0", "@wecode/welink-wlkh5-sdk": "^1.0.1", "element-ui": "2.15.12", "html2canvas": "1.4.1", "jquery": "3.6.3", "lodash": "4.17.21", "uuid": "v10.0.0", "vue": "2.6.14" }, "devDependencies": { "@alib/build-scripts": "0.1.32", "@alilc/lowcode-engine": "1.1.6", "@alilc/lowcode-engine-ext": "1.0.5", "@alilc/lowcode-plugin-components-pane": "1.0.7", "@alilc/lowcode-plugin-inject": "1.2.2", "@alilc/lowcode-plugin-schema": "1.0.2", "@alilc/lowcode-types": "1.0.3", "@alilc/lowcode-utils": "1.1.6", "@ffe/engine-vue-utils": "2.0.23", "@ffe/eslint-config-ffe": "1.0.29", "@ffe/fcore-lowcode-env": "1.1.5", "@ffe/stylelint-standard": "^1.0.10", "@types/events": "^3.0.0", "@types/react": "16.8.6", "@types/react-dom": "16.8.4", "build-plugin-moment-locales": "^0.1.0", "build-plugin-react-app": "^1.1.2", "copy-webpack-plugin": "5.1.2", "cross-env": "7.0.3", "css-loader": "3.6.0", "eslint": "8.34.0", "eslint-plugin-import": "^2.29.1", "fs-extra": "^10.0.1", "husky": "^8.0.3", "less-loader": "^7.3.0", "moment": "2.29.4", "prettier": "^2.8.8", "prop-types": "^15.5.8", "react": "16.14.0", "react-dom": "16.14.0", "screenfull": "5.2.0", "tsconfig-paths-webpack-plugin": "3.2.0", "vue-clipboard2": "0.3.3", "vue-grid-layout": "2.4.0", "vue-i18n": "8.27.2", "vue-loader": "15.9.8", "vue-router": "3.6.5", "vue-style-loader": "^4.1.3", "vue-template-compiler": "2.6.14", "vuera": "^0.2.7", "webpack-bundle-analyzer": "^4.10.2", "xlsx": "0.17.0" }, "config": {}, "license": "MIT", "repository": "git@github.com:alibaba/lowcode-demo.git" } 上面是packetjson,这个项目的依赖还能做什么优化?
06-24
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值