您的位置:首页 > 编程语言 > Java开发

struts2 --- ajax的三种实现方式

2018-01-08 20:59 357 查看

一、Struts2 Response实现

1.1 UserAction
package com.struts2.fileupload.action;

import org.apache.struts2.ServletActionContext;
import org.codehaus.jackson.map.ObjectMapper;

import com.struts2.fileupload.domain.Result;

public class UserAction {

public void checkUsername() {
// 解决响应乱码
ServletActionContext.getResponse().setCharacterEncoding("utf-8");
// 1.得到录入的用户名
String username = ServletActionContext.getRequest().getParameter("username");

Result result = new Result();
// 2.判断用户名是否可用
if ("tom".equals(username)) {
// 不可使用
result.setFlag(false);
result.setMessage("用户名已经被占用");
} else {
// 可以使用
result.setFlag(true);
result.setMessage("用户名可以使用");
}
// 3.将result转换成json响应到浏览器端
ObjectMapper mapper = new ObjectMapper();
try {
String json = mapper.writeValueAsString(result);

ServletActionContext.getResponse().getWriter().write(json);

} catch (Exception e) {
e.printStackTrace();
}
}
}

1.2 struts.xml

<package name="default" namespace="/" extends="struts-default">

<action name="checkUsername" class="com.struts2.fileupload.action.UserAction"
method="checkUsername"></action>
</package>

1.3 jsp

<%@ 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="Content-Type" content="text/html; charset=UTF-8">
<title>注册页面</title>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.8.3.js"></script>
<script type="text/javascript">
//校验用户名是否可用
function checkUsername() {
//1.获取用户名
var usernameValue = $("#username").val();
//2.向服务器发送请求
$.post("${pageContext.request.contextPath}/checkUsername", {
"username" : usernameValue
}, function(data) {

var jsonObj = eval(data); //转换成js对象
if (jsonObj.flag) {
//可以使用
$("#username_msg").html(
"<font color='green'>" + jsonObj.message + "</font>");
} else {
//不可以使用
$("#username_msg").html(
"<font color='red'>" + jsonObj.message + "</font>");
}

}, "json");
}
</script>
</head>
<body>
<input type="text" name="username" id="username" onblur="checkUsername()"><span id="username_msg"></span>
<br>
<input type="password" name="password">

</body>
</html>


二、使用result type="stream"实现
2.1 Action
package com.struts2.fileupload.action;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import com.opensymphony.xwork2.ActionSupport;

public class HelloAction extends ActionSupport{

private InputStream inputStream;

public InputStream getInputStream() {
return inputStream;
}

public String execute() throws Exception {
String str = "HelloWorld";
inputStream = new ByteArrayInputStream(str.getBytes("UTF-8"));
return SUCCESS;
}
}

2.2 strtus.xml
<package name="default" namespace="/" extends="struts-default">
<action name="hello" class="com.struts2.fileupload.action.HelloAction" method="execute">
<!--
type="stream"
向浏览器发送InputStream对象,通常用来处理文件下载
-->
<result name="success" type="stream">
<!--
contentType是用来指定响应类型,如果有中文的话最好设置一下编码
inputName是用来指定Action中的对应的输入流,它的默认值就是inputStream
-->
<param name="contentType">text/html; charset=utf-8</param>
<param name="inputName">inputStream</param>
</result>
</action>
</package>

2.3 jsp

<%@ 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="Content-Type" content="text/html; charset=UTF-8">
<title>Steam Test</title>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.8.3.js"></script>
<script type="text/javascript">
function ajax_stream_test() {
$.post("${pageContext.request.contextPath}/hello", function(data) {

alert(data);
$("#username_msg").html(
"<font color='green'>" + data + "</font>");

});
}
</script>
</head>
<body>
<input type="button" value="stream test" onclick="ajax_stream_test()" />
<span id="username_msg"></span>
</body>
</html>


三、使用strus2 json插件实现

3.1 导入jar包

struts2-json-plugin-2.3.24.jar

3.2 Action
package com.struts2.fileupload.action;

import java.util.ArrayList;
import java.util.List;

import com.opensymphony.xwork2.ActionContext;
import com.struts2.fileupload.domain.Product;

public class ProductAction {

public String showProduct() {

// 1.将数据得到List<Product>
Product p1 = new Product();
p1.setId(1);
p1.setName("电视机");
p1.setPrice(2000);

Product p2 = new Product();
p2.setId(2);
p2.setName("电冰箱");
p2.setPrice(3000);

List<Product> ps = new ArrayList<Product>();
ps.add(p1);
ps.add(p2);
// 2.将List<Product>压入到valueStack栈顶
ActionContext.getContext().getValueStack().set("ps", ps);

return "success";
}
}


3.3 jsp

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>注册页面</title>
<script type="text/javascript" src="/struts2-day03/js/jquery-1.8.3.js"></script>
<script type="text/javascript">
//页面加载完成后操作
$(function() {

$("#a").toggle(
function() {
//1.向服务器发送请求,获取商品信息
$.post(
"/struts2-day03/showProduct",
function(data) {
//2.将响应回的json数据转换成html代码,在div中展示
var html = "<table border='1'><tr><td>编号</td><td>名称</td><td>价格</td></tr>";

//[{"id":1,"name":"电视机","price":2000.0},{"id":2,"name":"电冰箱","price":3000.0}]
var jsonObj = eval(data);
for (var i = 0; i < jsonObj.length; i++) {
html += "<tr><td>"
+ jsonObj[i].id
+ "</td><td>"
+ jsonObj[i].name
+ "</td><td>"
+ jsonObj[i].price
+ "</td></tr>";
}

html += "</table>";
$("#productMsg").html(html);
}, "json");
}, function() {
$("#productMsg").html("");
});
});
</script>
</head>
<body>
<a href="javascript:void(0)" id="a">显示商品信息</a>
<div id="productMsg"></div>
</body>
</html>


3.4 xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
<package name="default" namespace="/" extends="json-default">

<action name="showProduct" class="cn.itheima.action.ProductAction"
method="showProduct">

<!-- 简单返回json数据 -->
<!-- <result name="success" type="json"></result> -->

<!-- 返回的数据包含或者不包含某些属性 -->
<result name="success" type="json">
<!--
返回的数据格式:
{"ps":[{"id":1,"电视机"},{"id":2,"电冰箱"}]}

我们只想返回的是[]中的值,可以通过root去掉ps
-->
<!-- root是struts2-json-plugin-2.3.24.jar扩展包下的org.apache.struts2.json.JSONResult中的属性 -->
<param name="root">ps</param>

<!-- 设置包含或者不包含的属性 -->
<!-- excludeProerties和includeProperties是struts2-json-plugin-2.3.24.jar扩展包下的org.apache.struts2.json.JSONResult中的属性 -->
<param name="excludeProperties">\[\d+\]\.releaseDate</param>
<!-- <param name="includeProperties">ps\[\d+\]\.id,ps\[\d+\]\.name</param> -->
</result>
</action>
</package>

</struts>

注意:
1、配置文件中的package需要去继承struts2 json插件定义的json-default
2、result的type="json"

3.5 配置常用JSON类型的Result --- org.apache.struts2.json.JSONResult

(1)浏览器是否缓存JSON

<result type="json">
  <!-- 取消浏览器缓存-->
  <param name="noCache">true</param>
</result>


 

 (2)设置浏览器响应类型,默认为text/html

<result type="json">
  <!-- 设置服务器响应类型-->
  <param name="contentType">application/json</param>
</result>



 


(3)排除值为null 的属性

<result type="json">
<!--排除值为null的属性-->
<param name="excludeNullProperties">true</param>
</result>


 

(4)只序列化指定的Action属性

<result type="json">
<!--只序列化Action内的list属性-->
<param name="root">list</param>
</result>


(5)序列化包含的属性(逗号分隔的正则表达式列表)


<result type="json">
<!--序列化list属性-->
<param name="includeProperties">list.*</param>
</result>


<result type="json">
<!--序列化array属性,\[和\]匹配数组的[]括号,\d匹配数字,+表示一次或多次-->
<param name="includeProperties">array\[\d+\]</param>
</result>


(6)排除不需要被序列化的属性(逗号分隔的正则表达式列表)


<result type="json">
<!--排除list属性-->
  <param name="excludeProperties"> list.* </param>
</result>




 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: