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>



猜你喜欢

转载自blog.csdn.net/linsa_pursuer/article/details/79117903
今日推荐