配置文件集

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_2_5.xsd" version="2.5">
</web-app>

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</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>/*</url-pattern>
</filter-mapping>


<filter>
<filter-name>hibernateFilter</filter-name>
<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>hibernateFilter</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>


<filter>
<filter-name>characterEncodingFilter</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>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<!-- Spring MVC配置 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-config.xml</param-value>
</context-param>
<servlet>
<servlet-name>spring-mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring-mvc</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>


struts.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<!--常量重新定义 -->
<!-- 开发模式下使用,这样可以打印出更详细的错误信息 -->
<constant name="struts.devmode" value="true" />
<!-- 国际化 -->
<constant name="struts.custom.i18n.resources" value="i18n" />
<!-- <constant name="struts.multipart.saveDir" value="D:/" /> -->
<constant name="struts.multipart.maxSize" value="2097152000" />
<constant name="struts.i18n.encoding" value="UTF-8" />

<!-- 自动重新加载映射加载 -->
<constant name="struts.convention.classes.reload" value="true" />
<!-- 搜寻action的根包 Convention默认的根packages -->
<!-- <constant name="struts.convention.packages.locators" value="" /> -->
<!-- 国际化 -->
<constant name="struts.i18n.reload" value="true" />
<!-- 重新设置Struts 2的请求后缀,默认为*.action -->
<constant name="struts.action.extension" value="action" />
<!-- 当struts的配置文件修改后,系统是否自动重新加载该文件 -->
<constant name="struts.configuration.xml.reload" value="true" />
<!-- action 对象是由Spring负责创建 -->
<constant name="struts.objectFactory" value="spring" />

<include file="struts_*.xml" />
</struts>

struts_*.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>

<package name="example" namespace="/example" extends="struts-default">
<action name="example_*" class="ExampleAction" method="{1}">
<result name="success" type="redirect">example_allExamType.action</result>
<result name="allExample">/WEB-INF/example/allExample.jsp</result>
<result name="saveBefore">/WEB-INF/example/addExample.jsp</result>
<result name="findExampleById">/WEB-INF/example/updateExample.jsp</result>
<result name="error">/WEB-INF/example/error.jsp</result>
</action>
</package>
</struts>

struts2中的标签
首先需要引用 <%@taglib prefix="s" uri="/struts-tags"%>
1.<s:if></s:if> 判断标签 后面可跟 <s:else>
2.<s:iterator> </s:iterator> 迭代 就是循环 for的又一种说法而已
3.<s:include></s:include> 引入标签 可以把一个JSP页面或者servlet带入一个页面中 比如说 我们有一个框架页面 但是很多页面都需要类似的框架
参数不同 所以没必要写那么多的页面 导入并且传入参数就好 例子分页显示代码
4.<s:property></s:property> 输出标签
5.<s:set></s:set> 标签赋予变量一个特定范围内的值
6.<s:form></s:form> 表单标签
7.<s:testarea></s:textarea> 文本域标签
8.<s:select></s:select> 下拉标签
9.<s:url></s:url> 声明一个url的路径
简单说就是将这些标签放到jsp页面中的显示格式
其中最常用到的 是判断<s:if></s:if> 循环<s:iterator></s:terator> 输出<s:property></s:property>

Spring:
<?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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
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.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" lazy-init="true" >
<property name="ignoreResourceNotFound" value="true" />
<property name="location">
<value>classpath:/database.properties</value>
</property>
</bean>

<context:property-placeholder location="classpath:/database.properties" />





Hibernate:
<!--创建数据源和c3p0连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="${driverClass}" />
<property name="jdbcUrl" value="${jdbcUrl}" />
<property name="user" value="${user}"></property>
<property name="password" value="${password}"></property>
<!--c3p0的配置 -->
<!--连接池中保留的最小连接数。 -->
<property name="minPoolSize" value="5" />
<!--连接池中保留的最大连接数。Default: 15 -->
<property name="maxPoolSize" value="30" />
<!--初始化时获取的连接数,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->
<property name="initialPoolSize" value="10" />
<!--最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->
<property name="maxIdleTime" value="60" />
<!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->
<property name="acquireIncrement" value="5" />
<!--JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量。但由于预缓存的statements 属于单个connection而不是整个连接池。所以设置这个参数需要考虑到多方面的因素。 如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 0 -->
<property name="maxStatements" value="0" />
<!--每60秒检查所有连接池中的空闲连接。Default: 0 -->
<property name="idleConnectionTestPeriod" value="60" />
<!--定义在从数据库获取新连接失败后重复尝试的次数。Default: 30 -->
<property name="acquireRetryAttempts" value="30" />
<!--获取连接失败将会引起所有等待连接池来获取连接的线程抛出异常。但是数据源仍有效保留,并在下次调用getConnection()的时候继续尝试获取连接。如果设为true,那么在尝试获取连接失败后该数据源将申明已断开并永久关闭。Default: false -->
<property name="breakAfterAcquireFailure" value="true" />
<!--因性能消耗大请只在需要的时候使用它。如果设为true那么在每个connection提交的时候都将校验其有效性。 建议使用idleConnectionTestPeriod或automaticTestTable等方法来提升连接测试的性能。Default: false -->
<property name="testConnectionOnCheckout" value="false" />
</bean>

<!-- 创建sessionFactory模板 -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
<!-- 指定Hibernate在何时释放JDBC连接. 默认情况下,直到Session被显式关闭或被断开连接时,才会释放JDBC连接. -->
<prop key="hibernate.connection.release_mode">${hibernate.connection.release_mode}</prop>
<!-- Hibernate连接数据库超时设置 -->
<prop key="hibernate.autoReconnect">${hibernate.autoReconnect}</prop>
<prop key="hibernate.jdbc.batch_size">${hibernate.jdbc.batch_size}</prop>
<prop key="hibernate.jdbc.fetch_size">${hibernate.jdbc.fetch_size}</prop>
<!--connection.useUnicode连接数据库时是否使用Unicode编码 -->
<prop key="Connection.useUnicode">${hibernate.connection.useUnicode}</prop>
<!--connection.characterEncoding连接数据库时数据的传输字符集编码方式,最好设置为UTF-8 -->
<prop key="connection.characterEncoding">${hibernate.connection.characterEncoding}</prop>
<!-- 开启二级缓存 -->
<prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop>
<prop key="hibernate.cache.provider_class">${hibernate.cache.provider_class}</prop>
<!-- 开启二级缓存的查询缓存 -->
<prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
</props>
</property>
<property name="mappingLocations">
<list>
<value>classpath:/**/po/*.hbm.xml</value>
</list>
</property>
</bean>

<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
</bean>

<!--配置hibernate的事务管理器 -->
<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>

<tx:advice id="txadvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="save*" propagation="REQUIRED" isolation="DEFAULT"/>
<tx:method name="delete*" propagation="REQUIRED" isolation="DEFAULT"/>
<tx:method name="update*" propagation="REQUIRED" isolation="DEFAULT"/>
<tx:method name="find*" read-only="true"/>
<tx:method name="get*" read-only="true"/>
</tx:attributes>
</tx:advice>
<!--配置切面 -->
<aop:config>
<aop:pointcut id="commonPointcut" expression="execution(* *..service..*.*(..))"/>
<aop:advisor advice-ref="txadvice" pointcut-ref="commonPointcut"/>
</aop:config>
<aop:aspectj-autoproxy proxy-target-class="true" />

<!-- 声明式事务 -->
<tx:annotation-driven proxy-target-class="true" />
@Transactional
org.springframework.transaction.annotation.Transactional




database.properties:
#------------ MySQL ------------
driverClass=com.mysql.jdbc.Driver
jdbcUrl=jdbc\:mysql\://localhost\:3306/zxks?useUnicode\=true&autoReconnect\=true&characterEncoding\=UTF-8&zeroDateTimeBehavior\=convertToNull
user=root
password=root
#设置数据库方言
hibernate.dialect=org.hibernate.dialect.MySQLDialect
#是否显示SQL
hibernate.show_sql=true
#格式化输出到控制台的SQL语句
hibernate.format_sql=false
#Hibernate连接数据库超时设置
hibernate.autoReconnect=true
#指定Hibernate在何时释放JDBC连接. 默认情况下,直到Session被显式关闭或被断开连接时,才会释放JDBC连接
hibernate.connection.release_mode=auto
#hibernate.connection.useUnicode连接数据库时是否使用Unicode编码
hibernate.connection.useUnicode=true
#hibernate.connection.characterEncoding连接数据库时数据的传输字符集编码方式,最好设置为UTF-8
hibernate.connection.characterEncoding=UTF-8
#设置自动创建|更新|验证数据库表结构
hibernate.hbm2ddl.auto=none
#开启二级缓存
hibernate.cache.use_second_level_cache=false
#使用缓存产品 -- 备选的缓存产品org.hibernate.cache.OSCacheProvider
hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider
#开启二级缓存的查询缓存
hibernate.cache.use_query_cache=false
#数据库批量查询数
hibernate.jdbc.fetch_size=50
#数据库批量更新数
hibernate.jdbc.batch_size=30

 


jdbc.driver=oracle.jdbc.OracleDriver
jdbc.url=jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=wserver)(PORT=1521)))(CONNECT_DATA=(SERVICE_NAME=CLASSR1)))
jdbc.user=tianlihu
jdbc.password=tianlihu

#设置数据库方言
hibernate.dialect=org.hibernate.dialect.Oracle10gDialect
#是否显示SQL
hibernate.show_sql=true
#格式化输出到控制台的SQL语句
hibernate.format_sql=false
#Hibernate连接数据库超时设置
hibernate.autoReconnect=true
#指定Hibernate在何时释放JDBC连接. 默认情况下,直到Session被显式关闭或被断开连接时,才会释放JDBC连接
hibernate.connection.release_mode=auto
#connection.useUnicode连接数据库时是否使用Unicode编码
Connection.useUnicode=true
#connection.characterEncoding连接数据库时数据的传输字符集编码方式,最好设置为UTF-8
connection.characterEncoding=UTF-8
#设置自动创建|更新|验证数据库表结构
hibernate.hbm2ddl.auto=none
#开启二级缓存
hibernate.cache.use_second_level_cache=false
#使用缓存产品 -- 备选的缓存产品org.hibernate.cache.EhCacheProvider
hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider
#开启二级缓存的查询缓存
hibernate.cache.use_query_cache=false
#数据库批量查询数
hibernate.jdbc.fetch_size=50
#数据库批量更新数
hibernate.jdbc.batch_size=30




*.hbm.xml
<?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>
<class name="com.tianlihu.User" table="ac_user">
<id name="usersId" type="java.lang.Integer" column="userId">
<generator class="native"/>
</id>
<property name="name" type="java.lang.String" column="name" />
</class>
</hibernate-mapping>








log4j.properties:
log4j.rootCategory=error,stdout

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=[HYYT] %p [%t] %C.%M(%L) | %m%n

log4j.logger.com.opensymphony.xwork2.ognl.OgnlValueStack=ERROR

SpringMVC配置
<?xml version="1.0" encoding="GBK"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<aop:aspectj-autoproxy proxy-target-class="true" />

<context:component-scan base-package="com.bwie.netpay" />
<mvc:annotation-driven />

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="cacheSeconds" value="0" />
<property name="messageConverters">
<util:list id="beanList">
<ref bean="stringHttpMessageConverter" />
<ref bean="byteArrayHttpMessageConverter" />
<ref bean="resourceHttpMessageConverter" />
<ref bean="sourceHttpMessageConverter" />
<ref bean="xmlAwareFormHttpMessageConverter" />
</util:list>
</property>
</bean>
<bean id="stringHttpMessageConverter" class="org.springframework.http.converter.StringHttpMessageConverter"/>
<bean id="byteArrayHttpMessageConverter" class="org.springframework.http.converter.ByteArrayHttpMessageConverter" />
<bean id="resourceHttpMessageConverter" class="org.springframework.http.converter.ResourceHttpMessageConverter" />
<bean id="sourceHttpMessageConverter" class="org.springframework.http.converter.xml.SourceHttpMessageConverter" />
<bean id="xmlAwareFormHttpMessageConverter" class="org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter" />

<mvc:resources mapping="/static/script/**" location="/script/" />
<mvc:resources mapping="/static/style/**" location="/style/" />
<mvc:resources mapping="/static/image/**" location="/image/" />
<mvc:resources mapping="/static/validator/**" location="/validator/" />
<mvc:resources mapping="/static/component/**" location="/component/" />
<mvc:resources mapping="/static/upload/**" location="/upload/" />

<bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="configLocation" value="classpath:ftl.properties" />
<property name="templateLoaderPath" value="/WEB-INF/views" />
<property name="defaultEncoding" value="GBK" />
<property name="freemarkerSettings">
<props>
<prop key="template_update_delay">10</prop>
<prop key="locale">zh_CN</prop>
</props>
</property>
</bean>
<bean id="viewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<property name="contentType" value="text/html;charset=GBK" />
<property name="prefix" value="" />
<property name="cache" value="true" />
<property name="suffix">
<value>.html</value>
</property>
</bean>

<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>

ftl.properties
classic_compatible=true
#auto_import=template/common.ftl as common
datetime_format=yyyy-MM-dd HH:mm:ss
date_format=yyyy-MM-dd
time_format=HH:mm:ss
number_format=#.####


#locale=zh_CN
template_update_delay=5
#number_format=0.######;
#boolean_format=true,false
#auto_import="/WEB-INF/ftl_lib/ponyjava.com/index.ftl" as p, "/WEB-INF/ftl_lib/jeecms/index.ftl" as cms
#whitespace_stripping=true
#default_encoding=UTF-8
#tag_syntax=auto_detect
#url_escaping_charset=UTF-8
#struts.freemarker.templatesCache=true
#template_update_delay=60000

jsp viewResolver
<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>

<!-- jackson Configuration -->
<bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>


*.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path;
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<base href="<%=basePath%>">
<title>用户列表</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>

<body>
<form action="${pageContext.request.contextPath}/user/list.action" method="get">
<select name="fieldName">
<option value="-1">全部</option>
<c:forEach items="${requestScope.users}" var="user">
<option value="${user.userId}">${user.type}</option>
</c:forEach>
</select>
<input type="submit" value="查询" />
</form>
<table border="1" cellpadding="0" cellspacing="0" width="90%">
<tr>
<td>用户ID</td>
<td>名称</td>
<td>操作</td>
</tr>
<c:forEach items="${requestScope.users}" var="user">
<tr>
<td>${user.userId}</td>
<td>${user.name}</td>
<td><c:if test="${user.status == 0}">未激活</c:if><c:if test="${user.status == 1}">活动</c:if></td>
<td><c:choose><c:when test="${user.status == 0}">未激活</c:when><c:when test="${user.status == 1}">活动</c:when><c:otherwise>其他</c:otherwise></c:choose></td>
<td><a href="usere/usere_findusereById.action?usere.usereId=${usere.usereId}">更新</a>&nbsp;<a href="usere/usere_deleteusereById.action?usere.usereId=${usere.usereId}">删除</a></td>
</tr>
</c:forEach>
</table>
<div align="center"><a href="usere/usere_saveBefore.action">添加用户</a></div>
</body>
</html>
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.SQLException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;

import javax.annotation.Resource;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import com.etiansoft.nco.common.Page;

@Repository
@SuppressWarnings("unchecked")
public class HibernateDao<T> {

@Resource
private HibernateTemplate hibernateTemplate;

public T findById(Integer id) {
Class<T> clazz = getRawClass();
return hibernateTemplate.get(clazz, id);
}

public Page findPage(int currentPage, int pageSize) {
return findPage(currentPage, pageSize, null);
}

public Page findPage(int currentPage, int pageSize, LinkedHashMap<String, Object> parameters) {
Page page = new Page();
page.setCount(count(parameters));
page.setCurrentPage(currentPage);
page.init();
page.setRecords(findRecords(page.getStartRecord(), pageSize, parameters));
return page;
}

public List<T> findAll() {
Class<T> clazz = getRawClass();
return hibernateTemplate.find("from " + clazz.getCanonicalName());
}

public void save(Object entity) {
hibernateTemplate.save(entity);
}

public void update(Object entity) {
hibernateTemplate.update(entity);
}

public void delete(Object entity) {
hibernateTemplate.delete(entity);
}

public void deleteById(Integer id) {
T entity = findById(id);
if (entity != null) {
delete(entity);
}
}

private int count(final LinkedHashMap<String, Object> parameters) {
return hibernateTemplate.execute(new HibernateCallback<Integer>() {

@Override
public Integer doInHibernate(Session session) throws HibernateException, SQLException {
Class<T> clazz = getRawClass();
StringBuilder hql = new StringBuilder(1024);
hql.append("select count(*) from ").append(clazz.getCanonicalName());
if (parameters != null && !parameters.isEmpty()) {
hql.append(" where 1=1");
Set<Entry<String, Object>> entries = parameters.entrySet();
for (Entry<String, Object> entry : entries) {
hql.append(" ").append(entry.getKey()).append("=:").append(entry.getKey());
}
}
Query query = session.createQuery(hql.toString());
if (parameters != null && !parameters.isEmpty()) {
Set<Entry<String, Object>> entries = parameters.entrySet();
for (Entry<String, Object> entry : entries) {
query.setParameter(entry.getKey(), entry.getValue());
}
}
Long count = (Long) query.uniqueResult();
return count.intValue();
}
});
}

private List<T> findRecords(final int startRecord, final int pageSize, final LinkedHashMap<String, Object> parameters) {
return hibernateTemplate.execute(new HibernateCallback<List<T>>() {

@Override
public List<T> doInHibernate(Session session) throws HibernateException, SQLException {
Class<T> clazz = getRawClass();
StringBuilder hql = new StringBuilder(1024);
hql.append("from ").append(clazz.getCanonicalName());
if (parameters != null && !parameters.isEmpty()) {
hql.append(" where 1=1");
Set<Entry<String, Object>> entries = parameters.entrySet();
for (Entry<String, Object> entry : entries) {
hql.append(" ").append(entry.getKey()).append("=:").append(entry.getKey());
}
}
Query query = session.createQuery(hql.toString());
if (parameters != null && !parameters.isEmpty()) {
Set<Entry<String, Object>> entries = parameters.entrySet();
for (Entry<String, Object> entry : entries) {
query.setParameter(entry.getKey(), entry.getValue());
}
}
query.setFirstResult(startRecord - 1);
query.setMaxResults(pageSize);
return query.list();
}
});
}

private Class<T> getRawClass() {
Class<?> clazz = getClass();
ParameterizedType genericSuperclass = (ParameterizedType) clazz.getGenericSuperclass();
Type actualClassType = genericSuperclass.getActualTypeArguments()[0];
return (Class<T>) actualClassType;
}
}

Page.java

import java.util.List;

public class Page {

private int currentPage;
private int previousPage;
private int nextPage;
private int startRecord;
private int endRecord;
private int count;
private int totalPage;
private int pageSize;

private List<?> records;

public Page() {
pageSize = 20;
currentPage = 1;
}

public void init() {
totalPage = (count % pageSize == 0) ? count / pageSize : count / pageSize + 1;
if (currentPage > totalPage) {
currentPage = totalPage;
}
if (totalPage < 1) {
currentPage = 1;
}
previousPage = currentPage - 1;
if (previousPage < 1) {
previousPage = 1;
}
nextPage = currentPage + 1;
if (nextPage > totalPage) {
nextPage = totalPage;
}

startRecord = (currentPage - 1) * pageSize + 1;
if (startRecord > count) {
startRecord = count;
}
endRecord = currentPage * pageSize;
if (endRecord > count) {
endRecord = count;
}
}

public int getCurrentPage() {
return currentPage;
}

public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}

public int getPreviousPage() {
return previousPage;
}

public void setPreviousPage(int previousPage) {
this.previousPage = previousPage;
}

public int getNextPage() {
return nextPage;
}

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

public int getStartRecord() {
return startRecord;
}

public void setStartRecord(int startRecord) {
this.startRecord = startRecord;
}

public int getEndRecord() {
return endRecord;
}

public void setEndRecord(int endRecord) {
this.endRecord = endRecord;
}

public int getCount() {
return count;
}

public void setCount(int count) {
this.count = count;
}

public int getTotalPage() {
return totalPage;
}

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

public int getPageSize() {
return pageSize;
}

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

public List<?> getRecords() {
return records;
}

public void setRecords(List<?> records) {
this.records = records;
}

}


<?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"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"
default-autowire="autodetect">
<aop:config>
<aop:aspect id="TestAspect" ref="aspectBean">
<!--配置com.spring.service包下所有类或接口的所有方法-->
<aop:pointcut id="businessService" expression="execution(* com.spring.service.*.*(..))" />
<aop:before pointcut-ref="businessService" method="doBefore"/>
<aop:after pointcut-ref="businessService" method="doAfter"/>
<aop:around pointcut-ref="businessService" method="doAround"/>
<aop:after-throwing pointcut-ref="businessService" method="doThrowing" throwing="ex"/>
</aop:aspect>
</aop:config>

<bean id="aspectBean" class="com.spring.aop.TestAspect" />
<bean id="aService" class="com.spring.service.AServiceImpl"></bean>
<bean id="bService" class="com.spring.service.BServiceImpl"></bean>

</beans>

package com.spring.aop;

public class TestAspect {

public void doAfter(JoinPoint jp) {
System.out.println("log Ending method: " + jp.getTarget().getClass().getName() + "." + jp.getSignature().getName());
}

public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
long time = System.currentTimeMillis();
Object retVal = pjp.proceed();
time = System.currentTimeMillis() - time;
System.out.println("process time: " + time + " ms");
return retVal;
}

public void doBefore(JoinPoint jp) {
System.out.println("log Begining method: " + jp.getTarget().getClass().getName() + "." + jp.getSignature().getName());
}

public void doThrowing(JoinPoint jp, Throwable ex) {
System.out.println("method " + jp.getTarget().getClass().getName() + "." + jp.getSignature().getName() + " throw exception");
System.out.println(ex.getMessage());
}

private void sendEx(String ex) {
}
}

<aop:config>
<aop:aspect id="TestAspect" ref="aspectBean">
<aop:pointcut id="businessService"
expression="execution(* com.spring.service.*.*(String,..)) and args(msg,..)" />
<aop:after pointcut-ref="businessService" method="doAfter"/>
</aop:aspect>
</aop:config>

 

package com.bird.service;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;

/**
* 切面
* @author Bird
*/
@Service
@Aspect
public class MyInterceptor {
@Pointcut("execution(* com.bird.service.impl.PersonServiceBean.*(..))")
private void anyMethod(){}//定义一个切入点

@Before("anyMethod() && args(name)")
public void doAccessCheck(String name){
System.out.println(name);
System.out.println("前置通知");
}

@AfterReturning("anyMethod()")
public void doAfter(){
System.out.println("后置通知");
}

@After("anyMethod()")
public void after(){
System.out.println("最终通知");
}

@AfterThrowing("anyMethod()")
public void doAfterThrow(){
System.out.println("例外通知");
}

@Around("anyMethod()")
public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable{
System.out.println("进入环绕通知");
Object object = pjp.proceed();//执行该方法
System.out.println("退出方法");
return object;
}
}

<?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"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">

<aop:aspectj-autoproxy/>
<context:component-scan base-package="com.tianlihu.*.model.*" />
</beans>

Tomcat的HTTPS配置
<Connector protocol="org.apache.coyote.http11.Http11NioProtocol"
port="7443" minSpareThreads="5" maxSpareThreads="75"
enableLookups="true" disableUploadTimeout="true"
acceptCount="100" maxThreads="200"
scheme="https" secure="true" SSLEnabled="true"
clientAuth="false" sslProtocol="TLS"
keystoreFile="E:/server.keystore"
keystorePass="changeit"
truststoreFile="E:/server.keystore"
truststorePass="changeit"/>

JBPM工作流要点总结:
1. 获取流程引擎ProcessEngine processEngine = Configuration.getProcessEngine();
2. 获取流程库Service: RepositoryServicve repositoryService = processEngine.getRepositoryService();
3. 发布流程:repositoryService.createDeployment().addResourceFromClassPath("xxxx").deploy();
4. 查询流程定义:repositoryService.createProcessDefinitionQuery().list();
5. 删除流程定义:repositoryService.deleteDeploymentCascade(deploymentId);
6. 获取执行Service:processEngine.getExecutionService();
7. 启动一个新流程:ProcessInstance processInstance = processEngine.startProcessInstanceByKey("processKey");
8. 执行流程:processInstance = processEngine.signalExecutionById(instanceId);
9. 查询流程是否执行完毕:processInstance.isEnded();
10. 强行终止流程:executionService.endProcessInstance(processInstanceId, cause);
11. 删除流程:executionService.deleteProcessInstance(processInstanceId);
12. 查询流程:executionService.createProcessInstanceQuery().list();


SpringMVC处理日期类型:
@InitBinder
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
binder.registerCustomEditor(Date.class, new DatePropertyEditorSupport());
}

public class DatePropertyEditorSupport extends PropertyEditorSupport {

@Override
public void setAsText(String text) throws IllegalArgumentException {
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
try {
Date value = format.parse(text);
setValue(value);
} catch (ParseException e) {
e.printStackTrace();
}
}
}

struts2标签
<%@ taglib prefix="s" uri="/struts-tags"%>
<s:iterator value="users" var="user">
<tr>
<td><s:property value="userId" /></td>
<td><s:property value="name" /></td>
<td><s:property value="password" /></td>
<td><s:property value="age" /></td>
<td><s:if test="age>21">已退休</s:if><s:elseif test="age>20">在岗</s:elseif><s:else>学生</s:else></td>
</tr>
</s:iterator>


<Connector URIEncoding="UTF-8" connectionTimeout="20000" port="80" protocol="HTTP/1.1" redirectPort="8443"/>

 

转载于:https://www.cnblogs.com/xiuzhaoyang/p/5237309.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值