JSON、AJAX、I18N
JSON
-
什么是JSON
JSON是一种轻量级的数据交换格式,数据交换指的是客户端和服务器之间业务数据的传递
-
JSON在JS中的使用方法
JSON对象转字符串调用 JSON.stringify()
JSON格式字符串转JSON对象调用 JSON.parse()
// json的定义 var jsonObj = { "key1":123, "key2":"Tom", "key3":[11,"arr",false], "key4":{ "key4_1":441, "key4_2":"key4_2" }, "key5":[ { "key5_1_1":5511, "key5_1_2":"key5_1_2" },{ "key5_2_1":5521, "key5_2_2":"key5_2_2" } ] }; // json的访问 alert(jsonObj.key1); alert(jsonObj.key2); alert(jsonObj.key3[0]); alert(jsonObj.key4.key4_1); alert(jsonObj.key4.key4_2); alert(jsonObj.key5[0].key5_1_1); alert(jsonObj.key5[0].key5_1_2); alert(jsonObj.key5[1].key5_2_1); alert(jsonObj.key5[1].key5_2_2); // json对象转字符串 var jsonStr = JSON.stringify(jsonObj); alert(jsonStr); // json字符串转json对象 var jsonObj2 = JSON.parse(jsonStr); alert(jsonObj2.key1);
-
JSON在Java中的使用方法
要在Java中使用JSON需要导入谷歌的Gson的jar包
- 需要new 一个Gson实例
- 转换成json调用gson.toJson()
- json转换成对象调用gson.fromJson()
@Test public void test1(){ //JavaBean与JSON的转换 Person person = new Person(1,"Tom"); Gson gson = new Gson(); String s = gson.toJson(person); System.out.println(s);//{"id":1,"name":"Tom"} Person person1 = gson.fromJson(s, Person.class); System.out.println(person1);//Person{id=1, name='Tom'} } @Test public void test2(){ //List与JSON的转换 List<Person> list = new ArrayList<>(); Person person1 = new Person(1,"Tom"); Person person2 = new Person(2,"Jerry"); list.add(person1); list.add(person2); Gson gson = new Gson(); String s = gson.toJson(list); System.out.println(s); // [{"id":1,"name":"Tom"},{"id":2,"name":"Jerry"}] //第二个参数要创建一个对象继承TypeToken List<Person> list2 = gson.fromJson(s, new JsonList().getType()); System.out.println(list2); // [Person{id=1, name='Tom'}, Person{id=2, name='Jerry'}] } @Test public void test3(){ //Map与JSON的转换 Map<Integer,Person> map = new HashMap<>(); map.put(1,new Person(1,"Tom")); map.put(2,new Person(2,"Jerry")); Gson gson = new Gson(); String s = gson.toJson(map); System.out.println(s);//{"1":{"id":1,"name":"Tom"},"2":{"id":2,"name":"Jerry"}} //也可以使用匿名内部类 Object o = gson.fromJson(s, new TypeToken<Map<Integer, Person>>() {}.getType()); System.out.println(o);//{1=Person{id=1, name='Tom'}, 2=Person{id=2, name='Jerry'}} }
创建一个类继承于TypeToken的方法如下
public class JsonList extends TypeToken<List<Person>> { }
AJAX
-
什么是AJAX
ajax是一种浏览器异步发起请求,局部更新页面的技术
-
JavaScript原生Ajax请求
原生的Ajax请求分四步
- 首先要创建XMLHttpRequest对象
- 调用open方法设置请求参数
- 调用send方法发送请求
- 再send方法前绑定onreadystatechange事件,处理请求完成后的操作
创建一个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"> function ajaxRequest() { // 1、首先要创建XMLHttpRequest var xhr = new XMLHttpRequest(); // 2、调用open方法设置请求参数-true代表异步 //第一个参数为请求方法,第二个参数为请求路径,第三个参数为是否异步 xhr.open("GET","http://localhost:8080/Json_AJAX_i18n/ajaxServlet?function=scriptGet",true); // 4、在send方法前绑定onreadystatechange事件,处理请求完成后的操作。 xhr.onreadystatechange = function (){ //判断请求是否完成及成功 if(xhr.status == 200 && xhr.readyState == 4){ document.getElementById("div01").innerText = xhr.responseText; } } // 3、调用send方法发送请求 xhr.send(); } </script> </head> <body> <button onclick="ajaxRequest()">ajax request</button> <div id="div01"> </div> </body> </html>
创建一个servlet程序用于处理请求
protected void scriptGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("ajaxRequest方法进来了"); Person person = new Person(1,"Tom"); Gson gson = new Gson(); String jsonStr = gson.toJson(person); resp.getWriter().write(jsonStr); }
-
JQuery发送ajax请求
使用JavaScript发送ajax请求非常麻烦,jQuery为我们包装好了几个方法供我们使用
分别是:
- .ajax : 5个重要参数
- url:请求地址
- data:请求参数
- type:请求类型
- success:请求成功后执行
- dataType:返回的参数类型
- .get :在.ajax上又包装了一次,省略了type参数
- .post :与get一样,只是type参数默认为post
- .getJSON:在get基础上再次包装,省略了dataType参数
- .serialize:用于表单,拼接所有的表单项以key=value&key=value方式
通过代码来看一下如何使用
<!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" src="script/jquery-1.7.2.js"></script> <script type="text/javascript"> $(function(){ // ajax请求 $("#ajaxBtn").click(function(){ $.ajax({ url:"http://localhost:8080/Json_AJAX_i18n/ajaxServlet", //请求路径 type:"get", //请求类型 data:"function=jQueryAjax", //请求参数 success:function (data){ //成功之后回调函数,data必填,代表传回的数据对象 $("#div01").html("编号:" + data.id + ",姓名:" + data.name) }, dataType:"json" //接收到的参数类型:Text,Json,XML }) }); // ajax--get请求 $("#getBtn").click(function(){ $.get("http://localhost:8080/Json_AJAX_i18n/ajaxServlet", "function=jQueryGet", function (data){ $("#div01").html("编号:" + data.id + ",姓名:" + data.name) }, "json" ) }); // ajax--post请求 $("#postBtn").click(function(){ $.post("http://localhost:8080/Json_AJAX_i18n/ajaxServlet", "function=jQueryGet", function (data){ $("#div01").html("编号:" + data.id + ",姓名:" + data.name) }, "json" ); }); // ajax--getJson请求 $("#getJSONBtn").click(function(){ $.getJSON("http://localhost:8080/Json_AJAX_i18n/ajaxServlet","function=jQueryGetJson", function (data){ $("#div01").html("编号:" + data.id + ",姓名:" + data.name) }) }); // ajax请求 $("#submit").click(function(){ //alert($("#form01").serialize()); //会把表单里的所有表单项拼接成key=value&key=value格式 $.ajax({ url:"http://localhost:8080/Json_AJAX_i18n/ajaxServlet", type: "get", data: "function=jQuerySerialize&" + $("#form01").serialize(), success:function (data){ $("#div01").html("编号:" + data.id + ",姓名:" + data.name) }, dataType: "json" }) }); }); </script> </head> <body> <div> <button id="ajaxBtn">$.ajax请求</button> <button id="getBtn">$.get请求</button> <button id="postBtn">$.post请求</button> <button id="getJSONBtn">$.getJSON请求</button> </div> <div id="div01"></div> <br/><br/> <form id="form01" > 用户名:<input name="username" type="text" /><br/> 密码:<input name="password" type="password" /><br/> 下拉单选:<select name="single"> <option value="Single">Single</option> <option value="Single2">Single2</option> </select><br/> 下拉多选: <select name="multiple" multiple="multiple"> <option selected="selected" value="Multiple">Multiple</option> <option value="Multiple2">Multiple2</option> <option selected="selected" value="Multiple3">Multiple3</option> </select><br/> 复选: <input type="checkbox" name="check" value="check1"/> check1 <input type="checkbox" name="check" value="check2" checked="checked"/> check2<br/> 单选: <input type="radio" name="radio" value="radio1" checked="checked"/> radio1 <input type="radio" name="radio" value="radio2"/> radio2<br/> </form> <button id="submit">提交--serialize()</button> </body> </html>
public class AjaxServlet extends BaseServlet{ protected void scriptGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("ajaxRequest 方法进来了"); Person person = new Person(1,"Tom"); Gson gson = new Gson(); String jsonStr = gson.toJson(person); resp.getWriter().write(jsonStr); } protected void jQueryAjax(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("jQueryAjax 方法进来了"); Person person = new Person(1,"Tom"); Gson gson = new Gson(); String jsonStr = gson.toJson(person); resp.getWriter().write(jsonStr); } protected void jQueryGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("jQueryGet 方法进来了"); Person person = new Person(1,"Tom"); Gson gson = new Gson(); String jsonStr = gson.toJson(person); resp.getWriter().write(jsonStr); } protected void jQueryPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("jQueryPost 方法进来了"); Person person = new Person(1,"Tom"); Gson gson = new Gson(); String jsonStr = gson.toJson(person); resp.getWriter().write(jsonStr); } protected void jQueryGetJson(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("jQueryGetJson 方法进来了"); Person person = new Person(1,"Tom"); Gson gson = new Gson(); String jsonStr = gson.toJson(person); resp.getWriter().write(jsonStr); } protected void jQuerySerialize(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("jQuerySerialize 方法进来了"); System.out.println(req.getParameter("username")); System.out.println(req.getParameter("password")); Person person = new Person(1,"Tom"); Gson gson = new Gson(); String jsonStr = gson.toJson(person); resp.getWriter().write(jsonStr); } }
- .ajax : 5个重要参数
i18n国际化
-
什么是i18n国际化?
国际化指的是同一个网站可以支持多种不同的语言,以方便各个国家的用户访问。关于国际化我们第一个想到的方案是为不同的国家创建不同的页面。而i18n是可以在同一个页面显示不同文字信息。
-
i18n国际化三要素
- Locale对象:表示不同的时区,位置,语言(比如中国:zh_CN)
- ResourceBundle资源包
- Properties配置文件:不同的语言配置不同的文件,命名规范 i18n_locale.properties
-
使用i18n
#中国 i18n_zh_CN.properties username=\u7528\u6237\u540D password=\u5BC6\u7801 sex=\u6027\u522B age=\u5E74\u9F84 regist=\u6CE8\u518C boy=\u7537 girl=\u5973 email=\u90AE\u7BB1 reset=\u91CD\u7F6E submit=\u63D0\u4EA4 #美国 i18n_en_US.properties username=username password=password sex=sex age=age regist=regist boy=boy email=email girl=girl reset=reset submit=submit
public class I18nTest { @Test public void test1(){ Locale locale = new Locale("zh_CN"); System.out.println(locale); System.out.println(Locale.CHINA); System.out.println(Locale.US); } @Test public void test2(){ //设置我们需要的locale对象 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")); System.out.println("Sex:" + bundle.getString("sex")); System.out.println("age:" + bundle.getString("age")); } }
-
EL表达式中使用
<%@ page import="java.util.Locale" %> <%@ page import="java.util.ResourceBundle" %> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!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> <% Locale locale = null; String country = request.getParameter("country"); if("china".equals(country)){ locale = Locale.CHINA; //设置中文 }else if ("usa".equals(country)){ locale = Locale.US; //设置英文 }else { locale = Locale.getDefault(); //设置浏览器默认 } ResourceBundle bundle = ResourceBundle.getBundle("i18n", locale); %> </head> <body> <a href="i18n.jsp?country=china">中文</a>| <a href="i18n.jsp?country=usa">english</a> <center> <h1><%=bundle.getString("regist")%></h1> <table> <form> <tr> <td><%=bundle.getString("username")%></td> <td><input name="username" type="text" /></td> </tr> <tr> <td><%=bundle.getString("password")%></td> <td><input type="password" /></td> </tr> <tr> <td><%=bundle.getString("sex")%></td> <td> <input type="radio" /><%=bundle.getString("boy")%> <input type="radio" /><%=bundle.getString("girl")%> </td> </tr> <tr> <td><%=bundle.getString("email")%></td> <td><input type="text" /></td> </tr> <tr> <td colspan="2" align="center"> <input type="reset" value="<%=bundle.getString("reset")%>" /> <input type="submit" value="<%=bundle.getString("submit")%>" /></td> </tr> </form> </table> <br /> <br /> <br /> <br /> </center> 国际化测试: <br /> 1、访问页面,通过浏览器设置,请求头信息确定国际化语言。 <br /> 2、通过左上角,手动切换语言 </body> </html>
-
在JSTL中使用
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!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> </head> <body> <%--设置locale对象--%> <fmt:setLocale value="${param.locale}" /> <%--设置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> <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> </html>