Structs 2 Action 与 JQuery Datatable 的整合_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > Structs 2 Action 与 JQuery Datatable 的整合

Structs 2 Action 与 JQuery Datatable 的整合

 2014/12/2 19:11:20  boyitech  程序员俱乐部  我要评论(0)
  • 摘要:这篇文章主要讲述SSH框架下如何整合AngularJS,JQueryDatatable以及Bootstrap。废话少说,进入主题,本篇主要以代码粘贴为主。第一步:新建Maven项目,pom文件如下:<projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache
  • 标签:jQuery

这篇文章主要讲述SSH框架下如何整合AngularJS, JQuery Datatable 以及Bootstrap。?

?

废话少说,进入主题,本篇主要以代码粘贴为主。?

?

第一步:新建Maven项目,pom文件如下:

class="xml" name="code"><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.boyi.web</groupId>
	<artifactId>ssh-datatabase-example</artifactId>
	<version>1.0.0</version>
	<packaging>war</packaging>
	<name>ssh-datatabase-example</name>
	<description>ssh-datatable-example</description>
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<spring.version>3.1.0.RELEASE</spring.version>
		<struts.version>2.3.15</struts.version>
		<hibernate.version>4.2.0.Final</hibernate.version>
		<mysql.version>5.1.6</mysql.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.struts</groupId>
			<artifactId>struts2-core</artifactId>
			<version>${struts.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.struts</groupId>
			<artifactId>struts2-convention-plugin</artifactId>
			<version>${struts.version}</version>
		</dependency>

		<!-- JASON Plug-in -->
		<dependency>
			<groupId>org.apache.struts</groupId>
			<artifactId>struts2-json-plugin</artifactId>
			<version>${struts.version}</version>
		</dependency>
		
		<dependency>
			<groupId>org.apache.struts</groupId>
			<artifactId>struts2-spring-plugin</artifactId>
			<version>${struts.version}</version>
		</dependency>

		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>${hibernate.version}</version>
		</dependency>

		<!-- for JPA, use hibernate-entitymanager instead of hibernate-core -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-entitymanager</artifactId>
			<version>${hibernate.version}</version>
		</dependency>

		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-c3p0</artifactId>
			<version>${hibernate.version}</version>
		</dependency>
		
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>${mysql.version}</version>
		</dependency>
		
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
			<scope>provided</scope>
		</dependency>
		
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<version>1.6.12</version>
		</dependency>
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>1.6.12</version>
		</dependency>
		<dependency>
			<groupId>cglib</groupId>
			<artifactId>cglib</artifactId>
			<version>2.2</version>
		</dependency>
		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-core-asl</artifactId>
			<version>1.8.8</version>
		</dependency>
		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-mapper-asl</artifactId>
			<version>1.8.8</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>ssh</finalName>
	</build>
</project>

?可以看出SSH的版本

Spring : 3.1.0.RELEASE

Struts2: 2.3.15

Hibernate : 4.2.0.Final

?

?第二步: 设置web.xml

?

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <display-name>ssh-datatable-example</display-name>
  <filter>
  <filter-name>CharacterEncoding</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>CharacterEncoding</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>

 
 <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        /WEB-INF/dispatcher-servlet.xml
    </param-value>
</context-param>

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

 <filter>  
        <filter-name>struts2</filter-name>  
        <filter-class>  
            org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter              
        </filter-class>  
    </filter>  
    <filter-mapping>  
        <filter-name>struts2</filter-name>  
        <url-pattern>*.action</url-pattern>  
    </filter-mapping>  
</web-app>
?

?

第三步:设置dispatcher-servlet.xml

?

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:c="http://www.springframework.org/schema/c" xmlns:cache="http://www.springframework.org/schema/cache"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:sec="http://www.springframework.org/schema/security" xmlns:jee="http://www.springframework.org/schema/jee"
	xmlns:lang="http://www.springframework.org/schema/lang" xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
		http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.1.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
		http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
		http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.1.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
		http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd
		http://www.springframework.org/schema/tx  http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">

	<mvc:annotation-driven>
		<mvc:message-converters>
			<bean class="org.springframework.http.converter.StringHttpMessageConverter">
				<property name="supportedMediaTypes">
					<list>
						<value>text/html;charset=UTF-8</value>
						<value>text/plain;charset=UTF-8</value>
					</list>
				</property>
			</bean>
			<bean id="jsonHttpMessageConverter"
				class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
		</mvc:message-converters>
	</mvc:annotation-driven>

	<context:component-scan base-package="com.boyi.web"></context:component-scan>

	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
		destroy-method="close">
		<property name="driverClass" value="com.mysql.jdbc.Driver" />
		<property name="jdbcUrl"
			value="jdbc:mysql://localhost:3307/ssh?characterEncoding=UTF-8&amp;characterSetResults=UTF-8" />
		<property name="user" value="root" />
		<property name="password" value="admin" />
		<property name="maxPoolSize" value="100" />
		<property name="minPoolSize" value="20" />
		<property name="initialPoolSize" value="10" />
		<property name="maxIdleTime" value="1800" />
		<property name="acquireIncrement" value="10" />
		<property name="idleConnectionTestPeriod" value="600" />
		<property name="acquireRetryAttempts" value="30" />
		<property name="breakAfterAcquireFailure" value="false" />
		<property name="preferredTestQuery" value="SELECT NOW()" />
	</bean>

	<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
		<constructor-arg ref="dataSource"></constructor-arg>
	</bean>

	<!-- hibernate 需要的信息 -->
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="packagesToScan">
			<list>
				<value>com.boyi.web.entity</value>
			</list>
		</property>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
				<prop key="hibernate.show_sql">true</prop>
				<prop key="hibernate.format_sql">true</prop>
			</props>
		</property>
	</bean>
	<aop:aspectj-autoproxy expose-proxy="true" />

	<tx:annotation-driven transaction-manager="txManager" />
	<bean id="txManager"
		class="org.springframework.orm.hibernate4.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>

	<tx:advice id="txAdvice" transaction-manager="txManager">
		<tx:attributes>
			<tx:method name="save*" propagation="REQUIRED" />
			<tx:method name="add*" propagation="REQUIRED" />
			<tx:method name="create*" propagation="REQUIRED" />
			<tx:method name="insert*" propagation="REQUIRED" />
			<tx:method name="*" read-only="true" />
		</tx:attributes>
	</tx:advice>

	<aop:config proxy-target-class="true">
		<aop:advisor advice-ref="txAdvice"
			pointcut="execution(* com..service..*.*(..))" />
	</aop:config>
</beans>
?第四步,准备css和js目录

?

1. 从JQuery官网下载最新的jquery.min.js ,copy到js目录,这里我下载的是jQuery v1.11.1

2. 从Bootstrap官网下载最新的bootstrap.min.js,?bootstrap.min.css,分别copy到js和css目录中,这里我下载的是Bootstrap v3.3.0

3. 从Datatables官网下载最新的jquery.dataTables.min.js,?dataTables.bootstrap.min.js,dataTables.bootstrap.css, 分别copy到js和css目录中,?

目录结构如下:


第五步:写hibernate实体类

?

package com.boyi.web.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "PERSON")
public class Person {

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private int id;

	@Column(name = "NAME")
	private String name;

	@Column(name = "BIRTHDAY")
	private String birth;

	@Column(name = "GENDER")
	private String gender;

	public int getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}

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

	public String getBirth() {
		return birth;
	}

	public void setBirth(String birth) {
		this.birth = birth;
	}

	public String getGender() {
		return gender;
	}

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

}
?
?第六步:写hibernateDAO超

?

?

package com.boyi.web.dao;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Criterion;

public interface HqlBaseDao<T, PK extends Serializable> {
	int count();
	 /** 
     * Persist the newInstance object into database.
     * @param newInstance to save
     * @return The identifier
     **/
    PK save(T newInstance);

    /**
     * Save or update.
     * @param transientObject to save
     */
    void saveOrUpdate(T transientObject);
    
    /** 
     * Retrieve a persisted object with a given id from the database.
     * @param id to load
     * @return An object of type T
     */
    T load(PK id);
    
    /** 
     * Retrieve a persisted object with a given id from the database.
     * @param id to get
     * @return An object of type T
     */
    T get(PK id);
    /** 
     * Save changes made to a persistent object.  
     * @param transientObject object to update
     **/
    void update(T transientObject);

    /** 
     * Remove the given object from persistent storage in the database.
     * @param persistentObject object to delete.
     **/
    void delete(T persistentObject);
    
    /** 
     * Remove the given object from persistent storage in the database. 
     * @param s Query to execute 
     * @return A query object
     **/
    Query getQuery(String s);
    
    /** Deletes an object of a given Id. Will load the object internally so 
     * consider using delete (T obj) directly.
     * @param id Id of record
     */
    void delete(PK id);
    
    
    /** Delete object from disk.
     * @param persistentObject to delete
     * @param session to use
     * 
     */
    void delete(T persistentObject, Session session);

    /** Deletes an object of a given Id. Will load the object internally so consider using delete (T obj) directly.
     * @param id to delete 
     * @param session to use
     */
    void delete(PK id, Session session);

    /**
     * Loads the given Object.
     * @param id to load
     * @param session to use
     * @return  an object of type T
     */
    T load(PK id, Session session);

    /**
     * Loads the given Object.
     * @param id Id to load
     * @param session to use
     * @return An object of type T
     */
    T get(PK id, Session session);

    /** Save object to disk using given session.
     * @param o to save
     * @param session to use
     * @return the id of the saved object
     * 
     */
    PK save(T o, Session session);

    /** Save or update given object.
     * @param o item to save.
     * @param session to use
     * 
     */
    void saveOrUpdate(T o, Session session); 

    /** Update given object.
     * @param o item to update 
     * @param session to use
     * 
     */
    void update(T o, Session session); 
    
    /** Refreshes the object of type T.
     * @param persistentObject to refresh
     */
    void refresh(T persistentObject);
    
    /**
     * Get a query handle.
     * @param s Query to use
     * @param session to use
     * @return Query object
     */
    Query getQuery(String s, Session session);

    /** FindByExample.
     * @param exampleInstance to use
     * @param excludeProperty to exclude
     * @return A list of objects
     */
    List<T> findByExample(T exampleInstance, String... excludeProperty);
    
    /** Returns a list of objects.
     * @return list of objects
     */
    List<T> findAll();
    
    List<T> findListForPage(String hql, Integer page, Integer size, Object... objects);
    
    /** Flushes the cache of the currently-used session.
     * 
     */
    void flush();
    
    /** Object to evict from cache.
     * @param obj Object to evict
     */
    void evict(Object obj);
    
    /** Hibernate wrapper.
     * @param criterion to filter.
     * @return list of objects
     */
    List<T> findByCriteria(Criterion... criterion);
}
?
package com.boyi.web.dao.impl;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Example;
import org.springframework.beans.factory.annotation.Autowired;

import com.boyi.web.dao.HqlBaseDao;

public class HqlBaseDaoImpl<T, PK extends Serializable> implements HqlBaseDao<T, PK>{

	/** Class type. */
	Class<T> type;
	
	@Autowired  
	SessionFactory sessionFactory;

	/**
	 * Default bean constructor for spring.
	 */
	public HqlBaseDaoImpl() {
		// default constructor for spring
	}

	/**
	 * Constructor.
	 * 
	 * @param type
	 *            class type
	 */
	public HqlBaseDaoImpl(Class<T> type) {
		this.type = type;
	}

	/**
	 * Helper functions.
	 * 
	 * @return the currently set class
	 */
	public Class<T> getPersistentClass() {
		return this.type;
	}

	/**
	 * Delete persistentObject from DB.
	 * 
	 * @param persistentObject
	 *            object to delete.
	 */
	public void delete(T persistentObject) {
		getSession().delete(persistentObject);
	}

	/**
	 * Deletes an object of a given Id. Will load the object internally so
	 * consider using delete (T obj) directly
	 * 
	 * @param id
	 *            Delete key
	 */
	public void delete(PK id) {
		getSession().delete(load(id));
	}

	/**
	 * Loads the given Object.
	 * 
	 * @param id
	 *            to load
	 * @return T Loaded object
	 */
	@SuppressWarnings("unchecked")
	public T load(PK id) {
		return (T) getSession().load(this.type, id);
	}

	/**
	 * Loads the given Object.
	 * 
	 * @param id
	 *            Id to load
	 * @return An object of type T
	 */
	@SuppressWarnings("unchecked")
	public T get(PK id) {
		return (T) getSession().get(this.type, id);
	}

	/**
	 * Item to save.
	 * 
	 * @param o
	 *            object to save
	 * @return PK
	 */
	@SuppressWarnings("unchecked")
	public PK save(T o) {
		return (PK) getSession().save(o);
	}

	/**
	 * Item to refresh.
	 * 
	 * @param o
	 *            object to refresh
	 */
	public void refresh(T o) {
		getSession().refresh(o);
	}

	/**
	 * Item to saveOrUpdate.
	 * 
	 * @param o
	 *            item to save.
	 */
	public void saveOrUpdate(T o) {
		getSession().saveOrUpdate(o);
	}

	/**
	 * Update object.
	 * 
	 * @param o
	 *            object to update
	 */
	public void update(T o) {
		getSession().update(o);
	}

	/**
	 * Gets the current session in use (creates one if necessary).
	 * 
	 * @return Session object
	 */
	public Session getSession() {
		return sessionFactory.getCurrentSession();
	}

	/**
	 * Get query.
	 * 
	 * @param s
	 *            Query to execute.
	 * @return Query object
	 */
	public Query getQuery(String s) {
		return getSession().createQuery(s);
	}

	/**
	 * Get Session factory.
	 * 
	 * @return SessionFactory Object
	 */
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	/**
	 * Set session factory.
	 * 
	 * @param sessionFactory
	 *            object
	 */
	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	/**
	 * Delete object.
	 * 
	 * @param persistentObject
	 *            to delete
	 * @param session
	 *            to use
	 * 
	 */
	public void delete(T persistentObject, Session session) {
		session.delete(persistentObject);
	}

	/**
	 * Deletes an object of a given Id. Will load the object internally so
	 * consider using delete (T obj) directly.
	 * 
	 * @param id
	 *            to delete
	 * @param session
	 *            to use
	 */
	public void delete(PK id, Session session) {
		session.delete(load(id));
	}

	/**
	 * Loads the given Object.
	 * 
	 * @param id
	 *            to load
	 * @param session
	 *            to use
	 * @return an object of type T
	 */
	@SuppressWarnings("unchecked")
	public T load(PK id, Session session) {
		return (T) session.load(this.type, id);
	}

	/**
	 * Loads the given Object.
	 * 
	 * @param id
	 *            Id to load
	 * @param session
	 *            Session to use
	 * @return An object of type T
	 */
	@SuppressWarnings("unchecked")
	public T get(PK id, Session session) {
		return (T) session.get(this.type, id);
	}

	/**
	 * Save object.
	 * 
	 * @param o
	 *            to save
	 * @param session
	 *            to use
	 * @return the id of the saved object
	 * 
	 */
	@SuppressWarnings("unchecked")
	public PK save(T o, Session session) {
		return (PK) session.save(o);
	}

	/**
	 * Save Or Update object.
	 * 
	 * @param o
	 *            to save
	 * @param session
	 *            to use.
	 * 
	 */
	public void saveOrUpdate(T o, Session session) {
		session.saveOrUpdate(o);
	}

	/**
	 * Update record.
	 * 
	 * @param o
	 *            to update
	 * @param session
	 *            to use
	 * 
	 */
	public void update(T o, Session session) {
		session.update(o);
	}

	/**
	 * GetQuery.
	 * 
	 * @param s
	 *            to return
	 * @param session
	 *            to use
	 * @return Query object
	 */
	public Query getQuery(String s, Session session) {
		return session.createQuery(s);
	}

	/**
	 * Wrapper around hibernate functions.
	 * 
	 * @param criterion
	 *            to use
	 * @return A list of matching objects
	 */
	@SuppressWarnings("unchecked")
	public List<T> findByCriteria(Criterion... criterion) {
		Session session = getSession();
		Criteria crit = session.createCriteria(getPersistentClass());

		for (Criterion c : criterion) {
			crit.add(c);
		}
		return crit.list();
	}

	/**
	 * FindAll.
	 * 
	 * @return A list of all the objects
	 */
	public List<T> findAll() {
		return findByCriteria();
	}

	/**
	 * Flushes the cache of the currently-used session.
	 * 
	 */
	public void flush() {
		getSession().flush();
	}

	/**
	 * Object to evict from cache.
	 * 
	 * @param obj
	 *            Object to evict
	 */
	public void evict(Object obj) {
		getSession().evict(obj);
	}

	/**
	 * FindByExample.
	 * 
	 * @param exampleInstance
	 *            to use
	 * @param excludeProperty
	 *            to use
	 * @return List of matching objects
	 */
	@SuppressWarnings("unchecked")
	public List<T> findByExample(T exampleInstance, String... excludeProperty) {
		Criteria crit = getSession().createCriteria(getPersistentClass());
		Example example = Example.create(exampleInstance);
		for (String exclude : excludeProperty) {
			example.excludeProperty(exclude);
		}
		crit.add(example);
		return crit.list();
	}

	public List<T> findListForPage(String hql, Integer page, Integer size, Object... objects) {

		Query query = getSession().createQuery(hql);
		if (objects != null) {
			for (int i = 0; i < objects.length; i++) {
				query.setParameter(i, objects[i]);
			}
		}
		if (page != null && size != null) {
			query.setFirstResult((page - 1) * size).setMaxResults(size);
		}
		@SuppressWarnings("unchecked")
		List<T> list = query.list();
		return list;
	}

	@Override
	public int count() {
		Query query = getSession().createQuery("select count(*) from " + this.type.getName());
		return ((Long)query.iterate().next()).intValue();
	}

}
?第七步:写hibernateDAO

?

package com.boyi.web.dao;

import java.io.Serializable;
import java.util.List;

import com.boyi.web.entity.Person;

public interface PersonDao extends HqlBaseDao<Person, Serializable> {
	
	
	/**
	 * 
	 * @param page
	 * @param pageSize
	 * @return the person by pagination
	 * @throws Exception
	 */
	public List<Person> list(Integer page, Integer pageSize) throws Exception;
}
?
package com.boyi.web.dao.impl;

import java.io.Serializable;
import java.util.List;

import org.springframework.stereotype.Repository;

import com.boyi.web.dao.PersonDao;
import com.boyi.web.entity.Person;

@Repository 
public class PersonDaoImpl extends HqlBaseDaoImpl<Person, Serializable> implements PersonDao {

	public PersonDaoImpl() {
		super(Person.class);
	}
	
	public List<Person> list(Integer page, Integer pageSize) throws Exception {
		return findListForPage("from Person", page, pageSize);
	}

}
??第八步:写Service
package com.boyi.web.service;

import java.util.List;

import com.boyi.web.entity.Person;

public interface PersonService {
	/**
	 * return the person counts
	 * @return
	 * @throws Exception
	 */
	public int count() throws Exception;
	
	/**
	 * 
	 * @param page
	 * @param pageSize
	 * @return the person by pagination
	 * @throws Exception
	 */
	public List<Person> list(Integer page, Integer pageSize) throws Exception;
}
?
package com.boyi.web.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.boyi.web.dao.PersonDao;
import com.boyi.web.entity.Person;
import com.boyi.web.service.PersonService;

@Service
public class PersonServiceImpl implements PersonService {

	@Autowired
	PersonDao dao;
	
	public int count() throws Exception {
		return dao.count();
	}

	public List<Person> list(Integer page, Integer pageSize) throws Exception {
		return dao.list(page, pageSize);
	}

}
? 九步:写Action
package com.boyi.web.action;

import java.util.List;

import javax.annotation.Resource;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.stereotype.Controller;

import com.boyi.web.entity.Person;
import com.boyi.web.service.PersonService;
import com.opensymphony.xwork2.ActionSupport;

@ParentPackage("json-default")
@Controller
public class PersonAjaxAction extends ActionSupport {

	private static final long serialVersionUID = 1L;

	/**
	 * datatable start value
	 */
	private int start;

	/**
	 * datatable page size
	 */
	private int length;
	private int recordsTotal;
	private int recordsFiltered;
	private int recordsDisplay;
	private List<Person> aaData;
	@Resource
	PersonService service;

	@Override
	@Action(value = "/persons", results = { @Result(name = "success", type = "json") })
	public String execute() throws Exception {
		// calculate the total records
		recordsTotal = service.count();

		// calculate the current page
		int page = start / length + 1;

		// query the persons
		aaData = service.list(page, length);
		
		recordsFiltered = recordsTotal;
		
		recordsDisplay = aaData.size();
		
		return ActionSupport.SUCCESS;
	}

	public int getStart() {
		return start;
	}

	public void setStart(int start) {
		this.start = start;
	}

	public int getLength() {
		return length;
	}

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

	public int getRecordsTotal() {
		return recordsTotal;
	}

	public void setRecordsTotal(int recordsTotal) {
		this.recordsTotal = recordsTotal;
	}

	public int getRecordsFiltered() {
		return recordsFiltered;
	}

	public void setRecordsFiltered(int recordsFiltered) {
		this.recordsFiltered = recordsFiltered;
	}

	public List<Person> getAaData() {
		return aaData;
	}

	public void setAaData(List<Person> aaData) {
		this.aaData = aaData;
	}

	public static long getSerialversionuid() {
		return serialVersionUID;
	}

	public int getRecordsDisplay() {
		return recordsDisplay;
	}

	public void setRecordsDisplay(int recordsDisplay) {
		this.recordsDisplay = recordsDisplay;
	}
	
}
? 第十步:写JSP
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>SHH - Datatable - Example</title>
<link rel='stylesheet' type='text/css' href='css/bootstrap.min.css'>
<link rel='stylesheet' type='text/css' href='css/dataTables.bootstrap.css'>
</head>
<body>
	<hr>
	<center>
		<h1>SHH - Datatable - Example</h1>
	</center>
	<hr>
	<div class="container">
		<div class="row">
			<table class="table table-striped table-bordered table-hover datatable" id="example"></table>
		</div>
		
	</div>
	
	<script src='js/jquery.min.js'></script>
	<script src='js/jquery.dataTables.min.js'></script>
	<script src='js/dataTables.bootstrap.min.js'></script>
	<script src='js/bootstrap.min.js'></script>
	<script src='js/index.js'></script>
</body>
</html>
? 第十一步:写JS
$(document).ready(function() {

	$("#example").dataTable({
		dom:
			"<'row'<'col-sm-12'tr>>" +
			"<'row'<'col-sm-3'i><'col-sm-3'l><'col-sm-6'p>>",
		"processing" : true,
		"serverSide" : true,
		"length" : 5,
		"paging" : true,
		"ordering" : true,
		"pageLength" : 5,
		"paginationType" : "full_numbers",
		"lengthMenu" : [ 5, 10, 25, 50, 75, 100 ],
		"ajax" : {
			"url" : "persons.action",
			"type" : "POST"
		},
		"columns" : [ {
			"title" : "ID",
			"data" : "id",
			"visible" : true,
			"orderable" : true,
			"render" : function(data, type, full, meta){
				return '<a href="http://www.baidu.com">' + data +'</a>';
			}
		}, {
			"title" : "NAME",
			"data" : "name",
			"visible" : true,
			"orderable" : true
		}, {
			"title" : "BIRTHDAY",
			"data" : "birth",
			"visible" : true,
			"orderable" : true
		}, {
			"title" : "GENDER",
			"data" : "gender",
			"visible" : true,
			"orderable" : true
		} ],
		"language" : {
			"emptyTable" : "没有数据",
			"info" : "显示 第 _START_ 到 _END_ 条数据  总共 _TOTAL_ 条数据 ",
			"infoEmpty" : "没有数据",
			"infoFiltered" : "(filtered from _MAX_ total entries)",
			"infoPostFix" : "",
			"thousands" : ",",
			"lengthMenu" : "每页显示条数 _MENU_ ",
			"loadingRecords" : "加载中...",
			"processing" : "处理中...",
			"search" : "搜索:",
			"zeroRecords" : "找不到匹配的数据",
			"paginate" : {
				"first" : "首页",
				"last" : "尾页",
				"next" : "下页",
				"previous" : "上页"
			}
		}
	});

});
?第十二步:数据库建表
DROP DATABASE IF EXISTS `ssh`;
CREATE DATABASE IF NOT EXISTS `ssh` 
USE `ssh`;

DROP TABLE IF EXISTS `PERSON`;
CREATE TABLE IF NOT EXISTS `PERSON` (
  `ID` int(9) NOT NULL AUTO_INCREMENT,
  `NAME` varchar(20) NOT NULL,
  `BIRTHDAY` varchar(20) NOT NULL,
  `GENDER` varchar(5) NOT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=22 DEFAULT CHARSET=utf8;
INSERT INTO `PERSON` (`ID`, `NAME`, `BIRTHDAY`, `GENDER`) VALUES
	(1, 'NAME1', '1984-01-02', '男'),
	(2, 'NAME2', '1984-01-03', '男'),
	(3, 'NAME3', '1984-01-04', '男'),
	(4, 'NAME4', '1984-01-05', '女'),
	(5, 'NAME5', '1984-01-06', '男'),
	(6, 'NAME6', '1984-01-07', '女'),
	(7, 'NAME7', '1984-01-08', '男'),
	(8, 'NAME8', '1984-01-09', '男'),
	(9, 'NAME9', '1984-01-10', '男'),
	(10, 'NAME10', '1984-01-11', '女'),
	(11, 'NAME11', '1984-01-12', '男'),
	(12, 'NAME12', '1984-01-13', '男'),
	(13, 'NAME13', '1984-01-14', '女'),
	(14, 'NAME14', '1984-01-15', '男'),
	(15, 'NAME15', '1984-01-16', '男'),
	(16, 'NAME16', '1984-01-17', '女'),
	(17, 'NAME17', '1984-01-18', '男'),
	(18, 'NAME18', '1984-01-19', '人妖'),
	(19, 'NAME19', '1984-01-20', '男'),
	(20, 'NAME20', '1984-01-12', '男'),
	(21, 'NAME21', '1984-01-22', '男');
?第十三步:打包部署,测试

?? 完整代码在附件中,有兴趣的可以下载。
  • 大小: 41.8 KB
  • ssh-datatabase-example.7z (142.6 KB)
  • 下载次数: 1
  • 大小: 38.1 KB
  • 查看图片附件
发表评论
用户名: 匿名