<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    輕松

    記述我學習java的里程

    常用鏈接

    統(tǒng)計

    積分與排名

    友情鏈接

    最新評論

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

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


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

     

     

    [目標]

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

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

    錄入一些測試數(shù)據(jù):

      

    [效果]

    (1)全部顯示:

    輸入頁面:

    輸出頁面:

     

    (2)查詢顯示:

     

    [背景知識]

     

     

    [步驟]

     

    1、打開Visual Struts開發(fā)環(huán)境:

    從桌面JavaWebStudio快揵或BIN目錄下的JavaWebStudio.exe文件啟動JavaWebStudioVisual Struts開發(fā)環(huán)境。

     

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

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

     

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

     

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

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

     

    3、利用Struts數(shù)據(jù)庫應用文件向導建立新的應用:

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

    1)輸入文件名:

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

     

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

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

     

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

     

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

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

     

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

     

    4、項目文件結構

     

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

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

     

    Test.jsp文件:

     

    TestInsert.jsp文件:

     

    TestOut.jsp文件:

     

     

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

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

    這里將采用調試狀態(tài)下的運行方式:

    (1)       顯示調試工具條:

     

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

     

    2)選擇調試狀態(tài)下的“編譯”:

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

    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

    出現(xiàn)一個錯誤,原因是因為前面我們設置userID為整數(shù)類型,而這里的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() {

          

        }

     

     

        //函數(shù)定義:

        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對象,用于實現(xiàn)數(shù)據(jù)庫的各種操作

     

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

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

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

                   

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

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

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

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

                 

                /////////

                  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_查找數(shù)據(jù)庫

                  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);//設置每頁顯示記錄數(shù)

                    int ipage;//當前頁

                    try

                    {

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

                        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對象查詢數(shù)據(jù)

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

                   

                    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) {

        //處理中文問題,實現(xiàn)編碼轉換

        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)啟動調試狀態(tài)下的服務器:

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

    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)啟動調試狀態(tài):

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

    下面將執(zhí)行的命令是: JDB -attach jdbconn

    Set uncaught java.lang.Throwable

    Set deferred uncaught java.lang.Throwable

    Initializing jdb ...

     

    5)設置斷點:

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

    下面將執(zhí)行的命令是: JDB -attach jdbconn

    Set uncaught java.lang.Throwable

    Set deferred uncaught java.lang.Throwable

    Initializing jdb ...

    > 下面將執(zhí)行的輸入?yún)?shù)是: stop at emptyprj.TestAction:127

    Deferring breakpoint emptyprj.TestAction:127.

    It will be set after the class is loaded.

    > 下面將執(zhí)行的輸入?yún)?shù)是: stop at emptyprj.TestAction:136

    Deferring breakpoint emptyprj.TestAction:136.

    It will be set after the class is loaded.

     

     

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

    運行結果:

     

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

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

    http-8080-Processor25[1] 下面將執(zhí)行的輸入?yún)?shù)是: locals

    下面將執(zhí)行的輸入?yún)?shù)是: 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]

     

     

    現(xiàn)在試一下單步執(zhí)行:

    http-8080-Processor25[1] 下面將執(zhí)行的輸入?yún)?shù)是: locals

    下面將執(zhí)行的輸入?yún)?shù)是: 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]

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

     

     

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

     

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

     

    通過上述步驟,實現(xiàn)了預計的目標功能。

     

     

     

     

    [程序源代碼]

    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數(shù)據(jù)庫連接池配置文件:

    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文件:

    這樣定義一個用于保存數(shù)據(jù)表數(shù)據(jù)的Bean,它的變量與數(shù)據(jù)庫表的字段完全對應,也就是與數(shù)據(jù)庫應用文件向導中的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類,用于實現(xiàn)數(shù)據(jù)加的查找、刪除、更新、添加及生成分頁字符串等功能。

    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

                  {

                         //提取記錄總數(shù)

                         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;       

            

                        }

                         //提取數(shù)據(jù)

                         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,除了包含與數(shù)據(jù)庫表的字段完全對應的變量外(例如可用于保存查詢條件中相應字段的變量的值、保存某行記錄的數(shù)據(jù)等),還包含了與分頁相關的變量,例如當前頁碼、分頁字符串等變量。

    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類,用于實現(xiàn)頁面的轉發(fā)功能,另外還包括了不同請求類型的不同操作。其中action變量表示操作類型,相當于事件類型。通過這個變量,實現(xiàn)了類似于.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() {

          

        }

     

     

        //函數(shù)定義:

        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對象,用于實現(xiàn)數(shù)據(jù)庫的各種操作

     

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

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

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

                    

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

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

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

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

                  

                /////////

                   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_查找數(shù)據(jù)庫

                  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);//設置每頁顯示記錄數(shù)

                    int ipage;//當前頁

                    try

                    {

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

                        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對象查詢數(shù)據(jù)

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

                   

                    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) {

        //處理中文問題,實現(xiàn)編碼轉換

        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項目的配置之外,還包括數(shù)據(jù)庫連接池的配置,見暗體字部分的代碼。

    <?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相關

    主站蜘蛛池模板: 亚洲精品视频免费看| 国产大片免费观看中文字幕| av永久免费网站在线观看| 亚洲冬月枫中文字幕在线看| 亚洲精品456播放| 亚洲av无码成人精品区在线播放 | 亚洲人成www在线播放| 精品日韩99亚洲的在线发布| 亚洲精品无码Av人在线观看国产 | 国拍在线精品视频免费观看| 美女被免费网站91色| 国产精品内射视频免费| 99re6在线精品免费观看| 日本免费污片中国特一级| 日韩免费人妻AV无码专区蜜桃 | 狠狠躁狠狠爱免费视频无码| 免费无码作爱视频| 免费女人高潮流视频在线观看| 99热在线免费观看| 曰批全过程免费视频在线观看| 国产一区二区免费视频| 91精品导航在线网址免费| 青春禁区视频在线观看直播免费| 久久免费国产精品一区二区| 免费看片在线观看| 91高清免费国产自产拍2021| 麻豆一区二区免费播放网站 | 西西大胆无码视频免费| 国产成人aaa在线视频免费观看| 久久亚洲AV无码西西人体| 免费一级毛片不卡在线播放| 相泽亚洲一区中文字幕| 亚洲人成依人成综合网| 亚洲综合久久夜AV | 成人亚洲网站www在线观看| 免费看的黄色大片| a毛片基地免费全部视频| 四虎影视在线永久免费看黄| 国产美女精品久久久久久久免费| a级亚洲片精品久久久久久久| 91亚洲精品视频|