Struts2中如何接收另一个action 或者JSP页面经过POST方法传过来的字符串

经验总结:

最近在用struts2 写接口,要给请求者返回一个json字符串,但是,请求是用POST请求的,各种方法尝试,最后终于得到了答案:

/**
     * 封装接收客户端传过来的post数据
     * @param ctx ActionContext的对象 
     * @return
     */
    public static String getRequestBody(ActionContext ctx){
        try {
            HttpServletRequest request = (HttpServletRequest)ctx.get(ServletActionContext.HTTP_REQUEST);
            InputStream inputStream = request.getInputStream();
            String strMessage = "";
            StringBuffer buff = new StringBuffer();
            BufferedReader bufferReader = new BufferedReader(new InputStreamReader(inputStream,"utf-8")); 
            while((strMessage = bufferReader.readLine()) != null){
                buff.append(strMessage);
            }
            bufferReader.close();
            inputStream.close();
            return buff.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

经过这个方法后,在另一个需要使用到POST的json的时候,只需要

ActionContext ctx = ActionContext.getContext();
String json = getRequestBody(ctx);

上面那个json就是POST中的json数据.

原文地址:https://www.cnblogs.com/llynic/p/6613515.html