ssh+Ext開發CRUD功能

CRUD是指在做計算處理時的增加(Create)、查詢(Retrieve)(重新得到數據)、更新(Update)和刪除(Delete)幾個單詞的首字母簡寫。主要被用在描述軟件系統中數據庫或者持久層的基本操作功能。
  In computing, CRUD is an acronym for create, retrieve, update, and delete. It is used to refer to the basic functions of a database or persistence layer in a software system.
  C reate new records
  R etrieve existing records
  U pdate existing records
  D elete existing records.
 
 
 
入門:

各種開源框架環境及下載:

Hibernate3.x  http://www.hibernate.org/ 需要hibernate core annotations 包。

Spring2.x http://springframework.org/

Struts22.x http://struts.apache.org/2.x/

ExtJS2.X http://extjs.com/

JSONJSON可以到http://www.json.org/ 查看詳細內容,這裏使用json-lib http://json-lib.sourceforge.net/

本所需要的包:

 

 

 

2、  配置:

1)首先是配置web.xml,配置方法可以在下面的配置文件代碼註釋中查看,這裏主要是Struts2的配置:

    <filter>

        <filter-name>struts2</filter-name>

        <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>

    </filter>

    <filter-mapping>

        <filter-name>struts2</filter-name>

        <url-pattern>/*</url-pattern>

</filter-mapping>

Spring的配置:

 

    <context-param>

       <param-name>contextConfigLocation</param-name>

       <param-value>/WEB-INF/spring/*.xml</param-value>

</context-param>

    <listener>     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

</listener>

Web.xml的全部文件:

<?xml version="1.0" encoding="UTF-8"?>

<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

    <display-name>struts2</display-name>

    <!-- Spring ApplicationContext配置文件的路徑,可使用通配符*,多個路徑用,號分隔,此參數用於後面的Spring-Context loader -->

    <context-param>

 

        <param-name>contextConfigLocation</param-name>

        <param-value>/WEB-INF/spring/*.xml</param-value>   

    </context-param>

    <!-- 著名 Character Encoding filter -->

    <filter>

        <filter-name>encodingFilter</filter-name>

    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>

        <init-param>

            <param-name>encoding</param-name>

            <param-value>UTF-8</param-value>

        </init-param>

    </filter>

 

    <!-- struts2 濾鏡配置  -->

    <filter>

        <filter-name>struts2</filter-name>

        <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>

 

    </filter>

 

    <filter-mapping>

        <filter-name>struts2</filter-name>

        <url-pattern>/*</url-pattern>

    </filter-mapping>

    <!--Spring ApplicationContext 載入 ,必須-->

    <listener>  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

    </listener>

 

    <!-- Spring 刷新Introspector防止內存泄露 -->

    <listener>

    <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>

    </listener>

    <!-- session超時定義,單位爲分鐘 -->

    <session-config>

        <session-timeout>10</session-timeout>

 

    </session-config>

    <welcome-file-list>

        <welcome-file>index.html</welcome-file>

        <welcome-file>index.htm</welcome-file>

        <welcome-file>index.jsp</welcome-file>

        <welcome-file>default.html</welcome-file>

        <welcome-file>default.htm</welcome-file>

        <welcome-file>default.jsp</welcome-file>

    </welcome-file-list>

</web-app>

2Hibernate配置:

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-configuration PUBLIC

        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"

        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>

    <!—-數據庫驅動類名稱 -->

 

        <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>

    <!—-數據庫用戶名 -->

<property name="hibernate.connection.username">MY</property>

        <property name="hibernate.default_schema">MY</property>

    <!—-數據庫用戶密碼 -->

        <property name="hibernate.connection.password">MY</property>

    <!—-數據庫連接字符串-->

        <property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:loon</property>

        <property name="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</property>

    <!—-控制檯是否輸出SQL語句 -->

        <property name="hibernate.show_sql">true</property>

        <mapping class="privilege.database.Level" />

 

    </session-factory>

</hibernate-configuration>

3Spring基本配置:配置文件應該在WEB-INF/spring/下面

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans default-autowire="autodetect">

    <!—如果用的是XML配置文件,sessionFactory用這個配置 "org.springframework.orm.hibernate3.LocalSessionFactoryBean" -->

    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">

        <property name="configLocation">

            <value>classpath:hibernate.cfg.xml</value>

        </property>

        <!--   配置多個hibernate.cfg.xml

            <property name="configLocations">

            <list>

            <value>classpath:hibernate_admin1.cfg.xml</value>

            <value>classpath:hibernate_admin2.cfg.xml</value>

 

            </list>

            </property>

        -->

    </bean>

    <!-- Hibernate 事務管理  -->

    <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">

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

    </bean>

<bean id="baseTransactionProxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean" abstract="true">

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

        <property name="transactionAttributes">

            <props>

                <prop key="find*">PROPAGATION_REQUIRED,readOnly</prop>

                <prop key="persist*">PROPAGATION_REQUIRED,-Exception</prop>

 

                <prop key="remove*">PROPAGATION_REQUIRED,-Exception</prop>

                <!--

                    <prop key="insert*">PROPAGATION_REQUIRED</prop>

                    <prop key="save">PROPAGATION_REQUIRED</prop>

                    <prop key="update*">PROPAGATION_REQUIRED</prop>

                    <prop key="edit*">PROPAGATION_REQUIRED</prop>

                    <prop key="del*">PROPAGATION_REQUIRED</prop>

                    <prop key="get*">PROPAGATION_REQUIRED,readOnly</prop>

                    <prop key="query*">PROPAGATION_REQUIRED,readOnly</prop>

                    <prop key="disPlay*">PROPAGATION_REQUIRES_NEW</prop>

                -->

            </props>

        </property>

    </bean>

 

    <bean id="LevelService" parent="baseTransactionProxy">

        <property name="target">

            <bean class="privilege.service.LevelService">

                <property name="dao">

 

                    <bean class="privilege.dao.LevelDAO">

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

                    </bean>

                </property>

            </bean>

        </property>

    </bean>

    <bean id="LevelAction" class="privilege.action.LevelAction">

        <property name="levelService" ref="LevelService" />

    </bean>

 </beans>

4struts.xml文件的配置:

<!DOCTYPE struts PUBLIC  

        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"  

        "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

    <package name="privilege" extends="struts-default">

 

        <action name="LoadLevel" class="LevelAction" method="findLevelById">

            <result>/resource/json_struts2.jsp</result>

        </action>

        <action name="LevelAjaxJsonData" class="LevelAction" method="jsonExecute">

            <result>/resource/json_struts2.jsp</result>

        </action>

    </package>

</struts>

3、  建立的項目目錄:

Root

/resource/ext2.0/  將下載的ext-2.0-beta1.zip文件解壓到該目錄

/WEB-INF/web.xml

/WEB-INF/lib

/WEB-INF/classes/struts.xml

/WEB-INF/spring/applicationContext.xml

4、  代碼清單:

Level.java

 

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.Id;

import javax.persistence.Table;

 

 

@Entity

 

@Table(name = "LOON_LEVEL")

public class Level implements java.io.Serializable {

    private Long levelid;

    private String levelname;

    private String description;

 

    public Level() {

    }

 

    public Level(Long levelid) {

       this.levelid = levelid;

    }

 

    public Level(Long levelid, String levelname, String description) {

       this.levelid = levelid;

       this.levelname = levelname;

       this.description = description;

    }

 

    @Id

    @Column(name = "LEVELID", unique = true, nullable = false, precision = 5, scale = 0)

    public Long getLevelid() {

       return this.levelid;

 

    }

 

    public void setLevelid(Long levelid) {

       this.levelid = levelid;

    }

 

    @Column(name = "LEVELNAME", length = 64)

    public String getLevelname() {

       return this.levelname;

    }

 

    public void setLevelname(String levelname) {

       this.levelname = levelname;

    }

 

    @Column(name = "DESCRIPTION", length = 256)

    public String getDescription() {

       return this.description;

    }

 

    public void setDescription(String description) {

       this.description = description;

    }

}

 

ILevelDAO.java

 

import java.util.List;

public interface ILevelDAO {

 

    public Level findLevelById(Long id);

    public List<Level>  findAllLevels();

    public void persistLevel(Level level);

    public void removeLevel(Level level);

    public void removeById(Long id);

}

 

LevelDAO.java

 

import java.util.List;

import org.hibernate.Session;

import org.springframework.orm.hibernate3.HibernateCallback;

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

public class LevelDAO extends HibernateDaoSupport implements ILevelDAO {

    public LevelDAO() {

       super();

    }

    public Level findLevelById(Long id) {

       return (Level) getHibernateTemplate().get(Level.class, id);

    }

    public List<Level> findAllLevels() {

       return getHibernateTemplate().loadAll(Level.class);// .find("from Level o");//

    }

    public void persistLevel(Level level) {

       getHibernateTemplate().saveOrUpdate(level);

 

    }

    public void removeLevel(Level level) {

       getHibernateTemplate().delete(level);

    }

 

    public void removeById(final Long id) {

       this.getHibernateTemplate().execute(new HibernateCallback() {

           public Object doInHibernate(Session session) {

              session.createQuery("delete from Level o where o.levelid=" + id + "").executeUpdate();

              return 1;

           }

       });

    }

}

 

ILevelService.java

 

import java.util.List;

public interface ILevelService {

    public Level findLevelById(Long id) throws Exception;

    public List<Level> findAllLevels() throws Exception;

    public List<Level> findLevelsByExample(Level level) throws Exception;

    public void persistLevel(Level level) throws Exception;

    public void removeLevel(Level level) throws Exception;

 

public void removeLevelById(Long id) throws Exception;

}

 

LevelService.java

 

import java.util.List;

import privilege.dao.*;

import privilege.database.Level;

import org.springframework.context.ApplicationContext;

public class LevelService implements ILevelService {

    private ILevelDAO dao;

    private static final String SERVICE_BEAN_ID = "LevelService";

    public LevelService() {

       super();

    }

    public static ILevelService getInstance(ApplicationContext context) {

       return (ILevelService) context.getBean(SERVICE_BEAN_ID);

    }

    public Level findLevelById(Long id) throws Exception {

       try {

           return getDao().findLevelById(id);

       } catch (RuntimeException e) {

           throw new Exception("findLevelById failed with the id " + id + ": " + e.getMessage());

 

       }

    }

    public void persistLevel(Level level) throws Exception {

       try {

           getDao().persistLevel(level);

       } catch (RuntimeException e) {

           throw new Exception("persistLevel failed: " + e.getMessage());

       }

    }

    public void removeLevel(Level level) throws Exception {

       try {

           getDao().removeLevel(level);

       } catch (RuntimeException e) {

           throw new Exception("removeLevel failed: " + e.getMessage());

       }

    }

    public void removeLevelById(Long id) throws Exception {

       try {

           getDao().removeById(id);

       } catch (RuntimeException e) {

           throw new Exception("removeLevel failed: " + e.getMessage());

 

       }

    }

 

    public void setDao(ILevelDAO dao) {

       this.dao = dao;

    }

    public ILevelDAO getDao() {

       return this.dao;

    }

}

 

ExtJSONActionSuport.java

輔助類,繼承了ActionSupport

import com.opensymphony.xwork2.ActionSupport;

 

public class ExtJSONActionSuport extends ActionSupport {

    private int totalCount = 0;// 總數

    private transient int start = 0;// 開始數

    private transient int limit = 0;// 限制數量

    private String jsonString = "";

 

    public String getJsonString() {

       return jsonString;

 

    }

 

    public void setJsonString(String jsonString) {

       this.jsonString = jsonString;

    }

 

    public String jsonExecute() throws Exception {

       return super.execute();

    }

 

     

 

    public int getTotalCount() {

       return totalCount;

    }

 

    public void setTotalCount(int totalCount) {

       this.totalCount = totalCount;

    }

 

    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;

    }

}

 

 

LevelAction.java

 

import java.util.List;

import java.util.ArrayList;

import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import net.sf.json.JSONArray;

import privilege.database.Level;

import privilege.service.*;

import commons.utils.action.ExtJSONActionSuport;

 

public class LevelAction extends ExtJSONActionSuport {

    private static final long serialVersionUID = 1L;

    private Level level = null;

    private List<Level> levels = new ArrayList<Level>(0);

    private ILevelService levelService = null;

 

    private String delData;

 

    public String execute() {

       return this.SUCCESS;

    }

 

    @Override

    public String jsonExecute() throws Exception {

       if (this.getDelData() != null && !"".equals(this.getDelData())) {

           if (this.getDelData().indexOf(",") < 0) {

              this.levelService.removeLevelById(Long.parseLong(this.getDelData()));

               System.out.println("del_id:" + getDelData());

           } else {

              String id[] = this.getDelData().split(",");

              for (int i = 0; i < id.length; i++) {

                  System.out.println("del:" + id[i]);

                  this.levelService.removeLevelById(Long.parseLong(id[i]));

 

               }

           }

       }

       HttpSession session = ServletActionContext.getRequest().getSession();

       Object o = null;// session.getAttribute("Level_Data1");

       if (o == null) {

           try {

              this.levels = this.getLevelService().findAllLevels();

              session.setAttribute("Level_Data1", this.levels);

              System.out.println("query database");

           } catch (Exception e) {

              e.printStackTrace();

           }

       } else {

           this.setLevels(((List<Level>) o));

       }

       this.setTotalCount(this.levels.size());

       JSONArray array = JSONArray.fromObject(this.levels);

       // System.out.println(this.getStart() + "---" + this.getLimit());

       this.setJsonString("{success:true,totalCount : " + this.getTotalCount() + ", list:" + array.toString() + "}");

 

       // System.out.println(this.getJsonString());

       return super.jsonExecute();

    }

 

    /**

     * Find an entity by its id (primary key).

     *

     * @param id

     * @return The found entity instance or null if the entity does not exist.

     */

    public String findLevelById(Long id) {

       try {

           this.level = this.getLevelService().findLevelById(id);

       } catch (Exception e) {

           e.printStackTrace();

       }

       JSONArray array = JSONArray.fromObject(this.levels);

 

       this.setJsonString(array.toString());

       return SUCCESS;

    }

 

    public String findLevelById() {

       System.out.println(this.level.getLevelid());

       try {

           this.level = this.getLevelService().findLevelById(this.level.getLevelid());

       } catch (Exception e) {

           e.printStackTrace();

       }

       JSONArray array = JSONArray.fromObject(this.level);

       this.setJsonString(array.toString());

       this.setJsonString("{success:true,totalCount:1,list:" + array.toString() + "}");

       System.out.println(array.toString());

       return SUCCESS;

    }

 

    /**

     * @return Return all persistent instances of the <code>Level</code> entity.

 

     */

    public String getAllLevels() {

       try {

           this.levels = this.getLevelService().findAllLevels();

       } catch (Exception e) {

           e.printStackTrace();

       }

       return SUCCESS;

    }

 

 

    /**

     * Make the given instance managed and persistent.

     *

     * @return

     */

    public String persistLevel() {

       System.out.println(this.level.getLevelid() + "---" + this.level.getLevelname() + "---"

              + this.level.getDescription());

       this.setJsonString("{success:true}");

 

       try {

           this.getLevelService().persistLevel(this.getLevel());

       } catch (Exception e) {

           e.printStackTrace();

       }

       return SUCCESS;

    }

 

    /**

     * Remove the given persistent instance.

     *

     * @return

     */

    public String removeLevel() {

       try {

           this.getLevelService().removeLevel(this.getLevel());

       } catch (Exception e) {

           e.printStackTrace();

       }

       return SUCCESS;

    }

 

    /**

     * Remove an entity by its id (primary key). *

 

     *

     * @return

     */

    public String removeLevelById(Long id) {

       try {

           this.getLevelService().removeLevelById(id);

       } catch (Exception e) {

           e.printStackTrace();

       }

       return SUCCESS;

    }

 

    public Level getLevel() {

       return level;

    }

 

    public void setLevel(Level level) {

       this.level = level;

    }

 

    public List<Level> getLevels() {

       return levels;

    }

 

    public void setLevels(List<Level> levels) {

       this.levels = levels;

    }

 

 

    public ILevelService getLevelService() {

       return levelService;

    }

 

    public void setLevelService(ILevelService levelService) {

       this.levelService = levelService;

    }

 

    public String getDelData() {

       return delData;

    }

 

    public void setDelData(String delData) {

       this.delData = delData;

    }

}

配置spring,添加:

<bean id="LevelService" parent="baseTransactionProxy">

       <property name="target">

           <bean class="privilege.service.LevelService">

              <property name="dao">

                  <bean class="privilege.dao.LevelDAO">

 

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

                  </bean>

              </property>

           </bean>

       </property>

    </bean>

    <bean id="LevelAction" class="privilege.action.LevelAction">

       <property name="levelService" ref="LevelService" />

    </bean>

配置struts.xml:

添加操作配置:

<action name="AddLevel" class="LevelAction" method="persistLevel">

    <result>/resource/json_struts2.jsp</result>

</action>

修改時載入數據操作配置:

<action name="LoadLevel" class="LevelAction" method="findLevelById">

    <result>/resource/json_struts2.jsp</result>

</action>

列表查詢和刪除數據時操作配置:

<action name="LevelAjaxJsonData" class="LevelAction" method="jsonExecute">

    <result>/resource/json_struts2.jsp</result>

</action>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章