1. 程式人生 > >SSH框架Action中JSON操作及struct.xml配置

SSH框架Action中JSON操作及struct.xml配置

頁面向action中傳送AJAX、json請求前面已經講過了,這裡不再重複,今天主要講一下後臺如何處理並返回json資料。

方式不唯一,會用其中一種就可以,我用的是Map

首先action中建立map物件

	private Map result;//用於返回AJAX

	public Map getResult() {
		return result;
	}

	public void setResult(Map result) {
		this.result = result;
	}

在需要返回的處理方法中填充map,map中可以放入String,boolean,實體物件等。其中editEdutype為物件
				map.put("result",true);
//				map.put("edutypid",editEdutype.getEdutypid());
//				map.put("edutypename", editEdutype.getEdutypename());
//				map.put("edutypecharcter", editEdutype.getEdutypecharcter());
//				map.put("edutypedesc", editEdutype.getEdutypedesc());
//				map.put("status", editEdutype.getStatus());
				map.put("editEdutype", editEdutype);

然後在structs.xml中配置

首先,package要繼承json-default

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

然後配置action
<action name="user_*" class="newEmployeeAction" method="{1}">
		<result name="ajaxlistSUCCESS" type="json">
			<param name="root">result</param>
		</result>
</action>


最後在jsp中呼叫返回的json

 success: function(data) {  
	                  if(true == data.result){
	                  	var edutypID = data.edutypid
	                  	//alert(edutypID);
	                  	//document.getElementById("picUserID").value=userID; 
	                  	alert("儲存成功");
	                  	
	                  	var url = "edutype_pagelist.action";
          				// alert("url為:" + url);
          				window.location.href=url;
	                  } else {
	                  	
	                  	alert("儲存失敗");
	                  
	                  }