struts2和ajax整合

          最近搭建SSH环境,想通过ajax技术进行前后台交互,但是发现struts2的result虽然支持类型比较多,但是却没有ajax适合的。于是,在网上翻了半天资料。闲话少说,直接上代码。


问题:

         通过ajax访问action,value stack中没有任何的数据。原因未知,可能是因为ajax请求跟普通的http请求还是有区别的,不会把所有的信息都返回回来吧。如果有知道的,欢迎告诉我啊!!


解决方案:

1.将需要返回的信息封装到request\session中。
2.将返回的信息通过json的格式返回。这里主要说一下第二种。


解决步骤:

1. 引入struts2-spring-plugin包

                <dependency>
			<groupId>org.apache.struts</groupId>
			<artifactId>struts2-spring-plugin</artifactId>
			<version>${struts2.version}</version>
		</dependency>
2. struts中配置
 <result name="success" type="json"></result>

       在实验的过程中发现,如果action中有多个属性,如User user,String str...等,返回的json字符串并不完全,只是其中一个的。如:

 

private Material material;
private String str;
返回的json串为{'name':'11','code':'22'...}。即只是把material这个属性给转换为json字符串了,而str丢失了。
这个问题的解决方案:把所有方案整合到一个map中。
           
private Map<String, Object> resultMap = new HashMap<String, Object>();
 /**
  * @return the resultMap
  */
 public Map<String, Object> getResultMap() {
  return resultMap;
 }
 /**
  * @param resultMap
  * the resultMap to set
  */
 public void setResultMap(Map<String, Object> resultMap) {
  this.resultMap = resultMap;
 }

然后让struts将resultMap转换为json,需要配置如下

 <result name="success" type="json">
	 <param name="root">resultMap</param>
</result>


3. 通过interceptor处理resultMap(当然这一步可以省略,如果你不嫌麻烦,每个action中的方法都多resultmap处理)

@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		
		String msg = Action.SUCCESS;
		// 对所有的方法进行拦截,并把结果放到resultMap中
		Object action = invocation.getAction();
		Method getMethod = action.getClass().getMethod("getResultMap");
		@SuppressWarnings("unchecked")
		Map<String,Object> resultMap = (Map<String, Object>) getMethod.invoke(action);
		try{
			resultMap.put("result", Action.SUCCESS); // 这个必须得写在invoke之前
			msg = invocation.invoke();
		}catch(Exception e){
			resultMap.put("result", Action.ERROR);
			resultMap.put("message", e.getMessage());
		}
		
		Method setMethod = action.getClass().getMethod("setResultMap", Map.class);
		setMethod.invoke(action, resultMap);
		return msg;
	}

这里遇到一个问题,弄了半天------到现在也没搞明白,估计跟action的new时机以及其属性的创建时机有关系,有知道的请指教啊
resultMap.put("result", Action.SUCCESS); // 这个必须得写在invoke之前


如果大家对struts2和ajax的整合有更好的方式,欢迎指出啦。




参考:http://blog.csdn.net/zhqingyun163/article/details/5208766

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值