JSON(JavaScript Object Notation)
1.一种轻量级的数据交换格式
2.通常用于在客户端和服务器之间传递数据
3.jQuery的所有参数都是以JSON格式出现
4.在Struts 2中通过插件的方式实现
优势(较XML):
1.轻量级交换语言
2.结构简单
3.易于解析
JSON对象:
语法:
var JSON对象 = {key:value,key:value,……};
范例:{"id":4,"name":"梅西","pwd":"6666"}
【注意:其中的key值必须是字符串】
JSON数组:
语法:
var JSON数组 = [value,value,……];
范例:
var countryArray = ["中国","美国","俄罗斯"];
var personArray = [
{"name":"张三","age":30},
{"name":"李四","age":40}
];
步骤:
1.导入struts2-json-plugin-xxx.jar
2.在struts.xml中定义package并继承json-default
3.指定<result>的type属性指定为"json"
================================Result===============================
一、JSON类型的Result:
1.参数说明:
参数 作用 默认值 适用场景
root 指定要序列化的根对象 当前Actin中所有有返回值的getter方法的值 用于指定不需要序列化key值的数据
includeProperties 指定根对象中要序列化的属性 当前根对象中的所有属性 用于需要序列化的属性较少的情况
excludeProperties 指定根对象中要排除的属性 null 用于需要排除序列化的属性较少的情况
excludeNullProperties 指定根对象中是否序列化值为空的属性 false 用于需要过滤空值的情况
2.步骤:
a.添加第三方插件:struts2-json-plugin-xxx.jar
b.在struts.xml中指定package继承json-default
c.指定<result>的type属性为“json”
d.根据业务需求合理指定param参数
3.作用:
a.返回JSON格式数据,配合jQuery实现Ajax
b.param参数
c.root、 includeProperties、 excludeProperties、 excludeNullProperties
范例:登录表单
1.User实体类
1 package com.Elastic.StrutsDemo6.ivy.entity; 2 spublic class User { 3 private String loginName; 4 private String loginPass; 5 6 public String getLoginName() { 7 return loginName; 8 } 9 public void setLoginName(String loginName) { 10 this.loginName = loginName; 11 } 12 public String getLoginPass() { 13 return loginPass; 14 } 15 public void setLoginPass(String loginPass) { 16 this.loginPass = loginPass; 17 } 18 19 }
2.UserAction类
1 package com.Elastic.StrutsDemo6.ivy.action; 2 3 import java.util.Date; 4 import java.util.HashMap; 5 import java.util.Map; 6 7 import com.Elastic.StrutsDemo6.ivy.entity.User; 8 import com.opensymphony.xwork2.ActionSupport; 9 10 public class UserAction extends ActionSupport { 11 private User user; 12 13 public User getUser() { 14 return user; 15 } 16 17 public void setUser(User user) { 18 this.user = user; 19 } 20 21 private Map<String, Object> jsonResult = new HashMap<String, Object>(); 22 23 public Map<String, Object> getJsonResult() { 24 return jsonResult; 25 } 26 27 public void setJsonResult(Map<String, Object> jsonResult) { 28 this.jsonResult = jsonResult; 29 } 30 31 public String login() { 32 33 //登陆成功以后,额外添加的信息 34 /*jsonResult.put("success", true); 35 jsonResult.put("data", user); 36 jsonResult.put("msg", "登陆成功"); 37 jsonResult.put("loginTime", new Date());*/ 38 39 if ("admin".equals(user.getLoginName().trim()) && "123456".equals(user.getLoginPass().trim())) { 40 jsonResult.put("success", true); 41 jsonResult.put("data", user); 42 jsonResult.put("msg", "登陆成功"); 43 jsonResult.put("loginTime", new Date()); 44 } else { 45 jsonResult.put("success", false); 46 jsonResult.put("msg", "登陆失败"); 47 jsonResult.put("loginTime", new Date()); 48 } 49 return SUCCESS; 50 } 51 }
3.struts.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd" > 3 <struts> 4 <!-- 使用JSON配置 --> 5 <package name="jsonDefault" namespace="/" extends="json-default"> 6 <action name="login" class="com.Elastic.StrutsDemo6.ivy.action.UserAction" method="login"> 7 8 <!-- 配置JSON类型的result --> 9 <!--type属性指定为"json"",将返回序列化的JSON格式数据--> 10 <result type="json"> 11 <!-- <param name="root">user</param> --> 12 <param name="root">jsonResult</param> 13 </result> 14 </action> 15 16 </package> 17 </struts>
4.web.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <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" id="WebApp_ID" version="2.5"> 3 <display-name>StrutsDemo6_ivy</display-name> 4 <welcome-file-list> 5 <welcome-file>index.html</welcome-file> 6 <welcome-file>index.htm</welcome-file> 7 <welcome-file>index.jsp</welcome-file> 8 <welcome-file>default.html</welcome-file> 9 <welcome-file>default.htm</welcome-file> 10 <welcome-file>default.jsp</welcome-file> 11 </welcome-file-list> 12 13 <filter> 14 <filter-name>Struts2</filter-name> 15 <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> 16 </filter> 17 <filter-mapping> 18 <filter-name>Struts2</filter-name> 19 <url-pattern>/*</url-pattern> 20 </filter-mapping> 21 22 </web-app>
5.valid.js
1 /** 2 * rules: 对象 3 */ 4 5 var rules = { 6 loginName : { 7 rule : { 8 required : true, 9 length : [6,12] 10 }, 11 msg : { 12 required : '用户名不能为空', 13 length : '用户名的长度必须在6-12位之间' 14 } 15 }, 16 17 loginPass : { 18 rule : { 19 length : [6,12] 20 }, 21 msg : { 22 length : '密码的长度必须在6-12位之间' 23 } 24 } 25 }; 26 27 function validForm(form,rules) { 28 for ( var p in rules) { 29 form.find('#' + p).on('valid',rules[p],function(event){ 30 //使用event.data, msg内容才会不同!!! 31 var inputRules = event.data.rule; 32 33 for ( var r in inputRules) { 34 var value = $(this).val(); 35 if (r === 'required' && inputRules[r] === true) { 36 if (value === '') { 37 $(this).data('success',false); 38 39 $(this).closest('div').next().html(event.data.msg[r]); 40 41 } else { 42 $(this).data('success',true); 43 $(this).closest('div').next().html(''); 44 } 45 } 46 47 //验证先后顺序 48 /*if ($(this).data('success') === false) { 49 return; 50 }*/ 51 52 if (r === 'length' && inputRules[r]) { 53 if (value.length > inputRules[r][1] || value.length < inputRules[r][0]) { 54 $(this).data('success',false); 55 56 $(this).closest('div').next().html(event.data.msg[r]); 57 58 } else { 59 $(this).data('success',true); 60 $(this).closest('div').next().html(''); 61 } 62 } 63 } 64 }); 65 } 66 67 //事件绑定一次 68 function valid() { 69 //trigger:触发valid事件 70 form.find(':input').trigger('valid'); 71 var success = true; 72 73 form.find(':input').each(function() { 74 if ($(this).data('success') === false) { 75 success = false; 76 return; 77 } 78 }); 79 return success; 80 } 81 82 return valid; 83 }
6.login.jsp
1 <%--引入JSP页面PAGE指令 --%> 2 <%@ page language="java" contentType="text/html; charset=UTF-8" 3 pageEncoding="UTF-8"%> 4 <%-- 引入JSTL标签指令 --%> 5 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> 6 <!DOCTYPE html> 7 <html language="zh-CN"> 8 <head> 9 <meta charset="utf-8"> 10 <!-- 设置浏览器渲染的引擎 --> 11 <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> 12 <!-- 设置支持移动设备 --> 13 <meta name="viewport" content="width=device-width, initial-scale=1"> 14 <title>网页标题</title> 15 <!-- 引入bootstrap的样式 --> 16 <link rel="stylesheet" type="text/css" href="<%=request.getContextPath()%>/css/bootstrap.min.css"> 17 </head> 18 <body> 19 <div class="container"> 20 21 <div class="panel panel-primary"> 22 <div class="panel-heading">登陆</div> 23 <div class="panel-body"> 24 <form class="form-horizontal" action="login" method="post" data-role="login"> 25 <div class="form-group"> 26 <label class="col-md-3 control-label" for="loginName">用户名:</label> 27 <div class="col-md-6"> 28 <input class="form-control" id="loginName" name="user.loginName" type="text" autocomplete="off" /> 29 </div> 30 <div class="col-md-3"> 31 32 </div> 33 </div> 34 <div class="form-group"> 35 <label class="col-md-3 control-label" for="loginPass">密码:</label> 36 <div class="col-md-6"> 37 <input class="form-control" id="loginPass" name="user.loginPass" type="password" /> 38 </div> 39 <div class="col-md-3"> 40 41 </div> 42 </div> 43 <div class="form-group"> 44 <input class="btn btn-primary btn-block" data-role="login" type="button" value="登陆" /> 45 </div> 46 </form> 47 </div> 48 </div> 49 </div> 50 51 <!-- 引入JS的样式 --> 52 <script type="text/javascript" src="<%=request.getContextPath()%>/js/jquery-2.2.4.js"></script> 53 <script type="text/javascript" src="<%=request.getContextPath()%>/js/bootstrap.min.js"></script> 54 55 <script type="text/javascript" src="<%=request.getContextPath()%>/js/valid.js"></script> 56 57 <script type="text/javascript"> 58 //JSON对象 59 //测试 60 /* var person = { 61 "name":"李四", 62 "age":20 63 }; 64 65 alert(person.age); */ 66 67 $(function() { 68 //方法二 69 //给表单元素绑定一个自定义的验证事件 70 /* $('#loginName').on('valid', function() { 71 var name = $(this).val(); 72 if ('' == name) { 73 $(this).closest('div').next().html('用户名不能为空!'); 74 $(this).data('success', false); 75 } else { 76 $(this).closest('div').next().html(''); 77 $(this).data('success', true); 78 } 79 80 }); 81 $('#loginPass').on('valid', function() { 82 var name = $(this).val(); 83 if ('' == name) { 84 $(this).closest('div').next().html('密码不能为空!'); 85 $(this).data('success', false); 86 } else { 87 $(this).closest('div').next().html(''); 88 $(this).data('success', true); 89 } 90 91 }); */ 92 93 var valid = validForm($('form'), rules); 94 95 $('[data-role="login"]').click(function() { 96 //获取表单 97 var $form = $(this).closest('form'); 98 99 $.ajax({ 100 url : "login", 101 type : "post", 102 data : $form.serialize(), 103 //data : $(this).closest('form').serialize(), 104 beforeSend : function() { 105 /* var success = true; 106 107 //trigger:触发valid事件 108 $form.find(':input').trigger('valid'); 109 $form.find(':input').each(function() { 110 if ($(this).data('success') === false) { 111 success = false; 112 return; 113 } 114 }); 115 return success;*/ 116 117 //方法三 118 //返回方法 119 return valid(); 120 121 //方法一: 122 /* var name = $('#loginName').val(); 123 if ('' == name) { 124 $('#loginName').closest('div').next().html('用户名不能为空!'); 125 return false; 126 } else { 127 $('#loginName').closest('div').next().html(''); 128 } 129 130 var pass = $('#loginPass').val(); 131 if ('' == pass) { 132 $('#loginPass').closest('div').next().html('密码不能为空!'); 133 return false; 134 } else { 135 $('#loginPass').closest('div').next().html(''); 136 } */ 137 }, 138 success : function(result) { 139 //返回result(对象) 140 //alert(result); 141 alert(result.msg); 142 if (result.success) { 143 //window.location = 'index.jsp'; 144 } 145 } 146 147 }); 148 }); 149 }); 150 </script> 151 </body> 152 </html>
二、Stream类型的Result
1.步骤:
a.定义一个InputStream类型的成员变量
b.给该变量添加getter和setter方法
c.将要发送到客户端的数据赋值给该变量
d.根据业务需求合理指定param参数
2.作用:
a.返回二进制数据,配合jQuery实现Ajax,或者实现验证码
3.param参数
a.contentType、inputStream
范例:验证码--在上一个范例的基础上修改
1.CodeAction类
1 package com.Elastic.StrutsDemo6.ivy.action; 2 3 import java.awt.Color; 4 import java.awt.Font; 5 import java.awt.FontMetrics; 6 import java.awt.Graphics2D; 7 import java.awt.image.BufferedImage; 8 import java.io.ByteArrayInputStream; 9 import java.io.ByteArrayOutputStream; 10 import java.io.IOException; 11 import java.io.InputStream; 12 import java.util.Date; 13 14 import javax.imageio.ImageIO; 15 16 import com.opensymphony.xwork2.ActionContext; 17 import com.opensymphony.xwork2.ActionSupport; 18 19 public class CodeAction extends ActionSupport { 20 private InputStream inputStream; 21 22 public InputStream getInputStream() throws IOException { 23 //1.随机生成4位的验证码 24 String[] strs = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", 25 "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", 26 "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", 27 "8", "9" }; 28 String code = ""; 29 for (int i = 0; i < 4; i++) { 30 String temp = strs[(int)(Math.random() * strs.length)]; 31 32 //随机生成大写字母 33 temp = (int)(Math.random() * 2) == 0 ? temp : temp.toUpperCase(); 34 code += temp; 35 } 36 37 //2.生成验证码图片 38 BufferedImage codeImg = new BufferedImage(100, 25, BufferedImage.TYPE_INT_RGB); 39 //得到图片的绘制对象 40 Graphics2D g2d = codeImg.createGraphics(); 41 //设置填充颜色并填充 42 g2d.setColor(new Color(240, 240, 240)); 43 g2d.fillRect(0, 0, codeImg.getWidth(), codeImg.getHeight()); 44 //绘制验证码到图片上 45 Font font = new Font("微软雅黑", Font.PLAIN, 20); 46 g2d.setFont(font); 47 //获取字体宽度 48 FontMetrics fm = g2d.getFontMetrics(); 49 //设置左右空白和字体间隔 50 float start = 15; 51 float space = (float)(codeImg.getWidth() - 2 * start - fm.getStringBounds(code, g2d).getWidth()) / (code.length() - 1); 52 //随机生成每个字符的样式 53 for (int i = 0; i < code.length(); i++) { 54 g2d.setColor(getRandomColor()); 55 String temp = code.charAt(i) + ""; 56 g2d.drawString(temp, start, font.getSize()); 57 start += fm.getStringBounds(temp, g2d).getWidth() + space; 58 } 59 60 //绘制干扰项 61 //随机生成点 62 for (int i = 0; i < 100; i++) { 63 g2d.setColor(getRandomColor()); 64 int x = (int)(Math.random() * codeImg.getWidth()); 65 int y = (int)(Math.random() * codeImg.getHeight()); 66 g2d.drawLine(x, y, x, y); 67 } 68 //随机生成线 69 for (int i = 0; i < 10; i++) { 70 g2d.setColor(getRandomColor()); 71 int x = (int)(Math.random() * codeImg.getWidth()); 72 int y = (int)(Math.random() * codeImg.getHeight()); 73 int x1 = (int)(Math.random() * codeImg.getWidth()); 74 int y1 = (int)(Math.random() * codeImg.getHeight()); 75 g2d.drawLine(x, y, x1, y1); 76 } 77 78 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); 79 ImageIO.write(codeImg, "png", byteArrayOutputStream); 80 ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); 81 82 //把验证码保存到session中 83 ActionContext.getContext().getSession().put("code", code); 84 //设置验证码有效时间 85 ActionContext.getContext().getSession().put("codeMaxTime", new Date().getTime() + 10 * 1000); 86 87 return byteArrayInputStream; 88 } 89 90 public Color getRandomColor() { 91 int r = (int)(Math.random() * 256); 92 int g = (int)(Math.random() * 256); 93 int b = (int)(Math.random() * 256); 94 return new Color(r, g, b); 95 } 96 97 }
2.struts.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd" > 3 <struts> 4 5 <!-- 使用JSON配置 --> 6 <package name="jsonDefault" namespace="/" extends="json-default"> 7 <action name="login" class="com.Elastic.StrutsDemo6.ivy.action.UserAction" method="login"> 8 <!-- 配置JSON类型的result --> 9 <!--type属性指定为"json"",将返回序列化的JSON格式数据--> 10 <result type="json"> 11 <!-- <param name="root">user</param> --> 12 <param name="root">jsonResult</param> 13 14 <!-- ??? --> 15 <param name="excludeProperties">data.loginPass</param> 16 <param name="excludeNullProperties">true</param> 17 </result> 18 19 </action> 20 </package> 21 22 <package name="default" namespace="/" extends="struts-default"> 23 <action name="code" class="com.Elastic.StrutsDemo6.ivy.action.CodeAction"> 24 <result type="stream"> 25 <param name="ContentType">image/jpeg</param> 26 <param name="inputStream"></param> 27 </result> 28 29 </action> 30 31 </package> 32 </struts>
3.UserAction类
1 package com.Elastic.StrutsDemo6.ivy.action; 2 3 import java.util.Date; 4 import java.util.HashMap; 5 import java.util.Map; 6 7 import com.Elastic.StrutsDemo6.ivy.entity.User; 8 import com.opensymphony.xwork2.ActionContext; 9 import com.opensymphony.xwork2.ActionSupport; 10 11 public class UserAction extends ActionSupport { 12 private User user; 13 14 private String code; 15 16 public String getCode() { 17 return code; 18 } 19 20 public void setCode(String code) { 21 this.code = code; 22 } 23 24 public User getUser() { 25 return user; 26 } 27 28 public void setUser(User user) { 29 this.user = user; 30 } 31 32 private Map<String, Object> jsonResult = new HashMap<String, Object>(); 33 34 public Map<String, Object> getJsonResult() { 35 return jsonResult; 36 } 37 38 public void setJsonResult(Map<String, Object> jsonResult) { 39 this.jsonResult = jsonResult; 40 } 41 42 public String login() { 43 44 long time = (long) ActionContext.getContext().getSession().get("codeMaxTime"); 45 if (time < new Date().getTime()) { 46 jsonResult.put("msg", "验证码过期"); 47 jsonResult.put("success", false); 48 return SUCCESS; 49 } 50 51 String sessionCode = ActionContext.getContext().getSession().get("code").toString(); 52 if (sessionCode.equalsIgnoreCase(code)) { 53 jsonResult.put("msg", "验证码错误"); 54 jsonResult.put("success", false); 55 return SUCCESS; 56 } 57 58 //登陆成功以后,额外添加的信息 59 /*jsonResult.put("success", true); 60 jsonResult.put("data", user); 61 jsonResult.put("msg", "登陆成功"); 62 jsonResult.put("loginTime", new Date());*/ 63 64 if ("admin".equals(user.getLoginName().trim()) && "123456".equals(user.getLoginPass().trim())) { 65 jsonResult.put("success", true); 66 jsonResult.put("data", user); 67 jsonResult.put("msg", "登陆成功"); 68 jsonResult.put("loginTime", new Date()); 69 } else { 70 jsonResult.put("success", false); 71 jsonResult.put("msg", "登陆失败"); 72 jsonResult.put("loginTime", new Date()); 73 } 74 return SUCCESS; 75 } 76 77 }
4.login.jsp
1 <%--引入JSP页面PAGE指令 --%> 2 <%@ page language="java" contentType="text/html; charset=UTF-8" 3 pageEncoding="UTF-8"%> 4 <%-- 引入JSTL标签指令 --%> 5 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> 6 <!DOCTYPE html> 7 <html language="zh-CN"> 8 <head> 9 <meta charset="utf-8"> 10 <!-- 设置浏览器渲染的引擎 --> 11 <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> 12 <!-- 设置支持移动设备 --> 13 <meta name="viewport" content="width=device-width, initial-scale=1"> 14 <title>网页标题</title> 15 <!-- 引入bootstrap的样式 --> 16 <link rel="stylesheet" type="text/css" 17 href="<%=request.getContextPath()%>/css/bootstrap.min.css"> 18 </head> 19 <body> 20 <div class="container"> 21 22 <div class="panel panel-primary"> 23 <div class="panel-heading">登陆</div> 24 <div class="panel-body"> 25 <form class="form-horizontal" action="login" method="post" data-role="login"> 26 <div class="form-group"> 27 <label class="col-md-3 control-label" for="loginName">用户名:</label> 28 <div class="col-md-6"> 29 <input class="form-control" id="loginName" name="user.loginName" type="text" autocomplete="off" /> 30 </div> 31 <div class="col-md-3"> 32 33 </div> 34 </div> 35 <div class="form-group"> 36 <label class="col-md-3 control-label" for="loginPass">密码:</label> 37 <div class="col-md-6"> 38 <input class="form-control" id="loginPass" name="user.loginPass" type="password" /> 39 </div> 40 <div class="col-md-3"> 41 42 </div> 43 </div> 44 <div class="form-group"> 45 <label class="col-md-3 control-label" for="code">验证码:</label> 46 <div class="col-md-6"> 47 <input class="form-control" id="code" name="code" type="password" /> 48 <img id="codeImg" alt="" src="code" onclick="getCode()"><a href="javascript:getCode();">看不清楚,换一张?</a> 49 </div> 50 <div class="col-md-3"> 51 52 </div> 53 </div> 54 <div class="form-group"> 55 <input class="btn btn-primary btn-block" data-role="login" type="button" value="登陆" /> 56 </div> 57 </form> 58 </div> 59 </div> 60 </div> 61 62 <!-- 引入JS的样式 --> 63 <script type="text/javascript" src="<%=request.getContextPath()%>/js/jquery-2.2.4.js"></script> 64 <script type="text/javascript" src="<%=request.getContextPath()%>/js/bootstrap.min.js"></script> 65 66 <script type="text/javascript" src="<%=request.getContextPath()%>/js/valid.js"></script> 67 68 <script type="text/javascript"> 69 function getCode() { 70 document.getElementById('codeImg').src='code?_dc='+new Data(); 71 } 72 </script> 73 74 <script type="text/javascript"> 75 $(function() { 76 var valid = validForm($('form'), rules); 77 78 $('[data-role="login"]').click(function() { 79 //获取表单 80 var $form = $(this).closest('form'); 81 $.ajax({ 82 url : "login", 83 type : "post", 84 data : $form.serialize(), 85 beforeSend : function() { 86 //返回方法 87 return valid(); 88 }, 89 success : function(result) { 90 alert(result.msg); 91 if (result.success) { 92 //window.location = 'index.jsp'; 93 } 94 } 95 96 }); 97 }); 98 }); 99 </script> 100 </body> 101 </html>