本方法是在后台将数据转成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数据传到页面。