讓JSON請求和引數請求一樣,可以通過Struts2的模型驅動給Action的類成員變數賦值(欄位驅動與模型驅動)
自己定義一個攔截器:
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.soumall.admin.utils.JsonUtils;
import java.util.HashMap;
import java.util.Map;
public class JSONParamReadInterceptor extends AbstractInterceptor {
private static final String jsonParamData = "jsonRequestParameter";
@Override
public String intercept(ActionInvocation invocation) throws Exception {
ActionContext ctx = ActionContext.getContext();
Map<String,Object> requestParam = ctx.getParameters();
boolean excuteFlag = false;
if(requestParam!=null){
String[] jsonParamObj = (String[])requestParam.get(jsonParamData);
if(jsonParamObj!=null && jsonParamObj.length>0){
String jsonParamObjStr = (String)(jsonParamObj[0]);
requestParam = JsonUtils.json2Map(jsonParamObjStr,requestParam,null,null);
if(requestParam!=null && requestParam.size()>0){
excuteFlag = true;
for(Object key : requestParam.keySet()){
System.out.print(" key: "+key);
System.out.println(" value: "+requestParam.get(key));
}
}
}
}
if(!excuteFlag ){
System.out.println("No JSON Paramter Or JSON paramter's name have error");
}
return invocation.invoke();
}
}
/**
* 把JSONObject中的資料填充到Map中.
*
* @param <T> Object
* @param jsonObjectStr json字串
* @param entity 需要填充資料的node
* @param excludes 不需要轉換的屬性陣列
* @param datePattern 日期轉換模式
* @return T
* @throws Exception java.lang.InstantiationException,
* java.beans.IntrospectionException,
* java.lang.IllegalAccessException
*/
public static Map<String,Object> json2Map(String jsonObjectStr,
Map<String,Object> map, String[] excludes, String datePattern)
throws Exception {
JSONObject jsonObject = JSONObject.fromObject(jsonObjectStr);
// JsonUtils.configJson(excludes, datePattern);
Set<String> excludeSet = createExcludeSet(excludes);
for (Object object : jsonObject.entrySet()) {
Map.Entry entry = (Map.Entry) object;
String propertyName = entry.getKey().toString();
if (excludeSet.contains(propertyName)) {
continue;
}
String propertyValue = entry.getValue().toString();
map.put(propertyName, propertyValue);
}
return map;
}
2,修改配置檔案struts-default.xml <!-- JSON parm Driver--> <interceptor name="jsonParamDriven" class="com.soumall.admin.interceptor.JSONParamReadInterceptor"/> <!-- JSON parm Driver--> <interceptor-ref name="jsonParamDriven"/>