JSON
什么是JSON
JSON是一种轻量级的数据交换格式
JSON跟XML相比的话,算是一种轻量级的数据交换格式,
数据交换指的是客户端和服务器之间业务数据的传递格式。
JSON在JavaScript中的使用
JSON的定义
// json的定义
var jsonObj = {
"key1":12,
"key2":"abc",
"key3":true,
"key4":[11,"qwe",false],
"key5":{
"key5_1":551,
"key5_2":"asd"
},
"key6":[{
"key6_1_1":6611,
"key6_1_2":"key6_1_2_value"
},{
"key6_2_1":6621,
"key6_2_2":"key6_2_2_value"
}]
};
JSON的访问
- json 本身是一个对象。
- json 中的 key 我们可以理解为是对象中的一个属性。
- json 中的 key 访问就跟访问对象的属性一样: json对象.key
jsonObj.key1
//普通数组
alert(jsonObj.key4[0]);
//json里面的json对象
alert(jsonObj.key5.key5_1);
//json对象数组
alert(jsonObj.key6[0].key6_1_1)
JSON的两个常用方法
json有两种存在形式
// json对象转字符串
var jsonObjString = JSON.stringify(jsonObj);
// json字符串转json对象
var jsonObj = JSON.parse(jsonObjString);
Gson
JSON和JavaBean的互转
@Test
public void test1(){
Person person = new Person(1,"admin");
Gson gson = new Gson();
//toJson()可以把java对象转换成json字符串
String jsonString = gson.toJson(person);
System.out.println(jsonString);
//fromJson()把json字符串转换回Java对象,参数1json字符串,参数2是对象类型
Person person1 = gson.fromJson(jsonString, Person.class);
System.out.println(person1);
}
JSON和List的互转
@Test
public void test2(){
List<Person> personList = new ArrayList<>();
personList.add(new Person(1,"admin"));
personList.add(new Person(2,"qweqwe"));
Gson gson = new Gson();
//把List转换为Json字符串
String personJson = gson.toJson(personList);
System.out.println(personList);
//把Json字符串转换为List
List<Person> jsonPersonList = gson.fromJson(personJson, new TypeToken<ArrayList<Person>>(){}.getType());
System.out.println(jsonPersonList.get(0));
}
JSON和Map的互转
@Test
public void test3(){
Map<Integer,Person> personMap = new HashMap<>();
personMap.put(1, new Person(1,"admin"));
personMap.put(2, new Person(2,"qweqwe"));
Gson gson = new Gson();
//把Map转换为Json字符串
String personJson = gson.toJson(personMap);
System.out.println(personJson);
//把Json转换为Map字符串
Map<Integer,Person> jsonPersonMap = gson.fromJson(personJson,new TypeToken<Map<Integer,Person>>(){}.getType());
System.out.println(jsonPersonMap.get(1));
}
Jackson
/**
* 提取Jackson工具类
*/
public class JsonUtils {
public static String getJson(Object o){
return getJson(o,"yyyy-MM-dd HH:mm:ss");
}
/**
* 取消timestamps形式 , 自定义时间格式
* @param o
* @param df
* @return
*/
public static String getJson(Object o, String df) {
ObjectMapper mapper = new ObjectMapper();
//不使用时间戳的方式
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
//自定义日期的格式
SimpleDateFormat sdf = new SimpleDateFormat(df);
mapper.setDateFormat(sdf);
try {
return mapper.writeValueAsString(o);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
}
springmvc-servlet.xml
<!--解决Json乱码问题-->
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8"/>
</bean>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
<property name="failOnEmptyBeans" value="false"/>
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
AJAX
什么是AJAX请求
AJAX就是异步JavaScript和XML,是一种浏览器通过js异步发起请求,局部更新页面的技术。
原生AJAX示例
ajax.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="pragma" content="no-cache" />
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="Expires" content="0" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
//在这里使用JavaScript发起Ajax请求,访问服务器AjaxServlet中JavaScriptAjax
function ajaxRequest() {
// 1、我们首先要创建XMLHttpRequest
var xmlhttprequest = new XMLHttpRequest();
// 2、调用open方法设置请求参数
xmlhttprequest.open("GET","http://localhost:8080/json_ajax_i18n/ajaxServlet?action=javaScriptAjax",true);
// 4、在send方法前绑定onreadystatechange事件,处理请求完成后的操作。
xmlhttprequest.onreadystatechange = function () {
//满足以下两个条件,表示数据已经传回来了
if (xmlhttprequest.readyState == 4 && xmlhttprequest.status == 200) {
var jsonObj = JSON.parse(xmlhttprequest.responseText);
document.getElementById("div01").innerHTML="编号:"+jsonObj.id+" 姓名:"+jsonObj.name
}
}
// 3、调用send方法发送请求
xmlhttprequest.send();
}
</script>
</head>
<body>
<button onclick="ajaxRequest()">ajax request</button>
<div id="div01">
</div>
</body>
</html>
AjaxServlet.java
public class AjaxServlet extends BaseServlet{
protected void javaScriptAjax(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Person person = new Person(1,"admin");
//将对象转换为json字符串
Gson gson = new Gson();
String personJson = gson.toJson(person);
//服务器将数据传给客户端
resp.getWriter().write(personJson);
}
}
jQyery中的AJAX请求
$.ajax方法
参数 | 作用 |
---|---|
url | 表示请求的地址 |
type | 表示请求的类型 GET 或 POST 请求 |
data | 表示发送给服务器的数据,有两种格式,一:name=value&name=value;二:{key:value}(会自动转换为第一种格式) |
success | 请求成功,响应的回调函数 |
dataType | 响应的数据类型,常用的数据类型有:text 表示纯文本、xml 表示 xml 数据、json 表示 json 对象 |
// $.ajax方法
$("#ajaxBtn").click(function(){
$.ajax({
url:"http://localhost:8080/json_ajax_i18n/ajaxServlet",
data:"action=jQueryAjax",
type:"GET",
success:function (data) {
$("#msg").html("编号:"+data.id+"姓名:"+data.name);
},
dataType:"json"
})
});
$.get、$.post方法
参数 | 作用 |
---|---|
url | 请求的地址 |
type | 返回的数据类型 |
data | 表示发送给服务器的数据 |
callback | 成功的回调函数 |
// ajax--get请求
$("#getBtn").click(function(){
// get请求
$.get("http://localhost:8080/json_ajax_i18n/ajaxServlet","action=jQueryGet",function (data) {
$("#msg").html("编号:"+data.id+"姓名:"+data.name);
},"json");
});
// ajax--post请求
$("#postBtn").click(function(){
// post请求
$.get("http://localhost:8080/json_ajax_i18n/ajaxServlet","action=jQueryPost",function (data) {
$("#msg").html("编号:"+data.id+"姓名:"+data.name);
},"json");
});
$.getJSON方法
参数 | 作用 |
---|---|
url | 请求的地址 |
data | 发送给服务器的数据 |
callback | 成功的回调函数 |
表单序列化serialize()
// ajax请求
$("#submit").click(function(){
// 把参数序列化,在action后面追加,服务器可直接根据标签里的name属性获取
alert($("#form01").serialize())
$.getJSON("http://localhost:8080/json_ajax_i18n/ajaxServlet","action=jQuerySerialize&"+$("#form01").serialize(),function (data) {
$("#msg").html("serialize编号:"+data.id+"姓名:"+data.name);
});
});
i18n
什么是i18n国际化
国际化(Internationalization)指的是同一个网站可以支持多种不同的语言,以方便不同国家,不同语种的用户访问,18N是国际化的简写。
国际化资源测试
配置i18n_en_US.properties、
username=username
password=password
sex=sex
age=age
regist=regist
boy=boy
email=email
girl=girl
reset=reset
submit=submit
配置i18n_zh_CN.properties
username= 用户名
password= 密码
sex= 性别
age= 年龄
regist= 注册
boy= 男
girl= 女
email= 邮箱
reset= 重置
submit=
测试代码
@Test
public void testI18n(){
Locale locale = Locale.CHINA;
//通过指定的basename和locale对象,读取相应的配置文件
ResourceBundle bundle = ResourceBundle.getBundle("i18n", locale);
System.out.println("username:"+bundle.getString("username"));
System.out.println("password:"+bundle.getString("password"));
}
通过请求头实现国际化
<%
// 从请求头中获取 Locale 信息(语言)
// Locale locale = request.getLocale();
// System.out.println(locale);
// 获取读取包(根据 指定的 baseName 和 Locale 读取 语言信息)
// ResourceBundle i18n = ResourceBundle.getBundle("i18n", locale);
%>
手动切换语言类型
<body>
<%
Locale locale = null;
String country = request.getParameter("country");
if ("cn".equals(country)) {
locale = Locale.CHINA;
}else if("usa".equals(country)) {
locale = Locale.US;
}else {
locale = request.getLocale();
}
//获取读取包(根据指定的baseName和Locale读取语言信息)
ResourceBundle i18n = ResourceBundle.getBundle("i18n", locale);
%>
<a href="i18n.jsp?country=cn">中文</a>|
<a href="i18n.jsp?country=usa">english</a>
<center>
<h1><%= i18n.getString("regist")%></h1>
<table>
<form>
<tr>
<td><%= i18n.getString("username")%></td>
<td><input name="username" type="text" /></td>
</tr>
<tr>
<td><%= i18n.getString("password")%></td>
<td><input type="password" /></td>
</tr>
<tr>
<td><%= i18n.getString("sex")%></td>
<td><input type="radio" /><%=i18n.getString("boy")%><input type="radio" /><%=i18n.getString("girl")%></td>
</tr>
<tr>
<td><%= i18n.getString("email")%></td>
<td><input type="text" /></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="reset" value="<%=i18n.getString("reset")%>" />
<input type="submit" value="<%=i18n.getString("submit")%>" /></td>
</tr>
</form>
</table>
<br /> <br /> <br /> <br />
</center>
国际化测试:
<br /> 1、访问页面,通过浏览器设置,请求头信息确定国际化语言。
<br /> 2、通过左上角,手动切换语言
</body>
JSTL 标签库实现国际化
<body>
<%--1. 使用标签设置Locale信息--%>
<fmt:setLocale value="${param.locale}"/>
<%--2. 使用标签设置baseName--%>
<fmt:setBundle basename="i18n"/>
<a href="i18n_fmt.jsp?locale=zh_CN">中文</a>|
<a href="i18n_fmt.jsp?locale=en_US">english</a>
<center>
<%--3. 输出指定key的国际化信息--%>
<h1><fmt:message key="regist"/> </h1>
<table>
<form>
<tr>
<td><fmt:message key="username"/></td>
<td><input name="username" type="text" /></td>
</tr>
<tr>
<td><fmt:message key="password"/></td>
<td><input type="password" /></td>
</tr>
<tr>
<td><fmt:message key="sex"/></td>
<td><input type="radio" /><fmt:message key="boy"/><input type="radio" /><fmt:message key="girl"/></td>
</tr>
<tr>
<td><fmt:message key="email"/></td>
<td><input type="text" /></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="reset" value="<fmt:message key="reset"/>" />
<input type="submit" value="<fmt:message key="submit"/>" /></td>
</tr>
</form>
</table>
<br /> <br /> <br /> <br />
</center>
</body>