Struts2框架接受/返回json數據

Struts接口可以從流中接受json數據並解析,並以流的形式返回給前端。如下所示:

public class testController extends ActionSupport{
    private InputStream inputStream; 

    private String getRequestPostData(HttpServletRequest request) throws IOException {
     //解析請求的Json數據
       int contentLength = request.getContentLength();
       if(contentLength<0){
          return null;
       }
       byte buffer[] = new byte[contentLength];
       for (int i = 0; i < contentLength;) {
           int len = request.getInputStream().read(buffer, i, contentLength - i);
           if (len == -1) {
               break;
           }
           i += len;
       }
        //return new String(buffer, "utf-8");
        String data=new String(buffer,"utf-8");

        //返回json,struts.xml文件也要一致
        try{
            inputStream=new ByteArrayInputStream(data.getBytes("UTF-8"));
        }catch(unsupportedEncodingException e){
            e.printStackTrace();
        }
    }
}

另外,Struts2框架還可以通過使用struts2-json-plugin配置,實現json數據的接受與返回。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章