1. 程式人生 > >Json框架的實現

Json框架的實現

一.在Spring MVC中使用@ResponseBody
基本使用
@ResponseBody用於註解Controller類中的方法。
一旦使用了這個註解,Controller中方法的返回值就應該是String,並且不再表示“返回View元件的名稱”的意義,而是返回普通的字串,最終,客戶端得到的響應也就是這個字串!
使用@ResponseBody時,推薦在Spring的配置檔案中新增驅動註解。

二.亂碼問題
一旦使用了@ResponseBody,在預設情況下,會通過StringHttpMessageConverter來處理結果,其預設的處理方式中,使用的是ISO-8859-1編碼,並不會按照UTF-8來處理,所以,會產生中文亂碼的問題!
解決方案就是在Spring的配置檔案中,在節點下,新增節點,顯式的配置StringHttpMessageConverter,並設定字元編碼,在這個類中,字元編碼是通過父類的supportedMediaType屬性來設定的
<mvc:annotation-driven>
    <mvc:message-converters>
        <bean class="org.springframework.http.converter.StringHttpMessageConverter">
            <property name="supportedMediaTypes" 
                value="text/html;charset=utf-8" />
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

三.Json(JavaScript Object Notation)是一種輕量級的資料交換格式

更加利於服務端程式“提供資料服務”,即只提供資料,而不負責資料的呈現。

四.Json的語法使用例項

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Json語法</title>
<script type="text/javascript">
function showJson() {
	var jsonData = { "name":"tomcat", 
			"age":"18" };
	alert(jsonData.age);
}

function showJson2() {
	var jsonData = {
			"status":1,
			"data":{
				"username":"tomcat",
				"age":18,
				"from":"BeiJing"
			}
	};
	alert(jsonData.data.from);
}

function showJson3() {
	var jsonData = {
		"users":[
			{ "username":"Alex", "age":18 },
			{ "username":"Billy", "age":19 }
		]
	};
	alert(jsonData.users[0].age);
}
</script>
</head>
<body>
	<li><a href="###" onclick="showJson()">show json</a></li>
	<li><a href="###" onclick="showJson2()">show json 2</a></li>
	<li><a href="###" onclick="showJson3()">show json 3</a></li>
</body>
</html>

五.Ajax和Json簡單實現登入功能例項
1.新增 spring-webmvc 3.2.8版本
新增 jackson-core 2.2.3版本
新增 jackson-annotations 2.2.3版本
新增 jackson-databind 2.2.3版本

2.web.xml配置檔案

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	version="2.5">
	<display-name>DAY10-01-Ajax-Login</display-name>
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.htm</welcome-file>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>
	<servlet>
		<servlet-name>SpringMVC</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:applicationContext.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>SpringMVC</servlet-name>
		<url-pattern>*.do</url-pattern>
	</servlet-mapping>
</web-app>

3.resources下applicationContext.xml配置檔案
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:util="http://www.springframework.org/schema/util"
	xmlns:jpa="http://www.springframework.org/schema/data/jpa"
	xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">

	<context:component-scan base-package="cn.tedu.spring"/>
	<mvc:annotation-driven>
		<mvc:message-converters>
			<bean class="org.springframework.http.converter.StringHttpMessageConverter">
				<property name="supportedMediaTypes">
					<list>
						<value>text/html;charset=utf-8</value>
						<value>application/json;charset=utf-8</value>
						<value>*/*;charset=utf-8</value>
					</list>
				</property>
			</bean>
		</mvc:message-converters>
	</mvc:annotation-driven>
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
	<property name="prefix" value="/WEB-INF/jsp/"/>
	<property name="suffix" value=".jsp"/>
</bean>
	
</beans>

4.響應結果資料類
package cn.tedu.spring.bean;

public class ResponseResult {
	private int state;
	private String message;
	private Object data;
	public ResponseResult() {
		super();
	}
	public ResponseResult(int state) {
		super();
		this.state = state;
	}
	public ResponseResult(int state, String message) {
		super();
		this.state = state;
		this.message = message;
	}
	public ResponseResult(int state, Object data) {
		super();
		this.state = state;
		this.data = data;
	}
	public ResponseResult(int state, String message, Object data) {
		super();
		this.state = state;
		this.message = message;
		this.data = data;
	}
	public int getState() {
		return state;
	}
	public void setState(int state) {
		this.state = state;
	}
	public String getMessage() {
		return message;
	}
	public void setMessage(String message) {
		this.message = message;
	}
	public Object getData() {
		return data;
	}
	public void setData(Object data) {
		this.data = data;
	}
	@Override
	public String toString() {
		String str =  "{ \"state\":" + state + ", \"message\":\"" + message + "\", \"data\":";
		if (data == null) {
			str += "null}";
		} else {
			str += "{" + data + "}}";
		}
		return str;
	}
	
}

5.使用者控制類
package cn.tedu.spring.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import cn.tedu.spring.bean.ResponseResult;

@Controller
public class UserController {
	
	@RequestMapping("handleLogin.do")
	@ResponseBody
	public String handlerLogin(String username,String password) {
		System.out.println("username=" + username);
		System.out.println("password=" + password);
		
		ResponseResult result = new ResponseResult();
		if ("tomcat".equals(username)) {
			if ("tomcat7".equals(password)) {
				result.setState(1);
			}else{
				result.setState(-2);
				result.setMessage("Password not match.");
			}
		}else {
			result = new ResponseResult(-1, "Username not exists.");
		}
		String jsonText = null;
		try {
			ObjectMapper om = new ObjectMapper();
			jsonText = om.writeValueAsString(result);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		return jsonText;
	}
}

6.webapp下index.html檔案
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Ajax Login</title>
<script type="text/javascript">
function $(id) {
	return document.getElementById(id);
}

function getXMLHttpRequest() {
	var xmlhttp = null;
	if (window.XMLHttpRequest) {
		xmlhttp = new XMLHttpRequest();
	} else {
		xmlhttp = new ActiveXObject("Microsoft.XMLHttp");
	}
	return xmlhttp;
}

function doLogin() {
	// 清除可能存在的提示資訊
	$("username_hint").innerHTML = "";
	$("password_hint").innerHTML = "";
	
	// 獲取資料
	var username = $("username").value;
	var password = $("password").value;
	
	// 檢驗資料
	if (username.length < 4 || password.length < 4) {
		return;
	}
	
	// 設定處理響應
	var xmlhttp = getXMLHttpRequest();
	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
			// 獲取響應的字串
			var result = xmlhttp.responseText;
			// var result = '{"status":1,"message":"OK"}'';
			console.log(result);
			
			// 將字串轉換為JSON物件
			var resultJson = JSON.parse(result);
			var state = resultJson.state;
			if (1 == state) {
				window.location = "user_info.html";
			} else if (state == -1) {
				$("username_hint").innerHTML = resultJson.message;
			} else {
				$("password_hint").innerHTML = resultJson.message;
			}
			
			/* if ("1" == result) {
				window.location = "user_info.html";
			} else if ("-1" == result) {
				$("username_hint").innerHTML = "使用者名稱不存在!";
			} else {
				$("password_hint").innerHTML = "密碼不正確!";
			} */
		}
	};
	
	// 提交請求
	var url = "handleLogin.do";
	var param = "username=" + username + "&password=" + password;
	xmlhttp.open("POST", url, true);
	xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
	xmlhttp.send(param);
}
</script>
</head>
<body>
	<p>
		<label>Username:</label>
		<input id="username" />
		<span id="username_hint"></span>
	</p>
	<p>
		<label>Password:</label>
		<input id="password" />
		<span id="password_hint"></span>
	</p>
	<p>
		<input type="button" value="LOGIN" onclick="doLogin()" />
	</p>
</body>
</html>


相關推薦

框架 day76 濤濤商城專案-使用json模板實現帶分類的產品規格資訊儲存及展示

淘淘商城第四天                        講師:入雲龍 1  商品描述的儲存 後臺要接收前臺頁面提交的商品資訊,及商品描述。商品資訊儲存還要儲存商品描述。 資料庫中商品資訊和商品描述是分開儲存的。 1.1    Dao層 把商品描述資訊儲存到tb_i

Java RPC 程式設計:Json-RPC 實現示例,Maven Webapp 框架

在多個伺服器程序之間的通訊,目前使用的技術一般是 RPC(Remote Procedure Call Protocol,遠端過程呼叫協議)。 使用 RPC 可以訪問遠端主機的程序服務,不需要清楚底層網路通訊機制,只需要關注服務本身即可。RPC 是目前分散式開發技術中一種常用的技術,其

Json框架實現

一.在Spring MVC中使用@ResponseBody基本使用@ResponseBody用於註解Controller類中的方法。一旦使用了這個註解,Controller中方法的返回值就應該是String,並且不再表示“返回View元件的名稱”的意義,而是返回普通的字串,最

SSM框架實現分頁,返回分頁的JSON資料

先看一下返回的JSON資料: { "pagNum": 1, "pageSize": 5, "totalRecord": 12, "totalPage": 3,

微控制器Json框架實現

背景 月初寫了一個簡單的微控制器json生成框架,目的是想為藍芽開發板封裝一套協議。加班了小一個月,終於有時間喘口氣搞搞自己的東西了….回過頭來看,發現很多不足之處,抽空進行了一些重構。主要修改了以下幾個方面: 1.修改了基本的資料結構,統一抽象為

RootFramework框架實現文件讀取和上傳以及使用JavaScript獲取fields中的值

roo 讀取 frame get .get 轉換 script 輸入 tor 1、項目中使用的相對路徑需要轉換成絕對路徑,(Python方法實現 os.path.abspath(‘path‘)) 2、choose file [locators,file_pat

.NET EF 框架-實現增刪改查

ont int string dbcontext 增刪 base set cts cti 聲明一個EF上下文對象 Model dbContext=new Model(); 添加操作(向表中插入一條數據) //聲明一個表的實體 Contact contact =new Con

Json.net實現方便的Json轉C#(dynamic動態類型)對象

bar 方便 api lba c# oid tool 可能 情況 以前需要將一段json字符串轉換為C#對象時,一般都是定義一個與之對應的實體類來接收。這樣做有一個很大的缺點,就是當字符串特別長,屬性特別多,又有嵌套時,手敲這個實體類就非常痛苦。 比如之前做的一個接收百度七

Springboot 框架實現rest接口風格

書寫規則 www ref href ring chang 規則 接口 註解 在springboot中的一些註解解釋: http://blog.csdn.net/u010399316/article/details/52913299 書寫規則可參照這個: http

[持續交付實踐] 基於 Junit 的接口自動化測試框架實現

lis ebo 命名 早已 更多 數據集 matcher 似的 相關 前言 這半個月基本都在出差以及各種公司業務上的事情,難得有空閑整理一些測試技術上的事情。周末有些空閑抓緊碼一篇填坑,持續交付/持續集成這一系列文章不僅僅是想在壇子裏和同行者做些分享,對個人的一種自我思考和

Tornado框架實現圖形驗證碼功能

tor length turn 黑客 body world 工作流 params fun 圖形驗證碼是項目開發過程中經常遇到的一個功能,在很多語言中都有對應的不同形式的圖形驗證碼功能的封裝,python 中同樣也有類似的封裝操作,通過繪制生成一個指定的圖形數據,讓前端HTM

用SSM框架實現第一個echarts的例子及一個調用百度開發者工具的例子

response char ons enc styles ping 地理編碼 nco swa   過年後的第一篇Blog,說實話年後的自己好慵懶,一直處於半睡半醒狀態 ̄□ ̄||。年後工作上用了好多新東西,像Spring Boot,Swagger,Jenkins,Maven,

Spring+Quartz框架實現定時任務(集群,分布式)

log cor alt 放置 這一 表達 mod 建數據庫 strac 1、定時任務的必要性:定時任務在應用中的重要性不言而喻,大多是應用,特別是金融應用更是離不開定時任務,能用定時任務來處理異常訂單,完成跑批,定時活動(雙11)等。在初期應用的訪問量並不是那麽大,

使用Spring框架實現遠程服務暴露與調用

java 分布式 程序員 一、前言 Spring框架提供了通過HTTP協議實現遠程調用的方式,具體是調用方使用HttpInvokerProxyFactoryBean生成一個代理對象,通過代理對象遠程通過http服務調用服務提供方法的服務並,服務提供方通過HttpInvokerServiceExpo

【轉】nose-parameterized是Python單元測試框架實現參數化的擴展

col ever sel mage 多線程 stc nbsp zed testng 原文地址: http://www.cnblogs.com/fnng/p/6580636.html   相對而言,Python下面單元測試框架要弱上少,尤其是Python自帶的unittest

Java + Selenium + TestNG + Maven 框架實現Web Automation

sta without ont window std ips run config setting 環境準備: 1. Java: Install Java jdk: Version: java 1.8 or aboveConfigure Java Environment V

Linux系統搭建 django框架實現web訪問

其中 python3 sta min python bsp 業務邏輯 配置 函數 打開終端 輸入命令 django-admin startproject demo   #其中demo是項目名稱可以自定義 在manage.py同級目錄下打開終端輸入命令啟動項目 python3

使用EF框架實現增刪改查操作

EF框架 增刪改查1:添加數據第二種方式:2:刪除數據3:修改數據4:查詢數據查詢所有的數據:查詢部分數據使用EF框架實現增刪改查操作

C#使用MVC框架實現登陸驗證

ring 數據庫訪問 傳輸數據 圖片 ont resource 使用 如果 database 步驟一:需求分析 我的目標是利用MVC框架實現簡單登陸驗證。從客戶端輸入用戶名和密碼。然後傳給數據庫驗證。如果數據庫存在此用戶名ID和密碼,則返回客戶端賬戶姓名的成功提示。否則返回

Java學習總結(隨筆)——利用JSON解析實現網絡下載

磁盤 bcd 數據 寫入 取數 mobile exce new mage 利用JSON實現網絡下載1.下載json字符串:(1)將網址封裝到URL中:URL url=new URL(“網址”);(2)利用url打開HTTP: HttpURLConnection conn=