`
boyitech
  • 浏览: 86832 次
  • 性别: Icon_minigender_1
  • 来自: 南通
社区版块
存档分类
最新评论

Structs 2 Action 与 JQuery Datatable 的整合

阅读更多

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

 

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

 

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

<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
  • 大小: 38.1 KB
分享到:
评论
1 楼 陈加菲 2017-04-09  
博主你好,我最近在学习datatable,但是获取struts2返回的json数据一直不成功,表格里面没有数据,博主有遇到过这种情况吗?

相关推荐

    全球变风量(VAV)系统市场研究:年复合增长率(CAGR)为 5.8%

    在全球建筑行业不断追求节能与智能化发展的浪潮中,变风量(VAV)系统市场正展现出蓬勃的发展潜力。根据 QYResearch 报告出版商的深入调研统计,预计到 2031 年,全球变风量(VAV)系统市场销售额将飙升至 1241.3 亿元,在 2025 年至 2031 年期间,年复合增长率(CAGR)为 5.8%。这一令人瞩目的数据,不仅彰显了 VAV 系统在当今建筑领域的重要地位,更预示着其未来广阔的市场前景。​ 变风量系统的起源可追溯到 20 世纪 60 年代的美国。它犹如建筑空调系统中的 “智能管家”,能够敏锐地感知室内负荷或室内所需参数的变化,通过维持恒定的送风温度,自动、精准地调节空调系统的送风量,从而确保室内各项参数始终满足空调系统的严格要求。从系统构成来看,变风量系统主要由四个基本部分协同运作。变风量末端设备,包括 VAV 箱和室温控制器,如同系统的 “神经末梢”,负责接收室内环境变化的信号并做出初步响应;空气处理及输送设备则承担着对空气进行净化、加热、冷却等处理以及高效输送的重任;风管系统,涵盖新风、排风、送风、回风等管道,构建起了空气流通的 “高速公路”;而自动控制系统宛

    《基于YOLOv8的跆拳道训练系统》(包含源码、完整数据集、可视化界面、部署教程)简单部署即可运行。功能完善、操作简单,适合毕设或课程设计.zip

    资源内项目源码是来自个人的毕业设计,代码都测试ok,包含源码、数据集、可视化页面和部署说明,可产生核心指标曲线图、混淆矩阵、F1分数曲线、精确率-召回率曲线、验证集预测结果、标签分布图。都是运行成功后才上传资源,毕设答辩评审绝对信服的保底85分以上,放心下载使用,拿来就能用。包含源码、数据集、可视化页面和部署说明一站式服务,拿来就能用的绝对好资源!!! 项目备注 1、该资源内项目代码都经过测试运行成功,功能ok的情况下才上传的,请放心下载使用! 2、本项目适合计算机相关专业(如计科、人工智能、通信工程、自动化、电子信息等)的在校学生、老师或者企业员工下载学习,也适合小白学习进阶,当然也可作为毕设项目、课程设计、大作业、项目初期立项演示等。 3、如果基础还行,也可在此代码基础上进行修改,以实现其他功能,也可用于毕设、课设、作业等。 下载后请首先打开README.txt文件,仅供学习参考, 切勿用于商业用途。

    探究ChatGPT情感化交互对其用户情绪健康的多方法研究

    内容概要:本文探讨了ChatGPT这种高级语音模式的人工智能聊天机器人与用户的互动对其情绪健康的影响。研究采用了两种互补的方法:大规模平台数据分析和随机对照试验(RCT)。平台数据部分通过对超过400万次对话进行隐私保护的大规模自动化分析以及对4000多名用户的调查,揭示了高频率使用者表现出更多的情感依赖和较低的社会交往意愿。RCT部分则通过近1000名参与者为期28天的研究,发现语音模型相较于文本模型能带来更好的情绪健康效果,但长时间使用可能导致负面后果。此外,初始情绪状态较差的用户在使用更具吸引力的语音模型时,情绪有所改善。 适合人群:对人机交互、情感计算和社会心理学感兴趣的科研人员和技术开发者。 使用场景及目标:本研究旨在为AI聊天机器人的设计提供指导,确保它们不仅能满足任务需求,还能促进用户的心理健康。同时,也为政策制定者提供了关于AI伦理使用的思考。 其他说明:研究强调了长期使用AI聊天机器人可能带来的复杂心理效应,特别是对于那些已经感到孤独或社交孤立的人来说,过度依赖可能会加剧这些问题。未来的研究应该更加关注这些极端情况下的用户体验。

    Java反射性能优化:深入探讨setAccessible与MethodHandle的技术差异及应用场景

    Java 反射(Reflection)是一种强大的机制,允许程序在运行时检查和操作类的成员变量和方法。然而,传统的 `setAccessible(true)` 方式虽然便捷,但存在安全性问题,并且性能相对较低。在 Java 7 引入 `MethodHandle` 后,我们可以通过 `MethodHandles.Lookup.findVirtual()` 提供更优雅、高效的方式来访问对象属性。本文将对比这两种反射方式,并分析它们的优缺点。

    loongdomShop.tar.gz

    loongdomShop.tar.gz

    人工智能与人类行为对聊天机器人社会心理效应的纵向随机对照研究

    内容概要:本文探讨了不同交互模式(文本、中性语音、吸引人语音)和对话类型(开放式、非个人化、个人化)对聊天机器人使用者的心理社会效果(如孤独感、社交互动、情感依赖、不当使用)的影响。研究表明,在初期阶段,语音型聊天机器人比文本型更能缓解孤独感并减少情感依赖,但随着每日使用时间增加,这种优势逐渐消失,尤其是对于中性语音聊天机器人。此外,个人话题对话略微增加了孤独感,而非个人话题则导致更高的情感依赖。总体而言,高频率使用聊天机器人的用户表现出更多的孤独感、情感依赖和不当使用,同时减少了真实人际交往。研究还发现,某些个体特征(如依恋倾向、情绪回避)使用户更容易受到负面影响。 适合人群:心理学家、社会学家、人工智能研究人员以及关注心理健康和人机交互的专业人士。 使用场景及目标:①帮助理解不同类型聊天机器人对用户心理健康的潜在影响;②为设计更健康的人工智能系统提供指导;③制定政策和规范,确保聊天机器人的安全和有效使用。 其他说明:研究强调了进一步探索聊天机器人管理情感内容而不引发依赖或替代人际关系的重要性,呼吁更多跨学科的研究来评估长期影响。

    MP4575GF-Z 产品规格书

    MP4575GF-Z MP4575 TSSOP-20 降压型可调DC-DC电源芯片

    界面设计_SwiftUI_习惯养成_项目管理_1742850611.zip

    界面设计_SwiftUI_习惯养成_项目管理_1742850611.zip

    免安装版的logic软件包 支持波形实时查看 内含驱动文件

    免安装版的logic软件包。支持波形实时查看。内含驱动文件。

    基于Springboot+Mysql的学生毕业离校系统(含LW+PPT+源码+系统演示视频+安装说明).zip

    1. **系统名称**:学生毕业离校系统 2. **技术栈**:Java技术、MySQL数据库、Spring Boot框架、B/S架构、Tomcat服务器、Eclipse开发环境 3. **系统功能**: - **管理员功能**:首页、个人中心、学生管理、教师管理、离校信息管理、费用结算管理、论文审核管理、管理员管理、留言板管理、系统管理。 - **学生功能**:首页、个人中心、费用结算管理、论文审核管理、我的收藏管理。 - **教师功能**:首页、个人中心、学生管理、离校信息管理、费用结算管理、论文审核管理。

    WebSocket测试Demo程序

    配套文章:https://blog.csdn.net/gust2013/article/details/139608432

    蓝凌OA系统V15.0管理员手册

    蓝凌OA系统V15.0管理员手册

    《基于YOLOv8的生物样本识别系统》(包含源码、完整数据集、可视化界面、部署教程)简单部署即可运行。功能完善、操作简单,适合毕设或课程设计.zip

    资源内项目源码是来自个人的毕业设计,代码都测试ok,包含源码、数据集、可视化页面和部署说明,可产生核心指标曲线图、混淆矩阵、F1分数曲线、精确率-召回率曲线、验证集预测结果、标签分布图。都是运行成功后才上传资源,毕设答辩评审绝对信服的保底85分以上,放心下载使用,拿来就能用。包含源码、数据集、可视化页面和部署说明一站式服务,拿来就能用的绝对好资源!!! 项目备注 1、该资源内项目代码都经过测试运行成功,功能ok的情况下才上传的,请放心下载使用! 2、本项目适合计算机相关专业(如计科、人工智能、通信工程、自动化、电子信息等)的在校学生、老师或者企业员工下载学习,也适合小白学习进阶,当然也可作为毕设项目、课程设计、大作业、项目初期立项演示等。 3、如果基础还行,也可在此代码基础上进行修改,以实现其他功能,也可用于毕设、课设、作业等。 下载后请首先打开README.txt文件,仅供学习参考, 切勿用于商业用途。

    mips-gcc520-glibc222编译工具链.zip

    mips-gcc520-glibc222编译工具链.zip

    社交网络_React_Native_开发教程_学习资源_1742847416.zip

    app开发

    Swift编程语言的基础特性与应用开发入门教程

    内容概要:本文档详细介绍了Swift编程语言的基础知识,涵盖语言特点、基础语法、集合类型、控制流、函数定义、面向对象编程、可选类型、错误处理、协议与扩展以及内存管理等方面的内容。此外还简要提及了Swift与UIKit/SwiftUI的关系,并提供了进一步学习的资源推荐。通过这份文档,读者可以全面了解Swift的基本概念及其在iOS/macOS/watchOS/tvOS平台的应用开发中的使用方法。 适合人群:初学者或者希望从其他编程语言转向Swift的开发者。 使用场景及目标:帮助读者快速上手Swift编程,掌握其基本语法和特性,能够独立完成简单的程序编写任务,为进一步学习高级主题如并发编程、图形界面设计打下坚实的基础。 阅读建议:由于Swift是一门现代化的语言,拥有许多独特的特性和最佳实践方式,在学习过程中应当多加练习并尝试理解背后的原理。同时利用提供的官方文档和其他辅助材料加深印象。

    《基于YOLOv8的泰拳训练辅助系统》(包含源码、完整数据集、可视化界面、部署教程)简单部署即可运行。功能完善、操作简单,适合毕设或课程设计.zip

    资源内项目源码是来自个人的毕业设计,代码都测试ok,包含源码、数据集、可视化页面和部署说明,可产生核心指标曲线图、混淆矩阵、F1分数曲线、精确率-召回率曲线、验证集预测结果、标签分布图。都是运行成功后才上传资源,毕设答辩评审绝对信服的保底85分以上,放心下载使用,拿来就能用。包含源码、数据集、可视化页面和部署说明一站式服务,拿来就能用的绝对好资源!!! 项目备注 1、该资源内项目代码都经过测试运行成功,功能ok的情况下才上传的,请放心下载使用! 2、本项目适合计算机相关专业(如计科、人工智能、通信工程、自动化、电子信息等)的在校学生、老师或者企业员工下载学习,也适合小白学习进阶,当然也可作为毕设项目、课程设计、大作业、项目初期立项演示等。 3、如果基础还行,也可在此代码基础上进行修改,以实现其他功能,也可用于毕设、课设、作业等。 下载后请首先打开README.txt文件,仅供学习参考, 切勿用于商业用途。

    《基于YOLOv8的室内装修质量检测系统》(包含源码、完整数据集、可视化界面、部署教程)简单部署即可运行。功能完善、操作简单,适合毕设或课程设计.zip

    资源内项目源码是来自个人的毕业设计,代码都测试ok,包含源码、数据集、可视化页面和部署说明,可产生核心指标曲线图、混淆矩阵、F1分数曲线、精确率-召回率曲线、验证集预测结果、标签分布图。都是运行成功后才上传资源,毕设答辩评审绝对信服的保底85分以上,放心下载使用,拿来就能用。包含源码、数据集、可视化页面和部署说明一站式服务,拿来就能用的绝对好资源!!! 项目备注 1、该资源内项目代码都经过测试运行成功,功能ok的情况下才上传的,请放心下载使用! 2、本项目适合计算机相关专业(如计科、人工智能、通信工程、自动化、电子信息等)的在校学生、老师或者企业员工下载学习,也适合小白学习进阶,当然也可作为毕设项目、课程设计、大作业、项目初期立项演示等。 3、如果基础还行,也可在此代码基础上进行修改,以实现其他功能,也可用于毕设、课设、作业等。 下载后请首先打开README.txt文件,仅供学习参考, 切勿用于商业用途。

    《基于YOLOv8的雕塑识别系统》(包含源码、完整数据集、可视化界面、部署教程)简单部署即可运行。功能完善、操作简单,适合毕设或课程设计.zip

    资源内项目源码是来自个人的毕业设计,代码都测试ok,包含源码、数据集、可视化页面和部署说明,可产生核心指标曲线图、混淆矩阵、F1分数曲线、精确率-召回率曲线、验证集预测结果、标签分布图。都是运行成功后才上传资源,毕设答辩评审绝对信服的保底85分以上,放心下载使用,拿来就能用。包含源码、数据集、可视化页面和部署说明一站式服务,拿来就能用的绝对好资源!!! 项目备注 1、该资源内项目代码都经过测试运行成功,功能ok的情况下才上传的,请放心下载使用! 2、本项目适合计算机相关专业(如计科、人工智能、通信工程、自动化、电子信息等)的在校学生、老师或者企业员工下载学习,也适合小白学习进阶,当然也可作为毕设项目、课程设计、大作业、项目初期立项演示等。 3、如果基础还行,也可在此代码基础上进行修改,以实现其他功能,也可用于毕设、课设、作业等。 下载后请首先打开README.txt文件,仅供学习参考, 切勿用于商业用途。

Global site tag (gtag.js) - Google Analytics