IDEA中通过Map返回JSON字符串

项目用到,简单记录下使用方法:

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, Object> dataMap;
    /* 构造方法 */
    public MapUserAction() {
        dataMap = new HashMap<>();    //初始化Map对象
    }
    public Map, 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
    id ="userDao" class="com.dao.UserDaoImpl">
        name="sessionFactory" ref="sessionFactory"/>
    

    id = "userBiz" class="com.biz.UserBiz">
        name="userDao" ref="userDao"/>
    

    id="mapAction" class="com.action.MapUserAction" scope="prototype">
        name="userBiz" ref="userBiz"/>
    
5.下面配置Struts.xml
name="json" extends="json-default" namespace="/Test">
    name="MapTest" class="mapAction" method="MapToJSON">
        type="json">
            name="root">dataMap
	    
	    
    

你可能感兴趣的:(IDEA中通过Map返回JSON字符串)