(十七)Struts 2.x与Ajax

        如果现在要想使用Struts2.x的Action利用异步处理实现数据输出,那么必然这个输出的输出分方法里面是不应该有返回路径的,不会跳转.

        如果要处理Ajax建议使用jQuery,将jQuery的开发包配置到项目之中;

范例:建立一个新的Action--CrityAction.java

package cn.zwb.action;
import java.io.IOException;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@SuppressWarnings("serial")
public class CrityAction extends ActionSupport{
	public void list(){  //利用多业务处理
		JSONObject all = new JSONObject();
		JSONArray array = new JSONArray();
		for (int i = 0; i <10; i++) {
			JSONObject temp = new JSONObject();
			temp.put("cid", i);
			temp.put("title", "城市名称-"+i);
			array.add(temp);
		}
		all.put("allCities", array);
		try {
			ServletActionContext.getResponse().getWriter().print(all);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

        现在的Action之中只负责了核心操作的处理,当然本次是减少了业务层的使用,

范例:在struts.xml文件中配置 

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
	<package name="front" namespace="/pages/font" extends="struts-default">
		<action name="CityAction" class="cn.zwb.action.CrityAction"/>
	</package>
</struts>    

        此处没有所谓的跳转,并且也建立相应的子目录,所以这个时候CrityAction的完整访问路径是"/pages/front/CrityAction"

        随后在页面之中建立相应的显示的JS程序.

范例:定义city_list.jsp页面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>jQuery+Struts 2.x</title>
 <script type="text/javascript" src="js/jquery-3.1.1.js"></script>
 <script type="text/javascript" src="js/crity_list.js"></script>
  </head>
  
  <body>
    <div>
    	<table border="1" id="cityTab">
    		<tr>
    			<td>城市编号</td>
    			<td>城市名称</td>
    		</tr>
    	</table>	
    </div>
  </body>
</html>

        随后的重点就是在city_list.js文件的使用上了

范例:编写city_list.js文件

$(function() {
	$.post("pages/front/CityAction!list.action", {}, function(data) {
		for (var x = 0; x < data.allCities.length; x++) {
			$("#cityTab").append("<tr><td>" + data.allCities[x].cid + "</td><td>" + data.allCities[x].title + "</td></tr>")
		}
	}, "json");

})

        以上已经完成了最基本的异步加载操作.

总结

        通过本程序可以发现如下需要注意的问题:

            ○路径的访问问题,使用完整路径;

            ○分发处理在Struts2.x中实现很轻松;

            ○乱码问题依然是一个头疼的东西,主要是因为Struts2.x使用过滤器处理.

猜你喜欢

转载自blog.csdn.net/qq1019648709/article/details/80571058