1. 程式人生 > >SSM框架中實現將json串顯示到前臺頁面中

SSM框架中實現將json串顯示到前臺頁面中

首先在Controller中的方法中定義如下如所示:

JSONObject json = new JSONObject();
	json.put("vcode", Vcode);
	json.put("username", "username");
	json.put("password", "password");
	HtmlUtil.writerJson(response, json);

當然,這裡引用了JSONObject,需要一個jar包,下載地址

然後就是公共類HtmlUtil

package com.jh5bframework.common.utils;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONException;
import com.jh5bframework.common.json.JSONUtil;

public class HtmlUtil {
	
	/**
	 * 功能:輸出json格式
	 * @param response
	 * @param jsonStr
	 * @throws Exception
	 */
	public static void writerJson(HttpServletResponse response,String jsonStr) {
			writer(response,jsonStr);
	}
	
	public static void writerJson(HttpServletResponse response,Object object){
			try {
				response.setContentType("application/json");
				writer(response,JSONUtil.toJSONString(object));
				
			} catch (JSONException e) {
				e.printStackTrace();
			}
	}
	
	/**
	 * 功能:輸出HTML程式碼
	 * @param response
	 * @param htmlStr
	 * @throws Exception
	 */
	public static void writerHtml(HttpServletResponse response,String htmlStr) {
		writer(response,htmlStr);
	}
	
	private static void writer(HttpServletResponse response,String str){
		try {
			StringBuffer result = new StringBuffer();
			//設定頁面不快取
			response.setHeader("Pragma", "No-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setContentType("text/html; charset=utf-8");
			PrintWriter out= null;
			out = response.getWriter();
			out.print(str);
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	} 
}
然後是JSONUtil公共類:
package com.jh5bframework.common.json;

import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONString;

/** 
 * JSON工具類,反射的方式轉換整個物件
 * @author 
 *
 */
public class JSONUtil{

    private static JSONUtil instance = null;
    
    public JSONUtil(){
    	
    }
    
    /** 
     * 代理類時做的檢查.返回應該檢查的物件.
     * @param bean
     * @return
     */
    protected Object proxyCheck(Object bean){
        return bean;
    }

    static public String toJSONString(Object obj) throws JSONException{
        return toJSONString(obj, false);
    }
    
    static public String toJSONString(Object obj, boolean useClassConvert) throws JSONException{
        if(instance == null)
            instance = new JSONUtil();
        return instance.getJSONObject(obj, useClassConvert).toString();
    }

    @SuppressWarnings("unchecked")
	private String getJSONArray(Object arrayObj, boolean useClassConvert) throws JSONException{
        
        if(arrayObj == null)
            return "null";
        
        arrayObj = proxyCheck(arrayObj);
        
        JSONArray jSONArray = new JSONArray();
        if(arrayObj instanceof Collection){
            Iterator iterator = ((Collection)arrayObj).iterator();
            while(iterator.hasNext()){
                Object rowObj = iterator.next();
                if(rowObj == null)
                    jSONArray.put(new JSONStringObject(null));
                else if(rowObj.getClass().isArray() || rowObj instanceof Collection)
                    jSONArray.put(getJSONArray(rowObj, useClassConvert));
                else
                    jSONArray.put(getJSONObject(rowObj, useClassConvert));
            }
        }
        if(arrayObj.getClass().isArray()){
            int arrayLength = Array.getLength(arrayObj);
            for(int i = 0; i < arrayLength; i ++){
                Object rowObj = Array.get(arrayObj, i);
                if(rowObj == null)
                    jSONArray.put(new JSONStringObject(null));
                else if(rowObj.getClass().isArray() || rowObj instanceof Collection)
                    jSONArray.put(getJSONArray(rowObj, useClassConvert));
                else
                    jSONArray.put(getJSONObject(rowObj, useClassConvert));
            }
        }
        return jSONArray.toString();
    }

    @SuppressWarnings("unchecked")
	JSONStringObject getJSONObject(Object value, boolean useClassConvert) throws JSONException{

        //處理原始型別

        if (value == null){
            return new JSONStringObject("null");
        }
        value = proxyCheck(value);
        if (value instanceof JSONString){
            Object o;
            try{
                o = ((JSONString)value).toJSONString();
            } catch (Exception e){
                throw new JSONException(e);
            }
            throw new JSONException("Bad value from toJSONString: " + o);
        }
        if (value instanceof Number){
            return new JSONStringObject(JSONObject.numberToString((Number) value));
        }
        if (value instanceof Boolean || value instanceof JSONObject ||
                value instanceof JSONArray){
            return new JSONStringObject(value.toString());
        }
        if (value instanceof String)
            return new JSONStringObject(JSONObject.quote(value.toString()));
        if (value instanceof Map){
            
            JSONObject jSONObject = new JSONObject();

            Iterator iterator = ((Map)value).keySet().iterator();
            while(iterator.hasNext()){
                String key = iterator.next().toString();
                Object valueObj = ((Map)value).get(key);
                jSONObject.put(key, getJSONObject(valueObj, useClassConvert));
            }
            return new JSONStringObject(jSONObject.toString());
        }

        //class

        if(value instanceof Class)
            return new JSONStringObject(JSONObject.quote(((Class)value).getSimpleName()));
        
        //陣列

        if (value instanceof Collection || value.getClass().isArray()){
            return new JSONStringObject(getJSONArray(proxyCheck(value), useClassConvert));
        }

        return reflectObject(value, useClassConvert);
    }//value.equals(null)


    @SuppressWarnings("unchecked")
	private JSONStringObject reflectObject(Object bean, boolean useClassConvert){
        JSONObject jSONObject = new JSONObject();

        Class klass = bean.getClass();
        Method[] methods = klass.getMethods();
        for (int i = 0; i < methods.length; i += 1){
            try{
                Method method = methods[i];
                String name = method.getName();
                String key = "";
                if (name.startsWith("get")){
                    key = name.substring(3);
                } else if (name.startsWith("is")){
                    key = name.substring(2);
                }
                if (key.length() > 0 &&
                        Character.isUpperCase(key.charAt(0)) &&
                        method.getParameterTypes().length == 0){
                    if (key.length() == 1){
                        key = key.toLowerCase();
                    } else if (!Character.isUpperCase(key.charAt(1))){
                        key = key.substring(0, 1).toLowerCase() +
                            key.substring(1);
                    }
                    Object elementObj = method.invoke(bean, null);
                    if(!useClassConvert && elementObj instanceof Class)
                        continue;

                    jSONObject.put(key, getJSONObject(elementObj, useClassConvert));
                }
            } catch (Exception e){
                /**//* forget about it */
            }
        }
        return new JSONStringObject(jSONObject.toString());
    }
}


最後是JSONStringObject公共類:
package com.jh5bframework.common.json;

import org.json.JSONString;

public class JSONStringObject implements JSONString{

    private String jsonString = null;
    
    public JSONStringObject(String jsonString){
        this.jsonString = jsonString;
    }

    @Override
    public String toString(){
        return jsonString;
    }

    public String toJSONString(){
        return jsonString;
    }
}



相關推薦

SSM框架實現json顯示前臺頁面

首先在Controller中的方法中定義如下如所示: JSONObject json = new JSONObject(); json.put("vcode", Vcode); json.put("username", "username"); json.put("

SSM框架整合(實現從數據庫到頁面展示)

patch beans response 由於 spring容器 void 不用 html show         SSM框架整合(實現從數據庫到頁面展示)     首先創建一個spring-web項目,然後需要配置環境dtd文件的引入,環境配置,jar包引入。 首先讓我

使用idea搭建SpringBoot+Spring jpa專案(實現獲取資料庫資料顯示頁面

搭建SpringBoot準備 javaweb基礎 idea使用基礎 maven使用基礎 開始搭建SpringBoot專案 建立springboot 設定Group、Artifact、Packaging 選擇web及SpringBoot版本 配置app

Servlet如何json物件轉化為Java的自定義物件

前段ajax$("#form1").submit(function() { var cname = $("input[name=cname]").val(); var sup_compan

json匯入poi xls模板其用io寫到指定位置資料夾

這也算是我昨天一天時間的學習成果吧,初入java,大神見笑。 String templatePath = request.getSession().getServletContext().getRealPath("/") + "WEB-INF" + File.separator + "lib"

實現點選上傳檔案檔名稱顯示在text

先上程式碼 html <input type="file" id="file"/> <input type="text" placeholder="file name" id="ai

html實現數據的顯示和隱藏

func 隱藏 obj else content cli solid head utf Author: YangQingQing <!DOCTYPE html><html><meta http-equiv="Content-Type" co

java SSM框架實現數據EXCEL導出下載功能

java 功能需求最近公司項目有個需求,是導出列表中的數據並下載。如下圖所示的列表數據,並且該數據不是一個表裏的數據。 -------------------------------------------------華麗的分割線----------------------------------------

java怎麽json形式的字符的key的value取出來呢

怎麽 ati parse 取出 () gets out get seo public static void main(String[] args){ String s = "{‘價格‘:‘_66k_‘}"; JSONObject jsonObject = JS

json轉換為物件時候,出現欄位和屬性不匹配問題

報錯資訊如下: org.codehaus.jackson.map.exc.UnrecognizedPropertyException: Unrecognized field "HPYS" (Class com.traffic.entity.BusBaseInfo), not marked

SSM框架實現更新功能

  做修改用我這種方式還有點複雜,其中的邏輯是這樣的: 1.第一步我總是從xml中寫sql語句開始,這裡用了兩個語句,一是更新語句,一個是根據id查詢語句,後面會用到的。 2. 然後就是Mapper.java,DaoI,DaoImp,ServiceI,ServiceImp層。 3.然後邏輯是這樣的,用i

詳細記錄->使用Maven+SSM框架實現單表簡單的增刪改查

       話不多說,ssm框架整合小列子,這次記錄一個單表增刪改查的ssm例子,所以才手寫mapper,平時我都是用逆向工程自動生成mapper,簡單方便。 需要了解逆向工程請看:https://blog.csdn.net/Destiny_stri

SSM框架+thymeleaf實現基本的增刪改查

前言 本文使用了SSM框架、thymeleaf和jquery實現了基本的增刪改查。   名詞解釋 SSM框架:springMVC、spring、mybatis thymeleaf:一個與Velocity、FreeMarker類似的模板引擎 jquery:一個快速、簡潔的JavaScrip

ssm框架基本實現配置

dao層與pojo層使用generatorSqlmapCustom逆向工程自動生存的程式碼 1.db.properties的配置 jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/springm

在PHP實現資料庫的資料在頁面表格呈現

一、實現思路:(匯入bootstrap的css,js以及jquery以後) 1.連線資料庫,執行sql查詢語句; 2.檢測資料庫是否連線成功,sql語句是否執行成功; 3.sql語句成功執行後獲得mysqli_result物件(只有執行增、刪、改查詢成功後才會返回mysqli_resul

SSM框架整合實現增刪改查(簡單的實現

SSM框架整合實現增刪改查 檔案結構 POM檔案 <packaging>war</packaging> <!-- 處理亂碼 --> <properties> <!-- 設定專案字符集 -->

SSM框架+WebSocket實現網頁聊天(Spring+SpringMVC+MyBatis+WebSocket)

建站不止於增刪改查,還有很多很有魅力的地方。對於通訊聊天這塊已經青睞好久了,前段時間在做的j2ee專案運用到Spring+SpringMVC+MyBatis的框架集合,是關於一個社交平臺的網站,類似於facebook,twitter,微博等。在做完基本的CURD(例如評論模組

python3json資料轉換到excel

#!/usr/bin/env python# coding=utf-8# json轉換為excel import xlrdimport jsonimport osfrom openpyxl import Workbookwb = Workbook()ws = wb.active cols = []def js

SSM框架實現登入註冊

基本配置:jdk1.8   tomcat 8  MyEclipse 先打好地基:                    spring配置檔案 application.xml: <?xml version="1.0" encoding="UTF-8"?&g

RapidJson(V1.1.0)的Value簡單操作(拼接json,存取檔案json,解析json)

#include <rapidjson/document.h> #include <rapidjson/stringbuffer.h> #include <rapidjson/pointer.h> #include <rapidjson/writer.h