2009年12月16日 星期三

實作Ext Combobox form,Ajax Submit form


開發環境:
IDE:MyEclipse6.6GA
Web Server:Tomcat 6.0.20
Database:MySql 5.1.36
MVC:Struts2.1.8
FrameWork:Spring2.0,Hibernate3.2
Client UI:Ext2.3.0

此範例為學習combo box在Ext2.3.0之用法,其中combo box之資料來源分別有從資料庫及local兩種,
以及透過Ajax Submit form後接收回傳結果到前端!
一、建立Combo表單頁面(combo.jsp):
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<%

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>



<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

  <head>

    <base href="<%=basePath%>">

    

    <title>My JSP 'combox.jsp' starting page</title>

    

 <meta http-equiv="pragma" content="no-cache">

 <meta http-equiv="cache-control" content="no-cache">

 <meta http-equiv="expires" content="0">    

 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

 <meta http-equiv="description" content="This is my page">

 <!--

 <link rel="stylesheet" type="text/css" href="styles.css">

 -->

 <link rel="stylesheet" type="text/css" href="extjs/resources/css/ext-all.css">

 <link rel="stylesheet" type="text/css" href="css/onReady.css">

 <script type="text/javascript" src="extjs/adapter/ext/ext-base.js"></script>

 <script type="text/javascript" src="extjs/ext-all.js"></script>

 <script type="text/javascript" src="extjs/ext-lang-zh_TW.js"></script> 

 <script type="text/javascript">

 <!--

  Ext.onReady(function(){

   Ext.BLANK_IMAGE_URL='extjs/resources/images/default/s.gif';

   Ext.QuickTips.init();

   Ext.form.Field.prototype.msgTarget = 'side';

   var proxy=new Ext.data.HttpProxy({url:'SysMgrJson!getFunctionAll.action',method:'post'});

   //JsonReader

   var reader=new Ext.data.JsonReader({root:'results',

            totalProperty:'totals'},

     [

      {name: 'fnid', mapping: 'fnid'},

      {name: 'fnname',mapping:'fnname'},

      {name: 'fndesc',mapping:'fndesc'}   

     ]

   );

   //Store   

   var store=new Ext.data.Store({

     proxy:proxy,

     reader:reader

     });

   var functionCombo01 = new Ext.form.ComboBox({

    fieldLabel:'請選擇功能',

    hiddenName:'function01',

          store: store,

          valueField: 'fnid',

          displayField:'fnname',

          lazyRender:true,

          typeAhead: true,

          mode: 'remote',

          forceSelection: true,

          triggerAction: 'all',

          emptyText:'請選擇功能...',

          selectOnFocus:true

      });

      //store.load();

   var gradeCombo01 = new Ext.form.ComboBox({

    store:new Ext.data.SimpleStore({

       data : [["A"], ["B"], ["C"], ["D"],["E"]],

       fields: ['grade']

    }),

    hiddenName:'grade01',

    fieldLabel:'請選擇等級',

    emptyText:'請選擇等級...',

    triggerAction: 'all',

    minChars : 1,

    typeAhead: true,

    lazyRender:true,

    valueField: 'grade',

    displayField : 'grade',

    selectOnFocus:true,   

    mode : 'local'

   });      

   var comboForm = new Ext.form.FormPanel({

    renderTo:document.body,

    frame:true,

    title:'Simple Form',

    width:350,

    height:200,

    labelAlign:'left',

    bodyStyle:'padding:0px 0px 0',

    items:[functionCombo01,gradeCombo01],

    applyTo:'Simple_Form',

    buttons:[{text:'存檔',

        formBind:true,

        handler:function(){

         if(comboForm.getForm().isValid()){

          comboForm.getForm().submit({//Ajax Form submit作法

           url:'SysMgrJson!comboFormSubmit.action',

           waitMsg:'傳出資料',

           success:function(form,action){

            var result = action.result;

            Ext.Msg.alert('結果:',action.result.funcId+','+action.result.grade);

           },

           failure:function(form,action){

            if(action.failureType==Ext.form.Action.CONNECT_FAILURE){

             Ext.Msg.alert('Error','Status:'+action.response.status+':'+action.response.statusText);

            }

            if(action.failureType==Ext.form.Action.SERVER_INVALID){

             Ext.Msg.alert('Invalid',action.result.errormsg);

            }            

           }

          });

         }

        }},

        {text:'重置',handler:function(){

       comboForm.getForm().reset();

          }

        }

    ]

   });

  });  

 //-->

 </script>

  </head>

  

  <body>

  <div id="Simple_Form"></div>

  </body>

</html>


二、建立DAO及Action:
1.建立系統管理DAO(SysMgrDAO.java):
package com.dao.test;



import java.util.List;



public interface SysMgrDAO {

 public List findFunctionAll();

 public List findFunctionAll(final int start,final int limit);

 public int getFunctionTotalCount();

 public List findTitleAll();

 public List findTitleAll(final int start,final int limit);

 public int getTitleTotalCount();

}


2.建立系統管理DAO Implement(SysMgrDAOImpl.java):
package com.dao.impl.test;



import java.sql.SQLException;

import java.util.List;



import org.apache.commons.logging.Log;

import org.apache.commons.logging.LogFactory;

import org.hibernate.Hibernate;

import org.hibernate.HibernateException;

import org.hibernate.Session;

import org.hibernate.transform.Transformers;

import org.springframework.orm.hibernate3.HibernateCallback;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;



import com.bean.test.Function;

import com.bean.test.Title;

import com.dao.test.SysMgrDAO;



public class SysMgrDAOImpl extends HibernateDaoSupport implements SysMgrDAO {

 private static final Log log = LogFactory.getLog(SysMgrDAOImpl.class);



 public List findFunctionAll() {

  log.debug("finding tbl_function with native sql");

  Session session = this.getSession();

  try{

   String sql="select id as fnid,name as fnname,`desc` as fndesc from cmsdb.tbl_function";  

   List list =  session.createSQLQuery(sql)

        .addScalar("fnid")

        .addScalar("fnname")

        .addScalar("fndesc")

        .setResultTransformer(Transformers.aliasToBean(Function.class))

        .list();

   log.debug("find successful of tbl_function with native sql");

   return list;

  }catch(RuntimeException re){

   log.error("finded error of tbl_function with native sql",re);

   throw re;

  }finally{

   session.close();

  }  

 }



 public List findFunctionAll(final int start,final int limit) {

  log.debug("get paging of tbl_function with native sql");

  return this.getHibernateTemplate().executeFind(new HibernateCallback(){

   public Object doInHibernate(Session session) throws HibernateException, SQLException {

    Object obj = session.createSQLQuery("select id as fnid,name fnname,`desc` as fndesc from cmsdb.tbl_function")

      .addScalar("fnid")

      .addScalar("fnname")

      .addScalar("fndesc")

      .setResultTransformer(Transformers.aliasToBean(Function.class))

      .setFirstResult(start)

      .setMaxResults(limit)

      .list();

    log.debug("get paging of tbl_function with native sql successful");

    return obj;

   }

  }); 

 }



 public int getFunctionTotalCount() {

  log.debug("finding totalcount of tbl_function with native sql");

  Session session = this.getSession();

  try{

   String sql="select count(*) as count from cmsdb.tbl_function";  

   List list =  session.createSQLQuery(sql)

        .addScalar("count",Hibernate.INTEGER)

        .list();

   log.debug("find successful totalcount of tbl_function with native sql");

   return ((Integer)list.get(0)).intValue();

  }catch(RuntimeException re){

   log.error("finded error totalcount of tbl_function with native sql",re);

   throw re;

  }finally{

   session.close();

  }

 }



 public List findTitleAll() {

  log.debug("finding tbl_title with native sql");

  Session session = this.getSession();

  try{

   String sql="select id,name,`desc` from cmsdb.tbl_title";  

   List list =  session.createSQLQuery(sql)

        .setResultTransformer(Transformers.aliasToBean(Title.class))

        .list();

   log.debug("find successful of tbl_title with native sql");

   return list;

  }catch(RuntimeException re){

   log.error("finded error of tbl_title with native sql",re);

   throw re;

  }finally{

   session.close();

  }

 }



 public List findTitleAll(final int start, final int limit) {

  log.debug("get paging of tbl_title with native sql");

  return this.getHibernateTemplate().executeFind(new HibernateCallback(){

   public Object doInHibernate(Session session) throws HibernateException, SQLException {

    Object obj = session.createSQLQuery("select id as id,name as name,`desc` as `desc` from cmsdb.tbl_title")

      .addScalar("id")

      .addScalar("name")

      .addScalar("desc")

      .setResultTransformer(Transformers.aliasToBean(Title.class))

      .setFirstResult(start)

      .setMaxResults(limit)

      .list();

    log.debug("get paging of tbl_title with native sql successful");

    return obj;

   }

  }); 

 }



 public int getTitleTotalCount() {

  log.debug("finding totalcount of tbl_title with native sql");

  Session session = this.getSession();

  try{

   String sql="select count(*) as count from cmsdb.tbl_title";  

   List list =  session.createSQLQuery(sql)

        .addScalar("count",Hibernate.INTEGER)

        .list();

   log.debug("find successful totalcount of tbl_title with native sql");

   return ((Integer)list.get(0)).intValue();

  }catch(RuntimeException re){

   log.error("finded error totalcount of tbl_title with native sql",re);

   throw re;

  }finally{

   session.close();

  }

 }

 

}


3.建立系統管理Service(SysMgrService.java):
package com.service.test;



import java.util.List;



public interface SysMgrService {

 public List findFunctionAll();

 public List findFunctionAll(final int start,final int limit);

 public int getFunctionTotalCount();

 public List findTitleAll();

 public List findTitleAll(final int start,final int limit);

 public int getTitleTotalCount();

}


4.建立系統管理Service Implement(SysMgrServiceImpl.java):
package com.service.impl.test;



import java.util.List;



import com.dao.test.SysMgrDAO;

import com.service.test.SysMgrService;



public class SysMgrServiceImpl implements SysMgrService {

 private SysMgrDAO sysMgrDAO;

 

 

 public List findFunctionAll() {

  return this.sysMgrDAO.findFunctionAll();

 }



 public List findFunctionAll(int start, int limit) {

  return this.sysMgrDAO.findFunctionAll(start, limit);

 }



 public List findTitleAll() {

  return this.sysMgrDAO.findTitleAll();

 }



 public List findTitleAll(int start, int limit) {

  return this.sysMgrDAO.findTitleAll(start, limit);

 }



 public int getFunctionTotalCount() {

  return this.sysMgrDAO.getFunctionTotalCount();

 }



 public int getTitleTotalCount() {

  return this.sysMgrDAO.getTitleTotalCount();

 }



 public SysMgrDAO getSysMgrDAO() {

  return sysMgrDAO;

 }



 public void setSysMgrDAO(SysMgrDAO sysMgrDAO) {

  this.sysMgrDAO = sysMgrDAO;

 }

}


5.建立系統管理Action(SysMgrAction.java):
package com.action.test;



import java.util.List;



import net.sf.json.JSONArray;

import com.opensymphony.xwork2.ActionSupport;

import com.service.test.SysMgrService;





public class SysMgrAction extends ActionSupport {

 /**

  * 

  */

 private static final long serialVersionUID = 1L;

 private SysMgrService sysMgrService;

 private String jsonString;

 private int start;

 private int limit;

 private String function01;

 private String grade01;



 public String getFunction() throws Exception {

  //沒有分頁功能

  //List list = this.sysMgrService.findFunctionAll();

  

  //有分頁功能  

  String totals = String.valueOf(this.sysMgrService.getFunctionTotalCount());

  List list = this.sysMgrService.findFunctionAll(start, limit);

  JSONArray array = JSONArray.fromObject(list);

  this.jsonString = "{\"totals\":"+totals+",\"results\":"+array.toString()+"}";

  return "functoinJSON";

 }

 

 public String getFunctionAll() throws Exception {

  //沒有分頁功能

  List list = this.sysMgrService.findFunctionAll();

  String totals = String.valueOf(list.size());

  //有分頁功能  

  //String totals = String.valueOf(this.sysMgrService.getFunctionTotalCount());

  //List list = this.sysMgrService.findFunctionAll(start, limit);

  JSONArray array = JSONArray.fromObject(list);

  this.jsonString = "{\"totals\":"+totals+",\"results\":"+array.toString()+"}";

  return "functoinJSON";

 }

 

 public String getTitle() throws Exception {

  //沒有分頁功能

  //List list = this.sysMgrService.findTitleAll();

  

  //有分頁功能  

  String totals = String.valueOf(this.sysMgrService.getTitleTotalCount());

  List list = this.sysMgrService.findTitleAll(start, limit);

  JSONArray array = JSONArray.fromObject(list);

  this.jsonString = "{\"totals\":"+totals+",\"results\":"+array.toString()+"}";

  return "titleJSON";

 } 



 public String comboFormSubmit() throws Exception{

  this.jsonString = "{\"success\":\"true\",\"funcId\":\""+function01+"\",\"grade\":\""+grade01+"\"}";

  return "comboFormJSON";

 }

 

 public SysMgrService getSysMgrService() {

  return sysMgrService;

 }





 public void setSysMgrService(SysMgrService sysMgrService) {

  this.sysMgrService = sysMgrService;

 } 



 public String getJsonString() {

  return jsonString;

 }



 public void setJsonString(String jsonString) {

  this.jsonString = jsonString;

 }



 public int getStart() {

  return start;

 }



 public void setStart(int start) {

  this.start = start;

 }



 public int getLimit() {

  return limit;

 }



 public void setLimit(int limit) {

  this.limit = limit;

 }



 public String getFunction01() {

  return function01;

 }



 public void setFunction01(String function01) {

  this.function01 = function01;

 }



 public String getGrade01() {

  return grade01;

 }



 public void setGrade01(String grade01) {

  this.grade01 = grade01;

 }

}


6.建立comboFormJSON頁面(comboFormJSON.jsp):
<%@ page language="java" contentType="text/html; charset=UTF-8" import="java.util.*" pageEncoding="UTF-8"%>

<%@ taglib prefix="s" uri="/struts-tags"  %>

<s:property value="jsonString" escape="false"/>


7.於struts.xml(src目錄下)設定Struts2 Action:
<action name="SysMgrJson" class="SysMgrJsonAction">

<result name="functoinJSON">JsonJSP/functionJSON.jsp</result>

<result name="titleJSON">JsonJSP/titleJSON.jsp</result>

<result name="comboFormJSON">JsonJSP/comboFormJSON.jsp</result>   

</action>


8.於applicationContext.xml(WEB-INF目錄下)設定Struts2 Action:
<!-- DAO -->

<bean id="SysMgrDAO" class="com.dao.impl.test.SysMgrDAOImpl">

<property name="sessionFactory" ref="sessionFactory"></property>

</bean>


<!-- Service -->

<bean id="SysMgrService" class="com.service.impl.test.SysMgrServiceImpl">

<property name="sysMgrDAO" ref="SysMgrDAO"></property>

</bean>


<!-- Action -->

<bean id="SysMgrJsonAction" class="com.action.test.SysMgrAction" scope="prototype">

<property name="sysMgrService" ref="SysMgrService"></property>

</bean>


三、測試結果:
1.http://localhost:8080/ExtStudy/Basic/combo.jsp





看到此畫面,恭喜您整合開發環境設定成功!

沒有留言:

張貼留言