struts2-通过action从后台将json数据传到前台的方法(二)

本方法是在后台将数据转成json数据再传回页面。

需要的jar包:

1.commons-beanutils-1.7.jar

2.commons-collections-3.2.1.jar

3.commons-lang-2.4.jar

4.commons-logging-1.0.4.jar

5.ezmorph-1.0.4.jar

前台jsp页面:

<table id="dg" title="My Users" class="easyui-datagrid" style="width:700px;height:250px"
       url="get_user01"
       toolbar="#toolbar" pagination="true"
       rownumbers="true" fitColumns="true" singleSelect="true">
  <thead>
  <tr>
    <th field="firstname" width="50">First Name</th>
    <th field="lastname" width="50">Last Name</th>
    <th field="phone" width="50">Phone</th>
    <th field="email" width="50">Email</th>
  </tr>
  </thead>
</table>
其中url是action。URL的返回值必须是json类型。

struts.xml配置文件

<package name="a" extends="struts-default">    
        <action name="get_user01" class="com.action.SyohinGetAction" method="write">
        </action>
</package>
后台部分代码:

public void write() throws IOException {
    HttpServletResponse response= ServletActionContext.getResponse();
/*
 * 在调用getWriter之前未设置编码(既调用setContentType或者setCharacterEncoding方法设置编码),
 * HttpServletResponse则会返回一个用默认的编码(既ISO-8859-1)编码的PrintWriter实例。这样就会
 * 造成中文乱码。而且设置编码时必须在调用getWriter之前设置,不然是无效的。
 * */
    response.setContentType("text/html;charset=utf-8");
    //response.setCharacterEncoding("UTF-8");
    PrintWriter out = response.getWriter();
    //JSON在传递过程中是普通字符串形式传递的,这里简单拼接一个做测试
    Dao dao=new Dao();
    list=dao.getHin();
    result = JSONArray.fromObject(list).toString();
    String jsonString = result;
    out.println(jsonString);
    out.flush();
    out.close();
}
这种方法不需要返回视图。

直接通过response对象将json数据传到页面。

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值