struts2 + hibernate + spring + flexgrid page implementation

2010-07-28  来源:本站原创  分类:Java  人气:249 

struts2 + hibernate + spring + flexgrid page implementation:

1, new construction, adding struts2, hibernate, spring, and the corresponding version of the required jar package jar file list to be added as follows:

struts2 + hibernate + spring + flexgrid page implementation

2, modify the web.xml configuration:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
        http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
        <display-name>SSH Demo</display-name>
        <context-param>
                <param-name>log4jConfigLocation</param-name>
                <param-value>classpath:log4j.properties</param-value>
        </context-param>
        <listener>
                <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
        </listener>
        <!--   Spring configuration file specified  ,  The default root directory from the web to find the configuration file  ,  Provided by spring  classpath:  Prefix search from the class path   -->
        <context-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>classpath:applicationContext*.xml</param-value>
        </context-param>
        <!--   Instantiated on the Spring container   -->
        <listener>
                <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>
        <!--   Filter Encoding  (  Configured to be placed in front of struts2  ) -->
        <filter>
                <filter-name>encodeFilter</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>
                <init-param>
                        <param-name>forceEncoding</param-name>
                        <param-value>true</param-value>
                </init-param>
        </filter>
        <filter-mapping>
                <filter-name>encodeFilter</filter-name>
                <url-pattern>/*</url-pattern>
        </filter-mapping>
        <filter>
                <filter-name>struts2</filter-name>
                <!--
                          The old version before the filter is used
                        <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
                -->
                <filter-class>
                        org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
        </filter>
        <filter-mapping>
                <filter-name>struts2</filter-name>
                <url-pattern>/*</url-pattern>
        </filter-mapping>
        <error-page>
                <error-code>404</error-code>
                <location>/WEB-INF/404.jsp</location>
        </error-page>
        <error-page>
                <error-code>500</error-code>
                <location>/WEB-INF/500.jsp</location>
        </error-page>
        <welcome-file-list>
                <welcome-file>index.jsp</welcome-file>
        </welcome-file-list>
</web-app>

3, an increase in the src directory, create a new struts.xml configuration file, which reads as follows:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
        <!--  When the modified configuration file struts.xml  ,  Whether the system to reload the file, open the feature development phase    -->
        <constant name="struts.configuration.xml.reload" value="true" />
        <!--
                  Encoding specified set of WEB applications  ,  Method equivalent to calling HttpServletRequest.setCharacterEncodint  ,  If you are using a velocity or  freemarker,  It is also used to specify the encoding format of the output
        -->
        <constant name="struts.i18n.encoding" value="UTF-8" />
        <!--  Specifies the request suffix. Action, specify the number of requests suffix separated by commas   -->
        <constant name="struts.action.extension" value="action" />
        <!--  Set browser cache static content, the proposed  :  Stage of development closed, open run-time    -->
        <constant name="struts.serve.static.browserCache" value="false" />
        <!--    Development Tips  :  More detailed error information to print  -->
        <constant name="struts.devMode" value="true" />
        <!--   This configuration can be further action after the  name  Elements used  "/" -->
        <constant name="struts.enable.SlashesInActionNames" value="true" />
        <constant name="struts.enable.DynamicMethodInvocation" value="false" />
        <!--   The default view of the theme   -->
        <constant name="struts.ui.theme" value="simple" />
        <!--   Resource file   -->
        <constant name="struts.custom.i18n.resources" value="native" />
        <!-- Spring  Responsible for creating Action instance   -->
        <constant name="struts.objectFactory" value="spring" />
        <package name="ssh" extends="json-default">
                <action name="GetUsersList">
                        <result type="json" />
                </action>
        </package>
</struts>

4, an increase in the src directory, create a hibernate.cfg.xml configuration file, which reads as follows:

<?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="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/test</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="myeclipse.connection.profile">com.mysql.jdbc.Driver</property>
        <!--
        <property name="hbm2ddl.auto">update</property>-->
        <property name="show_sql">true</property>
        <property name="format_sql">true</property>
        <mapping resource="com/starit/bean/TbUser.hbm.xml" />
</session-factory>
</hibernate-configuration>

5, an increase in the src directory, create a new applicationContext.xml configuration file, which reads as follows:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
        <bean
               >
                <property name="configLocation"
                        value="classpath:hibernate.cfg.xml" />
        </bean>
        <bean/>
        <bean>
                <property name="userDAO">
                        <ref local="userDAO"/>
                </property>
        </bean>
        <bean>
                <property name="userService">
                        <ref local="userService"/>
                </property>
        </bean>
</beans>

6, in the com / starit / bean / class and the tables established under the mapping between TbUser.hbm.xml, which reads as follows:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.starit.bean">
    <class name="TbUser" table="tb_user" catalog="test">
        <id name="id" type="java.lang.Integer">
            <column name="id" />
            <generator />
        </id>
        <property name="name" type="java.lang.String">
                <column name="name" length="20"/>
        </property>
        <property name="gender" type="java.lang.String">
                <column name="gender" length="6"/>
        </property>
        <property name="age" type="java.lang.Integer">
                <column name="age"/>
        </property>
        <property name="birthday" type="java.sql.Date">
                <column name="birthday"/>
        </property>
        <property name="phone" type="java.lang.String">
                <column name="phone" length="11"/>
        </property>
        <property name="address" type="java.lang.String">
                <column name="address" length="50"/>
        </property>
        <property name="username" type="java.lang.String">
            <column name="username" length="20" not-null="true" />
        </property>
        <property name="password" type="java.lang.String">
            <column name="password" length="20" not-null="true" />
        </property>
    </class>
</hibernate-mapping>

7, configure log4j, log4j.properties, which reads as follows:

log4j.rootLogger=error,CONSOLE,FILE

log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.Target=System.out
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d - %c -%-4r[%t]%-5p%c%x-%m%n

log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.File=file.log
log4j.appender.FILE.Append=false
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.ConversionPattern=[framework]  %d - %c -%-4r [%t] %-5p %c %x -%m%n

8, following the achievement levels of the code:

/**
 * File   : TbUser.java
 * Author : zqding
 * Date   : 2010-7-22
 * Version:
 * Desc   :
 */
package com.starit.bean;

import java.io.Serializable;
import java.sql.Date;

public class TbUser implements Serializable {
        private static final long serialVersionUID = 1L;

        private Integer id;

        private String name;

        private String gender;

        private Integer age;

        private Date birthday;

        private String phone;

        private String address;

        private String username;

        private String password;

        public String getAddress() {
                return address;
        }

        public void setAddress(String address) {
                this.address = address;
        }

        public Integer getAge() {
                return age;
        }

        public void setAge(Integer age) {
                this.age = age;
        }

        public Date getBirthday() {
                return birthday;
        }

        public void setBirthday(Date birthday) {
                this.birthday = birthday;
        }

        public String getGender() {
                return gender;
        }

        public void setGender(String gender) {
                this.gender = gender;
        }

        public Integer getId() {
                return id;
        }

        public void setId(Integer id) {
                this.id = id;
        }

        public String getName() {
                return name;
        }

        public void setName(String name) {
                this.name = name;
        }

        public String getPassword() {
                return password;
        }

        public void setPassword(String password) {
                this.password = password;
        }

        public String getPhone() {
                return phone;
        }

        public void setPhone(String phone) {
                this.phone = phone;
        }

        public String getUsername() {
                return username;
        }

        public void setUsername(String username) {
                this.username = username;
        }
}

/**
 * File   : UserDAO.java
 * Author : zqding
 * Date   : 2010-7-22
 * Version:
 * Desc   :
 */
package com.starit.dao;

import java.util.List;

import com.starit.bean.TbUser;
import com.starit.util.Page;

public interface UserDAO {
        public TbUser findByUsernamePassword(String username, String password);

        public Page findByPageNo(int pageNo, int pageSize);

        @SuppressWarnings("unchecked")
        public List getAllUsers()throws Exception;

        @SuppressWarnings("unchecked")
        public List getUsersByPage(int pageNo,int pageSize)throws Exception;
}

/**
 * File   : UserDAOImpl.java
 * Author : zqding
 * Date   : 2010-7-22
 * Version:
 * Desc   :
 */
package com.starit.dao.imp;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import com.starit.bean.TbUser;
import com.starit.dao.UserDAO;
import com.starit.util.HibernateSessionFactory;
import com.starit.util.Page;

public class UserDAOImpl implements UserDAO {
        private Session session = HibernateSessionFactory.getSession();

        public Page findByPageNo(int pageNo, int pageSize) {
                Page page = new Page();

                Query query = session.createQuery("select count(*) from TbUser");

                int count = Integer.parseInt(query.uniqueResult().toString());

                query = session.createQuery("from TbUser");
                query.setMaxResults(pageSize);
                query.setFirstResult((pageNo - 1) * pageSize);

                page.setList(query.list());
                page.setTotal(count);
                page.setPageNo(pageNo);
                page.setPageSize(pageSize);

                return page;
        }

        public TbUser findByUsernamePassword(String username, String password) {
                String hql = "from TbUser where username=? and password=?";
                Query query = session.createQuery(hql);
                query.setParameter(0, username);
                query.setParameter(1, password);
                return (TbUser) query.uniqueResult();
        }

        public List getAllUsers() throws Exception {
                String hql = "from TbUser";
                Query query = session.createQuery(hql);
                return query.list();
        }

        public List getUsersByPage(int pageNo,int pageSize) throws Exception {
                String hql = "from TbUser";
                Query query = session.createQuery(hql);
                query.setMaxResults(pageSize);
                query.setFirstResult((pageNo - 1) * pageSize);
                return query.list();
        }

}

/**
 * File   : UserService.java
 * Author : zqding
 * Date   : 2010-7-22
 * Version:
 * Desc   :
 */
package com.starit.service;

import java.util.List;

import com.starit.bean.TbUser;
import com.starit.util.Page;

public interface UserService {
        public TbUser findByUsernamePassword(String username, String password);

        public Page findByPageNo(int pageNo, int pageSize);

        @SuppressWarnings("unchecked")
        public List getAllUsers()throws Exception;

        @SuppressWarnings("unchecked")
        public List getUsersByPage(int pageNo,int pageSize)throws Exception;
}

/**
 * File   : UserServiceImpl.java
 * Author : zqding
 * Date   : 2010-7-22
 * Version:
 * Desc   :
 */
package com.starit.service.imp;

import java.util.List;

import com.starit.bean.TbUser;
import com.starit.dao.UserDAO;
import com.starit.service.UserService;
import com.starit.util.Page;

public class UserServiceImpl implements UserService {
        private UserDAO userDAO;

        public UserDAO getUserDAO() {
                return userDAO;
        }

        public void setUserDAO(UserDAO userDAO) {
                this.userDAO = userDAO;
        }

        public Page findByPageNo(int pageNo, int pageSize) {
                return userDAO.findByPageNo(pageNo, pageSize);
        }

        public TbUser findByUsernamePassword(String username, String password) {
                return userDAO.findByUsernamePassword(username, password);
        }

        @SuppressWarnings("unchecked")
        public List getAllUsers() throws Exception {

                return userDAO.getAllUsers();
        }

        @SuppressWarnings("unchecked")
        public List getUsersByPage(int pageNo, int pageSize) throws Exception {
                return userDAO.getUsersByPage(pageNo, pageSize);
        }
}

/**
 * File   : Page.java
 * Author : zqding
 * Date   : 2010-7-22
 * Version:
 * Desc   :
 */
package com.starit.util;

import java.util.List;

public class Page {
        private int total;

        private int pageSize;

        private int totalPage;

        private int pageNo;

        private int prePage;

        private int nextPage;

        private List list;

        public List getList() {
                return list;
        }

        public void setList(List list) {
                this.list = list;
        }

        public int getNextPage() {
                if (pageNo == totalPage) {
                        nextPage = pageNo;
                } else {
                        nextPage = pageNo + 1;
                }
                return nextPage;
        }

        public void setNextPage(int nextPage) {
                this.nextPage = nextPage;
        }

        public int getPageNo() {
                return pageNo;
        }

        public void setPageNo(int pageNo) {
                this.pageNo = pageNo;
        }

        public int getPageSize() {
                return pageSize;
        }

        public void setPageSize(int pageSize) {
                this.pageSize = pageSize;
        }

        public int getPrePage() {
                if (pageNo == 1) {
                        prePage = pageNo;
                } else {
                        prePage = pageNo - 1;
                }
                return prePage;
        }

        public void setPrePage(int prePage) {
                this.prePage = prePage;
        }

        public int getTotal() {
                return total;
        }

        public void setTotal(int total) {
                this.total = total;
        }

        public int getTotalPage() {
                if (total % pageSize == 0) {
                        totalPage = total / pageSize;
                } else {
                        totalPage = total / pageSize + 1;
                }
                return totalPage;
        }

        public void setTotalPage(int totalPage) {
                this.totalPage = totalPage;
        }
}

/**
 * File   : HibernateSessionFactory.java
 * Author : zqding
 * Date   : 2010-7-22
 * Version:
 * Desc   :
 */
package com.starit.util;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateSessionFactory {
        private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
        private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
        private static Configuration configuration = new Configuration();
        private static org.hibernate.SessionFactory sessionFactory;
        private static String configFile = CONFIG_FILE_LOCATION;

        static {
                try {
                        configuration.configure(configFile);
                        sessionFactory = configuration.buildSessionFactory();
                } catch (Exception e) {
                        System.err.println("Error Creating SessionFactory...");
                        e.printStackTrace();
                }
        }

        private HibernateSessionFactory() {
        }

        public static Session getSession() throws HibernateException {
                Session session = (Session) threadLocal.get();

                if (session == null || !session.isOpen()) {
                        if (sessionFactory == null) {
                                rebuildSessionFactory();
                        }
                        session = (sessionFactory != null) ? sessionFactory.openSession()
                                        : null;
                        threadLocal.set(session);
                }

                return session;
        }

        public static void rebuildSessionFactory() {
                try {
                        configuration.configure(configFile);
                        sessionFactory = configuration.buildSessionFactory();
                } catch (Exception e) {
                        System.err.println("Error Creating SessionFactory...");
                        e.printStackTrace();
                }
        }

        public static void closeSession() throws HibernateException {
                Session session = (Session) threadLocal.get();
                threadLocal.set(null);

                if (session != null) {
                        session.close();
                }
        }

        public static SessionFactory getSessionFactory() {
                return sessionFactory;
        }

        public static void setConfigFile(String configFile) {
                HibernateSessionFactory.configFile = configFile;
                sessionFactory = null;
        }

        public static Configuration getConfiguration() {
                return configuration;
        }
}

9, write flexgrid test side page:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
        <head>
                <meta http-equiv="content-type" content="text/html; charset=utf-8" />
                <title>Flexigrid</title>
                <link rel="stylesheet" type="text/css" href="resources/flexigrid/css/flexigrid/flexigrid.css" />
                <script type="text/javascript" src="resources/js/jquery1.3.2.js"></script>
                <script type="text/javascript" src="resources/flexigrid/flexigrid.js"></script>
                <script type="text/javascript">
                        $(document).ready(function(){
                                $("#flex1").flexigrid
                                                (
                                                {
                                                url: 'GetUsersList.action',
                                                dataType: 'json',
                                                colModel : [
                                                        //{display: '<input type="checkbox" alt="  Select All  ">', name : 'getAll', width : 50, sortable : true, align: 'center'},
                                                        {display: '  No.  ', name : 'id', width : 40, sortable : true, align: 'center'},
                                                        {display: '  Name  ', name : 'name', width : 40, sortable : true, align: 'center'},
                                                        {display: '  Gender  ', name : 'gender', width : 180, sortable : true, align: 'left'},
                                                        {display: '  Age  ', name : 'age', width : 120, sortable : true, align: 'left'},
                                                        {display: '  Birthday  ', name : 'birthday', width : 130, sortable : true, align: 'left', hide: true},
                                                        {display: '  Phone ', name : 'phone', width : 80, sortable : true, align: 'right'},
                                                        {display: '  Address  ', name : 'address', width : 80, sortable : true, align: 'right'}
                                                        ],
                                                searchitems : [
                                                        {display: '  No.  ', name : 'id'},
                                                        {display: '  Name  ', name : 'name', isdefault: true}
                                                        ],
                                                sortname: "id",
                                                sortorder: "asc",
                                                usepager: true,
                                                title: '  User list  ',
                                                useRp: true,
                                                checkbox : true,//   Checkbox if you want
                                                rowId : 'id',//   Checkbox binding line  id
                                                rp: 10,
                                                showTableToggleBtn: true,//  Fold
                                                resizable: true,
                                                striped: true, //  Speckle effect is displayed, the default is the parity in the form of interactive
                                                width: 700,
                                                height: 255
                                                }
                                                );   

                        });

</script>
        </head>
        <body>
                <h1>
                        Flexigrid Example Page
                </h1>
                <br />
                <br />
                <table></table>
                <br />
                <br />
        </body>
</html>

10, release testing, test results are as follows as indicated:

struts2 + hibernate + spring + flexgrid page implementation

相关文章