struts2后台接口接收json数据

情景:最近接手了一个控制器为Struts2的项目,struts2之前没用过,在接口接收json参数时,出现了些问题,解决后记录一下。

问题:我使用是下面方法中加@RequestBody Judgesticket judgesticket进行接收,但是会报找不到类方法错误。

最后一查,发现struts2中Action不支持,然后在网上找了不少,最后解决如下:

[1]传递数据

{
    "judgesID":"2225",
    "screeningsID":"20190312164409",
    "exhWorksIDs":["1178",  "1179","1180","1181"]
}

 

[2]获取请求的数据


import com.opensymphony.xwork2.ActionContext;
import org.apache.struts2.ServletActionContext;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * Created by LQ on 2019/3/21. 接收json数据之前,获取请求体中的数据
 */
public class StrResponse {

    //获取请求体中的数据
    public static String getStrResponse(){
        ActionContext ctx = ActionContext.getContext();
        HttpServletRequest request = (HttpServletRequest)ctx.get(ServletActionContext.HTTP_REQUEST);
        InputStream inputStream;
        String strResponse = "";
        try {
            inputStream = request.getInputStream();
            String strMessage = "";
            BufferedReader reader;
            reader = new BufferedReader(new InputStreamReader(inputStream,"utf-8"));
            while ((strMessage = reader.readLine()) != null) {
                strResponse += strMessage;
            }
            reader.close();
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return strResponse;
    }

}

[3]获取json数据

public String workVote()throws Exception{
		HttpServletResponse response = (HttpServletResponse)                     
        ServletActionContext.getResponse();
		response.setContentType("text/json");
		response.setCharacterEncoding("UTF-8");
		//获取请求体中的数据
		JSONObject jsonRequest = JSONObject.fromObject(StrResponse.getStrResponse());
		Long judid=jsonRequest.getLong("judgesID");
		Long scrid=jsonRequest.getLong("screeningsID");
		List<String> exhWorksIDs=jsonRequest.getJSONArray("exhWorksIDs");
        ...省略
        return null;
}

OK 这次就到这里了

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值