輕松

          記述我學習java的里程

          常用鏈接

          統計

          積分與排名

          友情鏈接

          最新評論

          Hibernate+Struts應用程序的JavaWebStudio 2005下快速、可視化開發 (轉)

          Hibernate+Struts應用程序的JavaWebStudio 2005下快速、可視化開發


          Struts中文論壇:http://www.javawebstudio.com/
          JavaWebStudio 2005下載地址:http://www.javawebstudio.com/bbs/dispbbs.asp?boardID=5&ID=3&page=1

           

           

          [目標]

          本例的目標是實現一個簡單的Struts 數據庫應用程序。其功能是從SQL Server 2000中讀取數據,并以表格的形式在輸出頁中顯示出來。

          定義一個名為“Test”表的字段:

          錄入一些測試數據:

            

          [效果]

          (1)全部顯示:

          輸入頁面:

          輸出頁面:

           

          (2)查詢顯示:

           

          [背景知識]

           

           

          [步驟]

           

          1、打開Visual Struts開發環境:

          從桌面JavaWebStudio快揵或BIN目錄下的JavaWebStudio.exe文件啟動JavaWebStudioVisual Struts開發環境。

           

          2、建立一個“空的Hibernate_Struts項目模板”應用程序:

              選擇菜單“文件”“新建”“新建項目”,彈出新建項目對話框,如圖3-1所示:

           

          在對話框中選擇“空的Struts數據庫應用模板”,在項目名稱中輸入“MyHibernate”,package (包名)和位置(項目的路徑)采用默認的值就行,當然也可以根據需要改變。最后點擊“確定”按鈕完成新項目的建立。

           

          從文件管理器中可看出MyHibernate項目的文件結構如下:

          MyHibernate項目根目錄下包含四個子目錄和兩個文件,這是JavaWebStudio項目的標準結構,最好不要改變它們默認的名稱,否則會出現問題。

           

          3、利用Struts數據庫應用文件向導建立新的應用:

          JavaWebStudio文件管理器內點擊鼠標右鍵,在彈出的菜單中選擇“HibernateHibernate_Struts文件向導”進入Struts文件向導對話框,也可以選擇菜單“文件向導” Hibernate_Struts文件向導”進入Hibernate文件向導對話框。如下圖所示:

          1)輸入文件名:

          2)從數據源中導入SQL語句及數據表的字段信息(字段名和字段類型):

           

          3)從數據據表中選擇所需的表“Test”。

          需要特別注意的是,這里的“從數據源中導入SQL語句及數據表的字段信息”及“從數據據表中選擇所需的表”僅僅是為了自動生成SQL語句及讀取字段信息,這里完成可以直接手工輸入,與該項目的數據庫連接池的配置無關,下面第(4)點將另行配置數據庫連接池。

           

          DAO文件、輸入JSP文件、ActionForm文件、Action文件等選擇默認就行了,主要是設置一下JSPOut文件,讓它自動分頁、每頁顯示4條記錄,選擇刪除、編輯、鏈接和添加新記錄功能。

           

          接下來配置數據庫連接池,其它屬性頁可采用默認的就行了,下面直接轉去數據連接配置屬性頁即可。

          (4)配置數據庫連接池:

           

          這里要特別注意的是Hibernate的數據庫連接池配置文件是Hibernate.properties,并且dialect類名是org.hibernate.dialect.SQLServerDialect

           

          4、項目文件結構

           

          項目目錄結構分析見如何實現最簡單的Struts程序,這次Hibernate文件向導自動生成了八個文件,其中web目錄下是輸入、輸出兩個JSP文件,src目錄下是Java文件。除了文件名是我們輸入之外,所有程序源代碼都是文件向導自動生成的,所有的配置也是自動完成的。

          刷新JavaWebStudio文件管理器,這時發現web目錄下自動生成了兩個文件,分別是Test.jsp.jspTestInsert.jspTestOut.jsp.jsp,分別是查詢條件輸入JSP文件、新記錄添加JSP文件和表格輸出JSP文件;src\emptyprj目錄下自動生成了五個文件,分別是TestAction.javaTestForm.java,前者是Action文件,后者是FormAction文件;還有是數據庫操作文件Test.javaTestDAO.java,前者用于保存數據表記錄的Bean,后者是數據庫操作DAO文件;還要特別注意的是還有一個xml文件,就是Test.hbm.xml,用于Hibernate對象與數據庫的映射。

           

          Test.jsp文件:

           

          TestInsert.jsp文件:

           

          TestOut.jsp文件:

           

           

          5、編譯、啟動服務器、運行:

            通過工具條上的按鍵分別編譯項目及啟動服務器,然后把開Test.jsp并通過工具條上的“運行”按鍵運行Test.jsp

          這里將采用調試狀態下的運行方式:

          (1)       顯示調試工具條:

           

          注:單步執行可跟蹤進原函數執行;單過程執行按語句跟蹤,一般選擇單過程執行即可。

           

          2)選擇調試狀態下的“編譯”:

          輸出欄中輸出如下提示信息:

          C:\Documents and Settings\Administrator\桌面>F:

          F:\>cd F:\JavaWebStudio\JavaWebStudioWorkDir\MyHibernate

          F:\JavaWebStudio\JavaWebStudioWorkDir\MyHibernate>ant -buildfile build.xml

          Buildfile: build.xml

          prepare:

               [copy] Copying 1 file to F:\JavaWebStudio\jakarta-tomcat-5.5.4\webapps\MyHibernate\WEB-INF\classes

          compile:

              [javac] Compiling 5 source files to F:\JavaWebStudio\jakarta-tomcat-5.5.4\webapps\MyHibernate\WEB-INF\classes

              [javac] F:\JavaWebStudio\JavaWebStudioWorkDir\MyHibernate\src\emptyprj\TestAction.java:68: setUserID(int) in emptyprj.Test cannot be applied to (java.lang.String)

              [javac]                  m_Test.setUserID(expression);

              [javac]                        ^

              [javac] 1 error

          BUILD FAILED

          F:\JavaWebStudio\JavaWebStudioWorkDir\MyHibernate\build.xml:34: Compile failed; see the compiler error output for details.

          Total time: 9 seconds

          出現一個錯誤,原因是因為前面我們設置userID為整數類型,而這里的expression是字符串類型,所以要修改一下TestAction.java文件:

          package  emptyprj;

           

           

          import emptyprj.TestDAO;

           

          import java.lang.reflect.InvocationTargetException;

          import java.util.Locale;

          import javax.servlet.ServletException;

          import javax.servlet.http.HttpSession;

          import javax.servlet.http.HttpServletRequest;

          import javax.servlet.http.HttpServletResponse;

          import org.apache.commons.beanutils.PropertyUtils;

          import org.apache.commons.logging.Log;

          import org.apache.commons.logging.LogFactory;

          import org.apache.struts.action.Action;

          import org.apache.struts.action.ActionError;

          import org.apache.struts.action.ActionErrors;

          import org.apache.struts.action.ActionForm;

          import org.apache.struts.action.ActionForward;

          import org.apache.struts.action.ActionMapping;

          import org.apache.struts.action.ActionServlet;

          import org.apache.struts.util.ModuleException;

          import org.apache.struts.util.MessageResources;

           

          import java.io.IOException;

          import java.sql.Connection;

          import java.sql.SQLException;

          import java.util.Collection;

           

          public final class TestAction extends Action

          {

              // 變量定義:

              private Log log = LogFactory.getLog("org.apache.struts.webapp.Example");

              public TestAction() {

                

              }

           

           

              //函數定義:

              public ActionForward execute(ActionMapping mapping,

                                       ActionForm form,

                                       HttpServletRequest request,

                                       HttpServletResponse response)

                 throws Exception

              {

                 // Extract attributes and parameters we will need

                 Locale locale = getLocale(request);

                 MessageResources messages = getResources(request);

                 HttpSession session = request.getSession();

                 TestForm m_TestForm = (TestForm) form;

                

                          TestDAO m_TestDAO = TestDAO.getInstance();  //定義Hibernate__DAO對象,用于實現數據庫的各種操作

           

                          String action=request.getParameter("action");  //動作類型                 

                          String search=request.getParameter("search");  //數據庫查找方式

                          String expression=request.getParameter("expression");    //參數,這里用于保存記錄(行)的ID數據

                         

                          if(action==null)action="find";

                        if(search==null)search="UNsearch";

                        if(expression==null)expression="";

                        expression=toChinese(expression);  //處理中文問題,實現編碼轉換

                       

                      /////////

                        if("delete".equals(action))    //刪除記錄操作 

                      {

                           Test m_Test= new Test();

                           //<delete>

                           m_Test.setUserID(expression);

                           //</delete>             

                             m_TestDAO.removeID(m_Test);

                       }

           

                      ////////////

                       if("update".equals(action)||"insert".equals(action))    //更新、添加記錄操作

                       {

                           Test m_Test= new Test();

                               //<update>

                             m_Test.setUserID(m_TestForm.getUserID());

                             m_Test.setUsername(m_TestForm.getUsername());

                             m_Test.setPassword(m_TestForm.getPassword());

                             m_Test.setRole(m_TestForm.getRole());

                             //</update>

                              if("update".equals(action))    //調用DAO對象更新記錄

                                       m_TestDAO.update(m_Test,expression);

                              if("insert".equals(action))    //調用DAO對象添加記錄

                                   m_TestDAO.create(m_Test);

                                        

                       }

                         

                        ///////////////HQL_查找數據庫

                        String sql="from emptyprj.Test Test";

                      

                        ////SQL字符處理,主要是加入查詢條件,如果是全部顯示,可把這部分代碼刪除。

                          if("search".equals(search))

                          {

                            String selectsql;

                              //<search>

                                 sql+=" where ";

                               sql+="userID";

                               sql+="=";

                               if("NULL".equals(expression)||"".equals(expression))

                              {

                                     sql+=m_TestForm .getUserID();

                                 }

                                 else

                                 {

                                     sql+=expression;

                                 }

                                 

                                 sql+="";

                              //</search>

                          }

           

                       //<分頁>

                          m_TestDAO.setLength(4);//設置每頁顯示記錄數

                          int ipage;//當前頁

                          try

                          {

                              String page=request.getParameter("page");//分頁參數,讀取請求的當前頁

                              ipage=java.lang.Integer.parseInt(page,10);

                          }

                          catch (Exception e)

                       {

                           ipage=m_TestForm.getPage();

                       }

                       if(ipage<1)ipage=1;

                       Collection col = m_TestDAO.findSQL("select Test "+sql,"select count(Test) "+sql,ipage);//通過DAO對象查詢數據

                          request.setAttribute("Test",col);  //保存數據     

                         

                          String pagestr=m_TestDAO.getPagestr(ipage);//分頁字符串,分頁內容

                        String s_find,str;

                          if(!"search".equals(search))    //查找和全部顯示兩個不同的操作,其分頁字符串不同,在此進行處理。如果是全部顯示則去掉"search=search&"

                          {

                              s_find="search=search&";

                              while(pagestr.indexOf(s_find)!=-1)

                              {

                                  str=pagestr.substring(0,pagestr.indexOf(s_find));

                                  str+=pagestr.substring(pagestr.indexOf(s_find)+s_find.length(),pagestr.length());

                                  pagestr=str;

                              }

                          }

                          m_TestForm.setPagestr(pagestr);  

                        m_TestForm.setAction(action);     

                          request.setAttribute("TestForm",m_TestForm);

                        //</分頁>

           

           

                          return mapping.findForward("success");

              

              }

           

           public String toChinese(String ss) {

              //處理中文問題,實現編碼轉換

              if (ss != null) {

                try {

                  String temp_p = ss;

                  byte[] temp_t = temp_p.getBytes("ISO8859-1");

                  ss = new String(temp_t);

                }

                catch (Exception e) {

                  System.err.println("toChinese exception:" + e.getMessage());

                  System.err.println("The String is:" + ss);

                }

              }

              return ss;

            }

           

          }

          把上述TestAction.java文件第68行:

          m_Test.setUserID(expression);

          修改成:

          m_Test.setUserID(java.lang.Integer.parseInt(expression,10));

           

          3)啟動調試狀態下的服務器:

          輸出欄中輸出如下提示信息:

          C:\Documents and Settings\Administrator\桌面>F:

          F:\>cd F:\JavaWebStudio\\jakarta-tomcat-5.5.4\bin\

          F:\JavaWebStudio\jakarta-tomcat-5.5.4\bin>startup_jpda.bat

          Using CATALINA_BASE:   F:\JavaWebStudio\jakarta-tomcat-5.5.4

          Using CATALINA_HOME:   F:\JavaWebStudio\jakarta-tomcat-5.5.4

          Using CATALINA_TMPDIR: F:\JavaWebStudio\jakarta-tomcat-5.5.4\temp

          Using JAVA_HOME:       F:\JavaWebStudio\jdk

           

          服務器啟動成功。

           

          4)啟動調試狀態:

          輸出欄中輸出如下提示信息:

          下面將執行的命令是: JDB -attach jdbconn

          Set uncaught java.lang.Throwable

          Set deferred uncaught java.lang.Throwable

          Initializing jdb ...

           

          5)設置斷點:

          打開TestAction文件,分別在127136行設置兩個斷點。輸出欄中輸出如下提示信息:

          下面將執行的命令是: JDB -attach jdbconn

          Set uncaught java.lang.Throwable

          Set deferred uncaught java.lang.Throwable

          Initializing jdb ...

          > 下面將執行的輸入參數是: stop at emptyprj.TestAction:127

          Deferring breakpoint emptyprj.TestAction:127.

          It will be set after the class is loaded.

          > 下面將執行的輸入參數是: stop at emptyprj.TestAction:136

          Deferring breakpoint emptyprj.TestAction:136.

          It will be set after the class is loaded.

           

           

          6)打開Test.jsp文件,并運行:

          運行結果:

           

          試一下全部顯示功能,點擊“全部顯示”接鈕,如果如下圖所示:

          可見運行到了斷點第128行處,再點擊一下調試工具條中的單過程執行,這時的變量值從輸出提示欄中可看出:

          http-8080-Processor25[1] 下面將執行的輸入參數是: locals

          下面將執行的輸入參數是: next

          Method arguments:

          mapping = instance of org.apache.struts.action.ActionMapping(id=1701)

          form = instance of emptyprj.TestForm(id=1702)

          request = instance of org.apache.catalina.connector.RequestFacade(id=1703)

          response = instance of org.apache.catalina.connector.ResponseFacade(id=1704)

          Local variables:

          locale = instance of java.util.Locale(id=1705)

          messages = instance of org.apache.struts.util.PropertyMessageResources(id=1706)

          session = instance of org.apache.catalina.session.StandardSessionFacade(id=1707)

          m_TestForm = instance of emptyprj.TestForm(id=1702)

          m_TestDAO = instance of emptyprj.TestDAO(id=1708)

          action = "search"

          search = "UNsearch"

          expression = "NULL"

          sql = "from emptyprj.Test Test"

          ipage = 1

          http-8080-Processor25[1] >

          Step completed: "thread=http-8080-Processor25", emptyprj.TestAction.execute(), line=128 bci=509

           

          http-8080-Processor25[1]

           

           

          現在試一下單步執行:

          http-8080-Processor25[1] 下面將執行的輸入參數是: locals

          下面將執行的輸入參數是: step

          Method arguments:

          mapping = instance of org.apache.struts.action.ActionMapping(id=1752)

          form = instance of emptyprj.TestForm(id=1753)

          request = instance of org.apache.catalina.connector.RequestFacade(id=1754)

          response = instance of org.apache.catalina.connector.ResponseFacade(id=1755)

          Local variables:

          locale = instance of java.util.Locale(id=1756)

          messages = instance of org.apache.struts.util.PropertyMessageResources(id=1757)

          session = instance of org.apache.catalina.session.StandardSessionFacade(id=1758)

          m_TestForm = instance of emptyprj.TestForm(id=1753)

          m_TestDAO = instance of emptyprj.TestDAO(id=1759)

          action = "search"

          search = "UNsearch"

          expression = "NULL"

          sql = "from emptyprj.Test Test"

          ipage = 1

          col = instance of java.util.ArrayList(id=2326)

          http-8080-Processor25[1] >

          Step completed: "thread=http-8080-Processor25", org.apache.catalina.connector.RequestFacade.setAttribute(), line=346 bci=0

          http-8080-Processor25[1]

          這時執行到了org.apache.catalina.connector.RequestFacade.setAttribute()RequestFacade.java文件的第246行。

           

           

          點擊一下調試工具條中的 “執行到下一個斷點”,執行到第137行。

           

          再點擊一下調試工具條中的 “執行到下一個斷點”,輸出最后結果,如下圖所示。

           

          通過上述步驟,實現了預計的目標功能。

           

           

           

           

          [程序源代碼]

          ConnectionFactory.java文件:

          package  emptyprj;

          import org.hibernate.HibernateException;

          import org.hibernate.MappingException;

          import org.hibernate.Session;

          import org.hibernate.SessionFactory;

          import org.hibernate.cfg.Configuration;

          public class ConnectionFactory

          {

                 private static ConnectionFactory instance = null;

                 private SessionFactory sessionFactory = null;

                 private ConnectionFactory()

                 {

                        try

                        {

                               //從這里裝截映射文件

                               Configuration cfg = new Configuration().

                                                       addClass(emptyprj.Test.class);

                               sessionFactory = cfg.buildSessionFactory();

                        }

                        catch (MappingException e)

                        {

                               System.err.println("Mapping Exception" + e.getMessage());

                               throw new RuntimeException(e);

                        }

                        catch (HibernateException e)

                        {

                               System.err.println("Hibernate Exception" + e.getMessage());

                               throw new RuntimeException(e);

                        }

                 }

                 public static synchronized ConnectionFactory getInstance()

                 {

                        if (instance == null)

                        {

                               instance = new ConnectionFactory();

                        }

                        return instance;

                 }

                 public Session getSession()

                 {

                        try

                        {

                               Session s = sessionFactory.openSession();

                               return s;

                        }

                        catch (HibernateException e)

                        {

                               System.err.println("Hibernate Exception" + e.getMessage());

                               throw new RuntimeException(e);

                        }

                 }

          }

           

          Test.hbm.xml文件:

          <?xml version="1.0"?>

          <!DOCTYPE hibernate-mapping PUBLIC

                  "-//Hibernate/Hibernate Mapping DTD 2.0//EN"

                  "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">

           

          <hibernate-mapping>

              <class name="emptyprj.Test" table="users" >

                  <id name="userID" column="userID" type="int" unsaved-value="null">

                      <generator class="uuid.hex"/>

                  </id>

                  <property name="username" column="username" type="java.lang.String" />

                  <property name="password" column="password" type="java.lang.String" />

                  <property name="role" column="role" type="java.lang.String" />

               </class>

          </hibernate-mapping>

           

          hibernate.properties數據庫連接池配置文件:

          hibernate.dialect=org.hibernate.dialect.SQLServerDialect

          hibernate.connection.driver_class=com.microsoft.jdbc.sqlserver.SQLServerDriver

          hibernate.connection.url=jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=EDB

          hibernate.dbcp.min_size=5

          hibernate.dbcp.max_size=20

          hibernate.dbcp.timeout=1800

          hibernate.dbcp.max_statements=50

          hibernate.connection.username=sa

          hibernate.connection.password=sa

           

          ///////////////////////////////////////////////////////////////////////////////////////////////////

          Test.java文件:

          這樣定義一個用于保存數據表數據的Bean,它的變量與數據庫表的字段完全對應,也就是與數據庫應用文件向導中的SQL語句要查找的字段完全對應。

          package  emptyprj;

          import java.io.Serializable;

          public class Test implements Serializable 

          {

                    private String  role;

                    private String  password;

                    private String  username;

                    private int  userID;

              //myfiledata;

                  public int getUserID()

                  {

                      return (this.userID);

                  }

                  public void setUserID(int userID)

                  {

                      this.userID=userID;

                  }

                  public String getUsername()

                  {

                      return (this.username);

                  }

                  public void setUsername(String username)

                  {

                      this.username=username;

                  }

                  public String getPassword()

                  {

                      return (this.password);

                  }

                  public void setPassword(String password)

                  {

                      this.password=password;

                  }

                  public String getRole()

                  {

                      return (this.role);

                  }

                  public void setRole(String role)

                  {

                      this.role=role;

                  }

          }

           

          TestDAO.java文件:

            這里定義一個DAO類,用于實現數據加的查找、刪除、更新、添加及生成分頁字符串等功能。

          package  emptyprj;

          import emptyprj.Test;

           

          import org.hibernate.HibernateException;

          import org.hibernate.ObjectNotFoundException;

          import org.hibernate.Query;

          import org.hibernate.Session;

           

          import java.util.List;

          import java.util.Iterator;

           

          public class TestDAO {

           

              private int rowCount;

              private int pageCount;

              private int length;     

              private String pagestr;

              public int getLength()  {  return (this.length);   }

              public void setLength(int length)  { this.length=length; } 

           

              private static TestDAO  instance = null;

              private TestDAO ()

              {

              }

           

                 public static synchronized TestDAO  getInstance()

                 {

                        if (instance == null)

                        {

                               instance = new TestDAO ();

                        }

                        return instance;

                 }

           

                 public Test getTest(Long id)

                 {

                        Session session = ConnectionFactory.getInstance().getSession();

                        try

                        {

                               return (Test) session.load(Test.class, id);

                        }

                        catch (ObjectNotFoundException onfe)

                        {

                               return null;

                        }

                        catch (HibernateException e)

                        {

                               System.err.println("Hibernate Exception" + e.getMessage());

                               throw new RuntimeException(e);

                        }

                        finally

                        {

                               if (session != null)

                               {

                                      try

                                      {

                                             session.close();

                                      }

                                      catch (HibernateException e)

                                      {

                                             System.err.println("Hibernate Exception" + e.getMessage());

                                             throw new RuntimeException(e);

                                      }

           

                               }

                        }

           

                 }

           

                

                 public void update(Test Test,String keyID)

                 {

                        Session session = ConnectionFactory.getInstance().getSession();

           

                        try

                        {

                               session.update(Test);

                               session.flush();

                        }

                        catch (HibernateException e)

                        {

                               System.err.println("Hibernate Exception" + e.getMessage());

                               throw new RuntimeException(e);

                        }

                           finally

                        {

                               if (session != null)

                               {

                                      try

                                      {

                                             session.close();

                                      }

                                      catch (HibernateException e)

                                      {

                                             System.err.println("Hibernate Exception" + e.getMessage());

                                             throw new RuntimeException(e);

                                      }

           

                               }

                        }

           

                 }

           

                 public void removeID(Test Test) {

                       Session session = ConnectionFactory.getInstance().getSession();

                        try

                        {

                               session.delete(Test);

                               session.flush();

                        }

                        catch (HibernateException e)

                        {

                               System.err.println("Hibernate Exception" + e.getMessage());

                               throw new RuntimeException(e);

                        }

                        finally

                        {

                               if (session != null)

                               {

                                      try

                                      {

                                             session.close();

                                      }

                                      catch (HibernateException e)

                                      {

                                             System.err.println("Hibernate Exception" + e.getMessage());

                                             throw new RuntimeException(e);

                                      }

           

                               }

                        }

           

                 }

           

           

                 public List findSQL(String sql,String countsql,int ipage)

                 {

                        Session session = ConnectionFactory.getInstance().getSession();

                        try

                        {

                               //提取記錄總數

                               Iterator results = session.createQuery(countsql).iterate();

                               while ( results.hasNext() ) {

                                   //Object[] row = results.next();

                                        //rowCount= (Integer) row[0];

                                        rowCount= (Integer) results.next();

                               }

                              

                              //rowCount=10;

                              int offset=1;

                              int pagesize=getLength();

                              if(getLength()<1)

                              {

                                    pagesize=rowCount;

                                  pageCount=1;

                              }

                              else

                              {

                                  pageCount=rowCount/getLength()+((rowCount%getLength())>0?1:0);

                                  offset=(ipage-1)*getLength()+1;

                                  if(offset<1)offset=1;

                                  if(offset>rowCount)offset=rowCount;       

                  

                              }

                               //提取數據

                               Query query =       session.createQuery(sql);

                               query.setFirstResult((ipage-1)*getLength());

                               query.setMaxResults(pagesize);

                               return query.list();

           

                        }

                        catch (HibernateException e)

                        {

                               System.err.println("Hibernate Exception" + e.getMessage());

                               throw new RuntimeException(e);

                        }

                        finally

                        {

                               if (session != null)

                               {

                                      try

                                      {

                                             session.close();

                                      }

                                      catch (HibernateException e)

                                      {

                                             System.err.println("Hibernate Exception" + e.getMessage());

                                             throw new RuntimeException(e);

                                      }

                               }

                        }

                 }

           

                 //添加一條新記錄

                 public void create(Test Test)

                 {

                        Session session = ConnectionFactory.getInstance().getSession();

                        try

                        {

                               session.save(Test);

                               session.flush();

                        }

                        catch (HibernateException e)

                        {

                               System.err.println("Hibernate Exception" + e.getMessage());

                               throw new RuntimeException(e);

                        }

                        finally

                        {

                               if (session != null)

                               {

                                      try

                                      {

                                             session.close();

                                      }

                                      catch (HibernateException e)

                                      {

                                             System.err.println("Hibernate Exception" + e.getMessage());

                                             throw new RuntimeException(e);

                                      }

                               }

                        }

                 }

           

              //分頁字符串處理

              public String getPagestr(int ipage)

              {

                     String strPage="";

                        if(getLength()>0)

                        {

                              strPage+="";

                              strPage+=String.valueOf(rowCount);

                              strPage+="條記錄,共";

                              strPage+=String.valueOf(pageCount);

                              strPage+="頁,當前是第";

                              strPage+=String.valueOf(ipage);

                              strPage+="頁,      ";

                         

                              int istart,iend;

                              istart=ipage-5;

                              if(istart<0) {istart=0;}

                              iend=istart+10;

                              if(iend>pageCount) {iend=pageCount;}

                              istart=iend-10;

                              if(istart<0) {istart=0;}

                              for(int i=istart;i<iend;i++)

                              {

                                  strPage+="<a href='TestAction.do?action=find&search=search&page=";

                                  strPage+=String.valueOf(i+1);

                                  strPage+="'>";

                                  strPage+=String.valueOf(i+1);

                                  strPage+="</a>";

                                  strPage+="  ";

                              }

                     }

                     this.pagestr=strPage;

                     return strPage;

            }

           

          }

          TestForm.java文件:

            這里定義一個ActionForm Bean,除了包含與數據庫表的字段完全對應的變量外(例如可用于保存查詢條件中相應字段的變量的值、保存某行記錄的數據等),還包含了與分頁相關的變量,例如當前頁碼、分頁字符串等變量。

          package  emptyprj;

           

          import javax.servlet.http.HttpServletRequest;

          import org.apache.struts.action.ActionError;

          import org.apache.struts.action.ActionErrors;

          import org.apache.struts.action.ActionForm;

          import org.apache.struts.action.ActionMapping;

           

          public final class TestForm extends ActionForm 

          {

                    private String  role;

                    private String  password;

                    private String  username;

                    private int  userID;

                    private int page;

                    private String  pagestr;

                    private String  action;

                    private String mybeanvariable1;

              //myfiledata;

                  public String getMybeanvariable1()

                  {

                      return (this.mybeanvariable1);

                  }

                  public void setMybeanvariable1(String mybeanvariable1)

                  {

                      this.mybeanvariable1=mybeanvariable1;

                  }

                  public String getAction()

                  {

                      return (this.action);

                  }

                  public void setAction(String action)

                  {

                      this.action=action;

                  }

                  public String getPagestr()

                  {

                      return (this.pagestr);

                  }

                  public void setPagestr(String pagestr)

                  {

                      this.pagestr=pagestr;

                  }

                  public int getPage()

                  {

                      return (this.page);

                  }

                  public void setPage(int page)

                  {

                      this.page=page;

                  }

                  public int getUserID()

                  {

                      return (this.userID);

                  }

                  public void setUserID(int userID)

                  {

                      this.userID=userID;

                  }

                  public String getUsername()

                  {

                      return (this.username);

                  }

                  public void setUsername(String username)

                  {

                      this.username=username;

                  }

                  public String getPassword()

                  {

                      return (this.password);

                  }

                  public void setPassword(String password)

                  {

                      this.password=password;

                  }

                  public String getRole()

                  {

                      return (this.role);

                  }

                  public void setRole(String role)

                  {

                      this.role=role;

                  }

          }

           

          TestAction.java文件:

             這里定義一個Action類,用于實現頁面的轉發功能,另外還包括了不同請求類型的不同操作。其中action變量表示操作類型,相當于事件類型。通過這個變量,實現了類似于.NET中的“事件驅動”的功能。

          package  emptyprj;

           

          import emptyprj.TestDAO;

          import java.lang.reflect.InvocationTargetException;

          import java.util.Locale;

          import javax.servlet.ServletException;

          import javax.servlet.http.HttpSession;

          import javax.servlet.http.HttpServletRequest;

          import javax.servlet.http.HttpServletResponse;

          import org.apache.commons.beanutils.PropertyUtils;

          import org.apache.commons.logging.Log;

          import org.apache.commons.logging.LogFactory;

          import org.apache.struts.action.Action;

          import org.apache.struts.action.ActionError;

          import org.apache.struts.action.ActionErrors;

          import org.apache.struts.action.ActionForm;

          import org.apache.struts.action.ActionForward;

          import org.apache.struts.action.ActionMapping;

          import org.apache.struts.action.ActionServlet;

          import org.apache.struts.util.ModuleException;

          import org.apache.struts.util.MessageResources;

           

          import java.io.IOException;

          import java.sql.Connection;

          import java.sql.SQLException;

          import java.util.Collection;

           

          public final class TestAction extends Action

          {

              // 變量定義:

              private Log log = LogFactory.getLog("org.apache.struts.webapp.Example");

              public TestAction() {

                

              }

           

           

              //函數定義:

              public ActionForward execute(ActionMapping mapping,

                                       ActionForm form,

                                       HttpServletRequest request,

                                       HttpServletResponse response)

                 throws Exception

              {

                 // Extract attributes and parameters we will need

                 Locale locale = getLocale(request);

                 MessageResources messages = getResources(request);

                 HttpSession session = request.getSession();

                 TestForm m_TestForm = (TestForm) form;

                

                           TestDAO m_TestDAO = TestDAO.getInstance();  //定義Hibernate__DAO對象,用于實現數據庫的各種操作

           

                           String action=request.getParameter("action");  //動作類型                 

                           String search=request.getParameter("search");  //數據庫查找方式

                           String expression=request.getParameter("expression");    //參數,這里用于保存記錄(行)的ID數據

                          

                           if(action==null)action="find";

                        if(search==null)search="UNsearch";

                        if(expression==null)expression="";

                        expression=toChinese(expression);  //處理中文問題,實現編碼轉換

                        

                      /////////

                         if("delete".equals(action))    //刪除記錄操作 

                      {

                           Test m_Test= new Test();

                           //<delete>

                           m_Test.setUserID(java.lang.Integer.valueOf(expression));

                           //</delete>             

                              m_TestDAO.removeID(m_Test);

                       }

           

                      ////////////

                        if("update".equals(action)||"insert".equals(action))    //更新、添加記錄操作

                        {

                           Test m_Test= new Test();

                               //<update>

                              m_Test.setUserID(m_TestForm.getUserID());

                              m_Test.setUsername(m_TestForm.getUsername());

                              m_Test.setPassword(m_TestForm.getPassword());

                              m_Test.setRole(m_TestForm.getRole());

                              //</update>

                               if("update".equals(action))    //調用DAO對象更新記錄

                                        m_TestDAO.update(m_Test,expression);

                               if("insert".equals(action))    //調用DAO對象添加記錄

                                    m_TestDAO.create(m_Test);

                                        

                        }

                          

                        ///////////////HQL_查找數據庫

                        String sql="from emptyprj.Test Test";

                      

                        ////SQL字符處理,主要是加入查詢條件,如果是全部顯示,可把這部分代碼刪除。

                           if("search".equals(search))

                           {

                            String selectsql;

                               //<search>

                                  sql+=" where ";

                               sql+="userID";

                               sql+="=";

                               if("NULL".equals(expression)||"".equals(expression))

                              {

                                      sql+=m_TestForm .getUserID();

                                  }

                                  else

                                  {

                                      sql+=expression;

                                  }

                                  

                                  sql+="";

                               //</search>

                           }

           

                       //<分頁>

                          m_TestDAO.setLength(4);//設置每頁顯示記錄數

                          int ipage;//當前頁

                          try

                          {

                              String page=request.getParameter("page");//分頁參數,讀取請求的當前頁

                              ipage=java.lang.Integer.parseInt(page,10);

                          }

                          catch (Exception e)

                       {

                           ipage=m_TestForm.getPage();

                       }

                       if(ipage<1)ipage=1;

                       Collection col = m_TestDAO.findSQL("select Test "+sql,"select count(Test) "+sql,ipage);//通過DAO對象查詢數據

                          request.setAttribute("Test",col);  //保存數據     

                         

                          String pagestr=m_TestDAO.getPagestr(ipage);//分頁字符串,分頁內容

                        if(!"search".equals(search))    //查找和全部顯示兩個不同的操作,其分頁字符串不同,在此進行處理。如果是全部顯示則去掉"search=search&"

                           {

                               pagestr=pagestr.replaceAll("search=search&","");

                           }

                          m_TestForm.setPagestr(pagestr);  

                        m_TestForm.setAction(action);     

                          request.setAttribute("TestForm",m_TestForm);

                        //</分頁>

           

           

                           return mapping.findForward("success");

              

              }

           

           public String toChinese(String ss) {

              //處理中文問題,實現編碼轉換

              if (ss != null) {

                try {

                  String temp_p = ss;

                  byte[] temp_t = temp_p.getBytes("ISO8859-1");

                  ss = new String(temp_t);

                }

                catch (Exception e) {

                  System.err.println("toChinese exception:" + e.getMessage());

                  System.err.println("The String is:" + ss);

                }

              }

              return ss;

            }

           

          }

          web.xml文件:

            這里除了普通的Struts項目的配置之外,還包括數據庫連接池的配置,見暗體字部分的代碼。

          <?xml version="1.0" encoding="ISO-8859-1"?>

           

          <!DOCTYPE web-app

            PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"

            "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">

           

          <web-app>

           

            <!-- Standard Action Servlet Configuration -->

            <servlet>

              <servlet-name>action</servlet-name>

              <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>

                 <load-on-startup>1</load-on-startup>

            </servlet>

             

          <filter>

              <filter-name>Set Character Encoding</filter-name>

              <filter-class>javawebstudio.struts_db.SetCharacterEncodingFilter</filter-class>

              <init-param>

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

                  <param-value>GB2312</param-value>

              </init-param>

              <init-param>

                  <param-name>ignore</param-name>

                  <param-value>true</param-value>

              </init-param>

          </filter>

           

          <filter-mapping>

              <filter-name>Set Character Encoding</filter-name>

              <servlet-name>action</servlet-name>

          </filter-mapping>

           

           

            <!-- Standard Action Servlet Mapping -->

            <servlet-mapping>

              <servlet-name>action</servlet-name>

              <url-pattern>*.do</url-pattern>

            </servlet-mapping>

           

           

            <welcome-file-list>

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

            </welcome-file-list>

           

           

            <!-- Struts Tag Library Descriptors -->

            <taglib>

              <taglib-uri>/bean</taglib-uri>

              <taglib-location>/WEB-INF/struts-bean.tld</taglib-location>

            </taglib>

           

            <taglib>

              <taglib-uri>/html</taglib-uri>

              <taglib-location>/WEB-INF/struts-html.tld</taglib-location>

            </taglib>

           

            <taglib>

              <taglib-uri>/logic</taglib-uri>

              <taglib-location>/WEB-INF/struts-logic.tld</taglib-location>

            </taglib>

           

            <taglib>

              <taglib-uri>/template</taglib-uri>

              <taglib-location>/WEB-INF/struts-template.tld</taglib-location>

            </taglib>

          </web-app>

           

           

          struts-config.xml文件:

          <?xml version="1.0" encoding="ISO-8859-1" ?>

           

          <!DOCTYPE struts-config PUBLIC

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

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

           

          <struts-config>

           

          <form-beans>

           

           

          <form-bean  name="TestForm"

                           type="emptyprj.TestForm"  />

          </form-beans>

           

          <action-mappings>

           

           

          <action  path="/TestAction"

                       type="emptyprj.TestAction"

                        name="TestForm" 

                      scope="request"

                       input="/Test.jsp">

                 <forward name="success"  path="/TestOut.jsp" /></action>

          </action-mappings>

           

          <!-- ========== Message Resources Definitions =========================== -->

           

            <message-resources    parameter="ApplicationResources_ch.properties"/>

           

            <message-resources    parameter="AlternateApplicationResources"

                                   key="alternate">

            </message-resources>

           

          </struts-config>

           

          posted on 2005-02-04 13:35 輕松 閱讀(1794) 評論(0)  編輯  收藏 所屬分類: Struts相關

          主站蜘蛛池模板: 阜康市| 股票| 安徽省| 淳化县| 沅江市| 禄丰县| 泉州市| 巧家县| 四平市| 永修县| 郸城县| 鄂州市| 定远县| 长海县| 镇坪县| 远安县| 石景山区| 房产| 神农架林区| 出国| 咸丰县| 嘉峪关市| 汤阴县| 宾川县| 江源县| 宜城市| 和田市| 武安市| 余江县| 万宁市| 道真| 台湾省| 辽阳县| 大宁县| 西峡县| 湘潭市| 铁力市| 阿城市| 敦煌市| 北海市| 宝山区|