最近项目不是很忙,整理了一个springMVC框架给大家分享下,框架结构:springMVC4+spring4+hibernate4,主要是spring配置、springmvc配置、hibernate配置,数据库连接和redis缓存配置,以及声明式缓存的配置,还有就是HibernateTemplate(hibernate4)的注入.。

项目结构

maven项目的pom文件:pom.xml

<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>maven-springmvc</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>springmvc</name>
<url>http://maven.apache.org</url> <properties>
<springVersion>4.3.1.RELEASE</springVersion>
<hibernateVersion>4.3.5.Final</hibernateVersion>
<jstlVersion>1.2</jstlVersion>
<taglibVersion>1.1.2</taglibVersion>
<servletVersion>3.0-alpha-1</servletVersion>
<jsonVersion>1.9.13</jsonVersion>
<jacksonVersion>2.5.0</jacksonVersion>
<mysqlVersion>5.1.38</mysqlVersion>
<c3p0Version>0.9.1.2</c3p0Version>
<log4jVersion>1.2.17</log4jVersion>
<fileuploadVersion>1.3.1</fileuploadVersion>
<lombokVersion>1.16.10</lombokVersion>
</properties> <!--项目依赖 -->
<dependencies>
<!-- 单元测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency> <!-- spring-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${springVersion}</version>
</dependency> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${springVersion}</version>
</dependency> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${springVersion}</version>
</dependency> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${springVersion}</version>
</dependency> <!-- spring web + spring MVC-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${springVersion}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springVersion}</version>
</dependency> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${springVersion}</version>
</dependency> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${springVersion}</version>
</dependency> <!-- hibernate配置-->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernateVersion}</version>
</dependency> <!-- hibernate 缓存 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
<version>${hibernateVersion}</version>
</dependency> <dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>${hibernateVersion}</version>
</dependency> <!-- jsp页面使用的jstl支持-->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>${jstlVersion}</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>${taglibVersion}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>${servletVersion}</version>
<scope>provided</scope>
</dependency> <!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysqlVersion}</version>
</dependency> <!-- 数据库连接池-->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>${c3p0Version}</version>
</dependency> <!-- redis-->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.0.2.RELEASE</version>
</dependency> <dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.1.0</version>
</dependency> <!-- Java对象转换成json对象-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jacksonVersion}</version>
</dependency> <dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jacksonVersion}</version>
</dependency> <dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jacksonVersion}</version>
</dependency> <!-- log4j配置, 视情况添加-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4jVersion}</version>
</dependency> <!--文件 上传-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>${fileuploadVersion}</version>
</dependency> <!-- lombok插件导包-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombokVersion}</version>
<scope>provided</scope>
</dependency> <dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.0</version>
</dependency> </dependencies> <build>
<finalName>springmvc</finalName>
<resources>
<!--表示把java目录下的有关xml文件,properties文件编译/打包的时候放在resources目录下-->
<resource>
<directory>${basedir}/src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>${basedir}/src/main/resources</directory>
</resource>
</resources>
<plugins>
<!--servlet容器 jetty插件-->
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>9.3.10.v20160621</version>
<configuration>
<scanIntervalSeconds>10</scanIntervalSeconds>
<webApp>
<contextPath>/springmvc</contextPath>
</webApp>
<httpConnector>
<port>8082</port>
</httpConnector>
</configuration>
</plugin>
</plugins>
</build>
</project>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<!--welcome pages-->
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list> <!--加载Spring的配置文件到上下文中去-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:applicationContext.xml
</param-value>
</context-param> <!-- spring MVC config start-->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<!-- 此处指向的的是SpringMVC的配置文件 -->
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<!--配置容器在启动的时候就加载这个servlet并实例化-->
<load-on-startup>1</load-on-startup>
</servlet> <servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- spring MVC config end--> <!-- Spring监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> <!-- 字符集过滤 -->
<filter>
<filter-name>encodingFilter</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>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> </web-app>

spring配置和hibernate配置以及事务管理:applicationContext.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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd"> <!--***************************配置Spring*******************-->
<!-- 自动扫描 -->
<context:component-scan base-package="com.example">
<!-- 扫描时跳过 @Controller 注解的JAVA类(控制器) -->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan> <!--*************************配置hibernate******************--> <!--扫描配置文件(这里指向的是之前配置的那个config.properties)-->
<context:property-placeholder location="classpath:config.properties" /> <!--配置数据源-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="${jdbc.driver}" /> <!--数据库连接驱动-->
<property name="jdbcUrl" value="${jdbc.url}" /> <!--数据库地址-->
<property name="user" value="${jdbc.username}" /> <!--用户名-->
<property name="password" value="${jdbc.password}" /> <!--密码-->
<property name="maxPoolSize" value="40" /> <!--最大连接数-->
<property name="minPoolSize" value="1" /> <!--最小连接数-->
<property name="initialPoolSize" value="10" /> <!--初始化连接池内的数据库连接-->
<property name="maxIdleTime" value="20" /> <!--最大空闲时间-->
</bean> <!--配置session工厂-->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.example.model" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> <!--hibernate根据实体自动生成数据库表-->
<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> <!--在控制台显示执行的数据哭操作语句(格式)-->
</props>
</property>
</bean> <!-- 配置spring的声明性事务 -->
<bean class="org.springframework.orm.hibernate4.HibernateTransactionManager" id="transactionManager"><!-- 要根据hibernate的版本配置 -->
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 配置事务属性 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="get*" propagation="REQUIRED" read-only="true" />
<tx:method name="del*" propagation="REQUIRED" />
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="*" propagation="REQUIRED" />
</tx:attributes>
</tx:advice>
<!-- 配置事务切入点 -->
<aop:config proxy-target-class="true">
<aop:pointcut expression="execution(* com.example.base.*.*(..))" id="pointCut"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="pointCut"/>
</aop:config>
<!-- 配置 HibernateTemplate -->
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean> <!-- 引入同文件夹下的redis属性配置文件 -->
<import resource="redis-context.xml"/>
</beans>

数据库和hibernate配置信息:config.properties

#database connection config
jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/data_springmvc?useSSL=false&characterEncoding=utf-8
jdbc.username = root
jdbc.password = root #hibernate config
hibernate.dialect = org.hibernate.dialect.MySQLDialect
hibernate.show_sql = true
hibernate.format_sql = true
hibernate.hbm2ddl.auto = update

springMVC配置:spring-mvc.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:mvc="http://www.springframework.org/schema/mvc"
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-4.3.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd"> <!--********************************************配置springMVC***************************************-->
<!-- 自动扫描 -->
<mvc:annotation-driven />
<context:component-scan base-package="com.example.controller" />
<aop:aspectj-autoproxy proxy-target-class="true"/>
<mvc:annotation-driven/> <!-- @ResponseBody 数据集合的转换-->
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
</mvc:message-converters>
</mvc:annotation-driven> <!-- 对模型视图名称的解析,即在模型视图名称添加前后缀(如果最后一个还是表示文件夹,则最后的斜杠不要漏了) 使用JSP-->
<bean id="defaultViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean> <!-- springmvc文件上传需要配置的节点-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="20971500"/>
<property name="defaultEncoding" value="UTF-8"/>
<property name="resolveLazily" value="true"/>
</bean>
</beans>

日志配置:log4j.properties

#配置根Logger 后面是若干个Appender
log4j.rootLogger=INFO,A1,R
#log4j.rootLogger=INFO,A1,R # ConsoleAppender 输出
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss,SSS} [%c]-[%p] %m%n # File 输出 一天一个文件,输出路径可以定制,一般在根路径下
log4j.appender.R=org.apache.log4j.DailyRollingFileAppender
log4j.appender.R.File=log.txt
log4j.appender.R.MaxFileSize=500KB
log4j.appender.R.MaxBackupIndex=10
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} [%t] [%c] [%p] - %m%n

redis缓存配置:redis-context.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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd"> <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxIdle" value="300" />
<property name="maxActive" value="600" />
<property name="maxWait" value="1000" />
<property name="testOnBorrow" value="true" />
</bean> <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
p:host-name="127.0.0.1"
p:port="6379"
p:password=""
p:pool-config-ref="poolConfig"/>
<bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">
<property name="connectionFactory" ref="connectionFactory" />
</bean>
</beans>
HibernateTemplate的注入
package com.example.base;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.*;
import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.orm.hibernate4.HibernateTemplate;
import javax.annotation.Resource;
import java.io.Serializable;
import java.util.Iterator;
import java.util.List;
import java.util.Map; /**
* Created by ypf on 2018/12/26.
*/
public class GenericDaoHibenate<T,PK extends Serializable> implements GenericDao<T,PK>{ protected final Log log = LogFactory.getLog(getClass());
protected Class<T> persistentClass; public GenericDaoHibenate(Class<T> persistentClass) {
this.persistentClass = persistentClass;
} @Resource(name = "hibernateTemplate")
private HibernateTemplate hibernateTemplate; public T get(PK id) {
T entity = hibernateTemplate.get(this.persistentClass, id);
Hibernate.initialize(entity);
if (entity == null) {
log.warn("Uh oh, '" + this.persistentClass + "' object with id '" + id + "' not found...");
throw new ObjectRetrievalFailureException(this.persistentClass, id);
}
return entity;
} public T save(T object) {
return hibernateTemplate.merge(object);
} public void saveOrUpdate(T object) {
hibernateTemplate.saveOrUpdate(object);
} public void remove(PK id) {
hibernateTemplate.delete(this.get(id));
hibernateTemplate.flush();
} public void update(T object) {
hibernateTemplate.update(object);
} public boolean exists(PK id) {
T entity = hibernateTemplate.get(this.persistentClass, id);
return entity != null;
} public List<T> findByNamedQuery(String queryName, Map<String, Object> queryParams) {
String[] params = new String[queryParams.size()];
Object[] values = new Object[queryParams.size()];
int index = 0;
Iterator<String> i = queryParams.keySet().iterator();
while (i.hasNext()) {
String key = i.next();
params[index] = key;
values[index++] = queryParams.get(key);
}
return (List<T>)hibernateTemplate.findByNamedQueryAndNamedParam(queryName,params,values);
} public Long countSql(String sql) {
Session session = getSession();
Query query = session.createQuery(sql);
long ret = ((Long) query.uniqueResult()).longValue();
releaseSession(session);
return ret;
} public Long countSql(String sql, Object[] parms) {
return null;
} public List querySql(String sql) {
return null;
} public List querySql(String sql, Object[] parms) {
return null;
} public List querySql(String sql, int start, int limit) {
return null;
} public List querySql(String sql, Object[] parms, int start, int limit) {
return null;
} public List querySql(String sql, Map<String, Object> params) {
return null;
} public List querySql(String sql, Map<String, Object> params, int start, int limit) {
return null;
} public boolean executeSql(String sql) {
return false;
} public boolean executeSql(String sql, Object[] parms) {
return false;
} private Session getSession(){
Session session = hibernateTemplate.getSessionFactory().openSession();
return session;
} private void releaseSession(Session session){
if(session != null){
session.close();
}
} }

redis缓存工具类

package com.example.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component; import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit; @Component
public class RedisManager { private final Logger logger = LoggerFactory.getLogger(RedisManager.class); @SuppressWarnings("rawtypes")
@Autowired
private RedisTemplate redisTemplate; /**
* 批量删除对应的value
*
* @param keys
*/
public void remove(final String... keys) {
for (String key : keys) {
remove(key);
}
} /**
* 批量删除key
*
* @param pattern
*/
@SuppressWarnings("unchecked")
public void removePattern(final String pattern) {
Set<Serializable> keys = redisTemplate.keys(pattern);
if (keys.size() > 0)
redisTemplate.delete(keys);
} /**
* 删除对应的value
*
* @param key
*/
@SuppressWarnings("unchecked")
public void remove(final String key) {
if (exists(key)) {
redisTemplate.delete(key);
}
} /**
* 判断缓存中是否有对应的value
*
* @param key
* @return
*/
@SuppressWarnings("unchecked")
public boolean exists(final String key) {
return redisTemplate.hasKey(key);
} /**
* 读取缓存 (String)
*
* @param key
* @return
*/
@SuppressWarnings("unchecked")
public Object get(final String key) {
Object result = null;
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
result = operations.get(key);
return result;
} /**
* 写入缓存 (String)
*
* @param key
* @param value
* @return
*/
@SuppressWarnings("unchecked")
public boolean set(final String key, Object value) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
} /**
* 写入缓存 (String)
*
* @param key
* @param value
* @param expireTime
* @return
*/
@SuppressWarnings("unchecked")
public boolean set(final String key, Object value, Long expireTime) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
} public boolean set(final String key, Object value, Long expireTime,int type) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
} /**
* 写入缓存 (List)单个值写入可设置缓存时间
*
* @param key
* @param value
* @param expireTime
* @return
*/
@SuppressWarnings("unchecked")
public boolean rightPush(final String key, Object value, Long expireTime) {
boolean result = false;
try {
ListOperations<Serializable, Object> operations = redisTemplate.opsForList();
operations.rightPush(key, value);
//设置缓存时间
if(expireTime > 0){
redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
}
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
} /**
* 写入缓存 (List)批量写入
*
* @param key
* @param values
* @param expireTime
* @return
*/
@SuppressWarnings("unchecked")
public boolean rightPushAll(final String key, Long expireTime, List<Object> values) {
boolean result = false;
try {
ListOperations<Serializable, Object> operations = redisTemplate.opsForList();
for(Object value:values){
operations.rightPush(key, value);
}
if(expireTime > 0){
redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
}
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
} /**
* 读取缓存 (List)(全部)
*
* @param key
* @return
*/
@SuppressWarnings("unchecked")
public List<Object> rangeAll(final String key) {
List<Object> result = new ArrayList<Object>();
try {
ListOperations<Serializable, Object> operations = redisTemplate.opsForList();
result = operations.range(key,0,-1);
} catch (Exception e) {
e.printStackTrace();
}
return result;
} /**
* 读取缓存 (List)
*
* @param key
* @param start
* @param end
* @return
*/
@SuppressWarnings("unchecked")
public List<Object> range(final String key,long start,long end) {
List<Object> result = new ArrayList<Object>();
try {
ListOperations<Serializable, Object> operations = redisTemplate.opsForList();
result = operations.range(key,start,end);
} catch (Exception e) {
e.printStackTrace();
}
return result;
} /**
* 删除list中的value (List)
*
* @param key
* @param count
* count > 0:删除等于从头到尾移动的值的元素。
count < 0:删除等于从尾到头移动的值的元素。
count = 0:删除等于value的所有元素。
* @param value
* @return
*/
@SuppressWarnings("unchecked")
public void removeListValue(final String key,long count,String value) {
try {
if(exists(key)){
ListOperations<Serializable, Object> operations = redisTemplate.opsForList();
operations.remove(key,count,value);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

测试类TestController

package com.example.controller;

import com.example.model.User;
import com.example.service.UserManager;
import com.example.util.RedisManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map; /**
* Created by ypf on 2018/12/24.
*/
@Controller
@RequestMapping("/test")
public class TestController { private static final Logger logger = LoggerFactory.getLogger(TestController.class); @Autowired
private RedisManager redisManager; @Autowired
private UserManager userManager; public static String RESULT_CODE = "resultCode";
public static String RESULT_MSG = "resultMsg"; @RequestMapping("/index")
public String index(){
return "index";
} @RequestMapping("/hello")
@ResponseBody
public String hello(HttpServletRequest request){
logger.info("url:" + request.getPathInfo());
logger.info("url:" + request.getRequestURI());
logger.info("url:" + request.getRequestURL());
return "hello world";
} @RequestMapping("/redis")
@ResponseBody
public String test(String key,String value){
redisManager.set(key,value);
String result = redisManager.get(key).toString();
return result;
} @RequestMapping("/getUserInfo")
@ResponseBody
public User getUserInfo(Long id){
User user = userManager.get(id);
return user;
} @RequestMapping("/saveUserInfo")
@ResponseBody
public Map<String,Object> saveUserInfo(String name){
Map<String,Object> map = new HashMap<String, Object>();
User user = new User();
user.setUsername(name);
user.setPassword("123456");
user.setLoginTime(new Date());
userManager.save(user);
map.put(RESULT_CODE,"200");
map.put(RESULT_MSG,"success");
map.put("userInfo",user);
return map;
} }

由于文件比较多,这里就不一一列举了,下面为测试结果:

springMVC4+spring4+hibernate4框架搭建的更多相关文章

  1. J2EE开发框架搭建(2) - springmvc4 + spring4 + hibernate4 整合

    1. 打开hqhop-framework-parent项目下的pom.xml文件.加入springmvc4 , spring4 , hibernate4 ,以及数据源druid的依赖包,插件,依赖包版 ...

  2. 《转》Spring4 Freemarker框架搭建学习

    这里原帖地址:http://www.cnblogs.com/porcoGT/p/4537064.html 完整配置springmvc4,最终视图选择的是html,非静态文件. 最近自己配置spring ...

  3. 基于全注解的SpringMVC+Spring4.2+hibernate4.3框架搭建

    概述 从0到1教你搭建spring+springMVC+hibernate整合框架,基于注解. 本教程框架为基于全注解的SpringMVC+Spring4.2+hibernate4.3,开发工具为my ...

  4. 基于Spring4+SpringMVC4+Mybatis3+Hibernate4+Junit4框架构建高性能企业级的部标GPS监控平台

    开发企业级的部标GPS监控平台,投入的开发力量很大,开发周期也很长,选择主流的开发语言以及成熟的开源技术框架来构建基础平台,是最恰当不过的事情,在设计之初就避免掉了技术选型的风险,避免以后在开发过程中 ...

  5. 基于Spring4+SpringMVC4+Mybatis3+Hibernate4+Junit4框架构建高性能企业级的部标1077视频监控平台

    开发企业级的部标GPS监控平台,投入的开发力量很大,开发周期也很长,选择主流的开发语言以及成熟的开源技术框架来构建基础平台,是最恰当不过的事情,在设计之初就避免掉了技术选型的风险,避免以后在开发过程中 ...

  6. spring4+hibernate4+maven环境搭建

    本文主要介绍利用maven搭建spring4+hibernate4开发环境. 首先我们创建一个maven项目,具体步骤就不详细介绍了,看看我们pom.xml文件 <project xmlns=& ...

  7. Maven+struts2+spring4+hibernate4的环境搭建

    搭建Maven+struts2+spring4+hibernate4其实并不难!但开始弄的时候还是费了我好大的力气,老是出现这样那样的错误!好了,废话不多说,开始搭建开发环境. 一.Myeclipse ...

  8. SSH(Struts2+Spring4+Hibernate4)框架教程之配置篇

    SSH(Struts2+Spring4+Hibernate4)框架教程之配置篇 - 若明天不见 - 博客频道 - CSDN.NEThttp://blog.csdn.net/why_still_conf ...

  9. Spring4 mvc+maven 框架搭建(1)

    这篇博客其实很早就应该写,早在半年前,因为对SpringMVC感兴趣,便自学了一下Spring.一段时间的学习后,对Spring有了一个基本的了解,于是想着自己动手搭建一个SpringMvc的框架出来 ...

随机推荐

  1. N4复习考试总结

    一つ(ひとつ) 半分(はんぶん) 煙草(たばこ)を吸う(すう) 玄関(げんかん) ナイフ(刀)     財布(さいふ) 浅い(あさい) 薄い(うすい) 牛乳(ぎゅうにゅう) 皿(さら) 七日(なのか) ...

  2. 解析html,提取元素参数

    r = s.get(loginurl, verify=False) dom = etree.HTML(r.content.decode("utf-8")) try: result[ ...

  3. python 服务器 cpu 监控程序--转

    后台 py 代码 app.py ''' 服务器cpu监控程序 思路:后端后台线程一旦产生数据,即刻推送至前端. 好处:不需要前端ajax定时查询,节省服务器资源. 作者:hhh5460 时间:2017 ...

  4. java课堂动手测试

    课堂实验3 一个Java类文件中真的只能有一个公有类吗? 经过测试,当含有两个public  类时会报错,不能执行,假如删除第二个public则可以正常生成,说明一个java文件只能有一个公有类. 课 ...

  5. Python分布式+云计算

    参考: http://wiki.python.org/moin/ParallelProcessing http://wiki.python.org/moin/DistributedProgrammin ...

  6. 2019春Python程序设计作业2(0326--0401)

    1-1 已知st="Hello World!",使用print(st[0:-1])语句可以输出字符串变量st中的所有内容. (2分) T         F 1-2 Python程 ...

  7. python 使用嵌套函数报local variable xxx referenced before assignment或者 local variable XXX defined in enclosing scope

    情况一: a 直接引用外部的,正常运行 def toplevel(): a = 5 def nested(): print(a + 2) # theres no local variable a so ...

  8. Python连接MySQL之Python库pymysql

    连接数据库 pymysql连接数据库的方式和使用sqlite的方式基本相同: 使用connect创建连接对象 connect.cursor创建游标对象,SQL语句的执行基本都在游标上进行 cursor ...

  9. TTTTTTTTTTTTT LA 2191 树状数组 稍修改

    题意:给出n个数字,操作有修改(S)和输出区间和(M). #include <iostream> #include <cstdio> #include <cstring& ...

  10. linux下简易端口扫描器

    #include<iostream> #include<string.h> #include<sys/types.h> #include<sys/socket ...