情景:最近接手了一个控制器为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 这次就到这里了