项目用到,简单记录下使用方法:
1.项目中要引入struts2-json-plugin.jar包
2.到Project Structure - Facets - Struts2 - File sets - Default File Set 增加 jar 包内的 struts-plugin.xml
3.在Action类中加入如下代码:
package com.action; import com.biz.IUserBiz; import com.entity.UserEntity; import com.opensymphony.xwork2.ActionSupport; import java.util.List; import java.util.HashMap; import java.util.Map; public class MapUserAction extends ActionSupport{ private String loginName; private String loginPwd; //将会被Struts2序列化为JSON字符串的对象,必须有该属性的getter方法 private Map<String, Object> dataMap; /* 构造方法 */ public MapUserAction() { dataMap = new HashMap<>(); //初始化Map对象 } public Map<String, Object> getDataMap() { return dataMap; } public void setLoginName(String loginName){ this.loginName = loginName; } public void setLoginPwd(String loginPwd){ this.loginPwd = loginPwd; } private IUserBiz userBiz; public void setUserBiz(IUserBiz userBiz){ this.userBiz = userBiz; } /** 测试通过action以Struts2默认方式返回JSON数据 **/ public String MapToJSON() throws Exception { List list = userBiz.login(loginName,loginPwd); if(list.size()>0){ UserEntity user = (UserEntity)list.iterator().next(); // dataMap中的数据将会被Struts2转换成JSON字符串,所以这里要先清空其中的数据 dataMap.clear(); dataMap.put("ID",user.getId()); dataMap.put("Account",user.getAccount()); dataMap.put("Name",user.getName()); dataMap.put("Phone",user.getPhone()); dataMap.put("Type",user.getType()); if(user.getCarListByCar()!= null){ dataMap.put("CarID",user.getCarListByCar().getCarId()); dataMap.put("CarNum",user.getCarListByCar().getCarNum()); dataMap.put("CarName",user.getCarListByCar().getCarName()); dataMap.put("CarModel",user.getCarListByCar().getCarModel()); dataMap.put("CarStatus",user.getCarListByCar().getCarStatus()); } dataMap.put("loginStatus","True"); return SUCCESS; }else { dataMap.clear(); dataMap.put("loginStatus","False"); return SUCCESS; } } }
4.接下来配置Spring-config.xml
<bean id ="userDao" class="com.dao.UserDaoImpl"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <bean id = "userBiz" class="com.biz.UserBiz"> <property name="userDao" ref="userDao"/> </bean> <bean id="mapAction" class="com.action.MapUserAction" scope="prototype"> <property name="userBiz" ref="userBiz"/> </bean>
5.下面配置Struts.xml
<package name="json" extends="json-default" namespace="/Test"><action name="MapTest" class="mapAction" method="MapToJSON"> <result type="json"><!--默认序列化返回所有getter方法--> <param name="root">dataMap</param><!-- root 返回 dataMap 注释掉将返回全部 --><!--<param name="excludeNullProperties">true</param>--> <!--<param name="excludeProperties">loginPwd</param>--></result></action>
</package>