1. 程式人生 > >Java Web控制層傳送Json物件資料(二)

Java Web控制層傳送Json物件資料(二)

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()) {//如果有選中的行,返回true
							if (selm.getCount() == 1) {//獲取選中行總數
								nn = [];
								//返回被第一條被選中的記錄Record,data描述了當前Record的資料,domain為其中一個欄位key
								nn.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 : "上一頁",// update
						nextText : "下一頁",
						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
 *
 */

@Controller
public class TestAction {
	@Autowired
	StudentlistDaoImpl 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返回。

下面是顯示效果: