Java Web控制层发送Json对象数据(二)

来源:互联网 发布:淘宝卖家新手入门 编辑:程序博客网 时间:2024/06/02 03:21

Ext数据查询类表显示:

案例:学生管理系统,采用Ext中AJax异步获取数据库中数据并且展现在网页前端

1、客户端简单实现:

createWindow : function(){        var desktop = this.app.getDesktop();        var win = desktop.getWindow('test-win');        if(!win){        var sid = "";        var nn=[];            var studentid="";//            var adminid='';        var page = 20;//每页最多显示20//        var ad;var ds = new Ext.data.Store({autoLoad:true,pruneModifiedRecords : true,baseParams: {limit:page},proxy:new Ext.data.HttpProxy({url:'./'+OS_StudentCHAXU}),reader:new Ext.data.JsonReader({root:'root',totalProperty:'totalCount'},  [{name:'studentid'},{name:'studentname'},{name:'studentbir'},{name:'studentsex'}])//                listeners:{//                    'datachanged':function(){//                        Ext.getCmp("student_remove").setDisabled(true);//                        Ext.getCmp("student_modify").setDisabled(true);//                    }//                }});var sm = new Ext.grid.CheckboxSelectionModel({handleMouseDown : Ext.emptyFn,//一个空方法//加入一个事件监听listeners : {//当选中状态发生改变时触发selectionchange : function(selm) {//selm为SelectionModel监听if (selm.hasSelection()) {//如果有选中的行,返回trueif (selm.getCount() == 1) {//获取选中行总数nn = [];//返回被第一条被选中的记录Record,data描述了当前Record的数据,domain为其中一个字段keynn.push(selm.getSelected().data.studentid);Ext.getCmp("student_modify").setDisabled(false);studentid=selm.getSelected().data.studentid;} else {//返回所有选中记录Array var record = selm.getSelections();nn = [];for ( var i = 0; i < record.length; i++) {nn.push(record[i].data.studentid);}Ext.getCmp("student_modify").setDisabled(true);}//域移除按钮有效与否Ext.getCmp("student_remove").setDisabled(false);} else {Ext.getCmp("student_remove").setDisabled(true);Ext.getCmp("student_modify").setDisabled(true);}}}});var cm = new Ext.grid.ColumnModel([    new Ext.grid.RowNumberer(),sm,    {header: "学生ID", width: 70, sortable: true, dataIndex: 'studentid',hideable : false},    {header: "学生姓名", width: 70, sortable: true,dataIndex: 'studentname'},    {header: "出生年月",width:70,sortable: true,dataIndex: 'studentbir'},    {header: "性别",width:70,sortable: true,dataIndex: 'studentsex'}]);            String.prototype.endWith=function(str){              if(str==null||str==""||this.length==0||str.length>this.length)                   return false;                  if(this.substring(this.length-str.length)==str)                    return true;                  else                   return false;                 return true;              }                        win = desktop.createWindow({            id :'test-win',                title:'学生信息',                width:'50%',                height:450,                shim:false,                animCollapse:false,                constrain:true,                layout: 'fit',                items:                new Ext.grid.GridPanel({                border:false,                    bbar: new Ext.PagingToolbar({    pageSize: page,    store: ds,    displayInfo: true,    afterPageText: '/ {0}',beforePageText: '页',    firstText : "第一页",prevText : "上一页",// updatenextText : "下一页",lastText : "最后页",refreshText : "刷新",    displayMsg: '显示第 <em>{0}</em> 条到 <em>{1}</em> 条记录,一共 <em>{2}</em> 条',    emptyMsg: "没有记录"}),cm :cm,                    sm:sm,                    loadMask:{msg:"数据加载中...."},                    store:ds,                    viewConfig: {                        forceFit:true                    },


以上是一个简单显示界面,主要数据获取是在ds中通过

baseParams: {limit:page},

proxy:new Ext.data.HttpProxy({url:'./'+OS_StudentCHAXU}),

reader:new Ext.data.JsonReader({root:'root',totalProperty:'totalCount'}, [{name:'studentid'},{name:'studentname'},{name:'studentbir'},{name:'studentsex'}])

得到结果,然后进入OS_StudentCHAXU控制器处理查询并返回结果:

 

2、控制层、DAO层实现,下面是采用Spring注释来注册服务

bean对象:

package com.xiaoli.form;public class Student implements java.io.Serializable{private static final long serialVersionUID = 1L;private String studentid;private String studentname;private String studentbir;private String studentsex;//public Student(String studentid, String studentname,String studentbir,//String studentsex) {//super();//this.studentid = studentid;//this.studentname = studentname;//this.studentbir = studentbir;//this.studentsex = studentsex;//}public String getStudentid() {return studentid;}public void setStudentid(String studentid) {this.studentid = studentid;}public String getStudentname() {return studentname;}public void setStudentname(String studentname) {this.studentname = studentname;}public String getStudentbir() {return studentbir;}public void setStudentbir(String studentbir) {this.studentbir = studentbir;}public String getStudentsex() {return studentsex;}public void setStudentsex(String studentsex) {this.studentsex = studentsex;}}

控制层类:

package com.avcon.action.os;import java.sql.Connection;import java.sql.SQLException;import java.util.List;import java.util.Map;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.log4j.Logger;import org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.ui.ModelMap;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import com.avcon.dao.impl.StudentlistDaoImpl;import com.avcon.util.ActionUrlManage;import com.avcon.util.BeanConverter;import com.avcon.util.ConnManager;import com.avcon.util.Function;import com.avcon.util.MessageResolver;import com.avcon.util.RequestUtils;import com.avcon.util.ResponseUtils;import com.avcon.form.OrgList;import com.avcon.form.Student;import com.avcon.form.SysAdmin;/** * Test 学生管理 * @author fish * */@Controllerpublic class TestAction {@AutowiredStudentlistDaoImpl sldi;static Logger log=Logger.getLogger(TestAction.class);    @RequestMapping(value=ActionUrlManage.OS_StudentCHAXU,method= RequestMethod.POST)    public void QueryAll(HttpServletRequest r,HttpServletResponse rp,ModelMap model){    try {    int start = 0;    String query=r.getParameter("query");    String where="";    if(query==null)where=" 1=1 ";    else{    query=query.trim();    where =" s.studentid like '%"+query+"%' or s.student like '%"+Function.PageToDb(query)+"'%";    }    if(r.getParameter("start") == null){    model.addAttribute("start", 0);    }else{    start =  Integer.parseInt(r.getParameter("start"));    }    int limit = Integer.parseInt(r.getParameter("limit"));    List<Student> list=sldi.getAll(start,limit,where);    int num = Function.cwhere("studentid","sys_student_test o",where);    JSONObject json = new JSONObject();    JSONArray arr = new JSONArray();    System.out.println("-------------"+num);for (Student s : list) {arr.put(new JSONObject(s));}json.put("root", arr);json.append("totalCount", num);ResponseUtils.renderJson(rp,json.toString());} catch (JSONException e) {log.error(e.getMessage(),e);}catch (Exception e){log.error(e.getMessage(),e);}    }
}


以上的StudentlistDaoImpl是服务层处理类,也就是数据访问层,得到的数据对象数组都转换为一个JSONObject,再将其置于JSONArray中,最后返回给客服端的数据依然还是将上面的数据打包为JSONObject并转换为String返回。

下面是显示效果:


 

原创粉丝点击