资料:
一、首先导入依赖:
<spring-version>4.3.13.RELEASE</spring-version>
<mybatis-version>3.4.5</mybatis-version>
<servlet-version>4.0.0</servlet-version>
<mysql-version>5.1.46</mysql-version>
<dbcp-version>1.4</dbcp-version>
<log4j-version>1.2.12</log4j-version>
<slf4j-version>1.5.6</slf4j-version>
<jackson-version>2.9.2</jackson-version>
<jedis-version>2.9.0</jedis-version>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- spring核心包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</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-jdbc</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-aop</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring-version}</version>
</dependency>
<!-- mybatis核心包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis-version}</version>
</dependency>
<!-- mybatis/spring包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<!--加入servlet依赖-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${servlet-version}</version>
</dependency>
<!-- 导入Mysql数据库链接jar包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-version}</version>
</dependency>
<!-- 导入dbcp的jar包,用来在applicationContext.xml中配置数据库 -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>${dbcp-version}</version>
</dependency>
<!-- 日志文件管理包 -->
<!-- log start -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j-version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j-version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j-version}</version>
<scope>test</scope>
</dependency>
<!-- log end -->
<!--加入jackson包-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson-version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson-version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson-version}</version>
</dependency>
<!--导入jedis的依赖-->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>${jedis-version}</version>
</dependency>
在build标签里加上(不加则会造成找不到myBatis的核心文件):
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
二、编写java代码(java文件夹下):
1、pojo包的实体类 User.java:
/**
* 测试类的实体类
*/
public class User implements Serializable {
/**
* 编号
*/
private String user_id;
/**
* 用户名
*/
private String user_name;
/**
* 密码
*/
private String user_pwd;
/**
* 类型
*/
private int user_type;
public User() {
}
public User(String user_id, String user_name, String user_pwd, int user_type) {
this.user_id = user_id;
this.user_name = user_name;
this.user_pwd = user_pwd;
this.user_type = user_type;
}
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getUser_pwd() {
return user_pwd;
}
public void setUser_pwd(String user_pwd) {
this.user_pwd = user_pwd;
}
public int getUser_type() {
return user_type;
}
public void setUser_type(int user_type) {
this.user_type = user_type;
}
@Override
public String toString() {
return "User{" +
"user_id='" + user_id + '\'' +
", user_name='" + user_name + '\'' +
", user_pwd='" + user_pwd + '\'' +
", user_type=" + user_type +
'}';
}
}
2、mapper包的接口 IUsersMapper.java:
/**
* 测试类mapper包的接口
*/
@Repository
public interface IUsersMapper {
/**
* 查询测试类的所有数据的方法
*
* @return
*/
public List<User> findUsersAll();
/**
* 新增数据
*
* @param user
* @return
*/
public int addUsers(User user);
/**
* 编辑数据
*
* @param user
* @return
*/
public int editUsers(User user);
/**
* 删除数据
*
* @param user
* @return
*/
public int removeUser(User user);
}
3、mapper包的MyBatis核心配置文件 IUsersMapper.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zking.mapper.IUsersMapper">
<!--查询测试类的所有数据的sql语句-->
<select id="findUsersAll" resultType="User">
SELECT * FROM USER
</select>
<!--新增数据的sql语句-->
<insert id="addUsers" parameterType="User">
<!-- <selectKey resultType="java.lang.String" keyProperty="user_id" order="BEFORE">
SELECT UUID();
</selectKey>-->
INSERT INTO USER VALUES(UUID(),#{user_name},#{user_pwd},#{user_type})
</insert>
<!--编辑数据的sql语句-->
<update id="editUsers" parameterType="User">
UPDATE USER
<set>
<if test="user_name!=null">
user_name=#{user_name},
</if>
<if test="user_pwd!=null">
user_pwd=#{user_pwd},
</if>
<if test="user_type!=null">
user_type=#{user_type},
</if>
</set>
where user_id=#{user_id}
</update>
<!--删除数据的sql语句-->
<delete id="removeUser" parameterType="User">
delete from User WHERE user_id=#{user_id}
</delete>
</mapper>
4、service包的接口 IUsersService:
/**
* 测试类service包的接口
*/
public interface IUsersService {
/**
* 查询测试类的所有数据的方法
*
* @return
*/
public List<User> findUsersAll();
/**
* 新增数据
*
* @param user
* @return
*/
public int addUsers(User user);
/**
* 编辑数据
*
* @param user
* @return
*/
public int editUsers(User user);
/**
* 删除数据
*
* @param user
* @return
*/
public int removeUser(User user);
}
5、service.impl包的实现类 UsersServiceImpl.java:
/**
* 测试类service包的实现类
*/
@Service("IUsersService")
public class UsersServiceImpl implements IUsersService {
@Resource(name = "IUsersMapper")
private IUsersMapper ium;
@Override
public List<User> findUsersAll() {
return ium.findUsersAll();
}
@Override
public int addUsers(User user) {
return ium.addUsers(user);
}
@Override
public int editUsers(User user) {
return ium.editUsers(user);
}
@Override
public int removeUser(User user) {
return ium.removeUser(user);
}
}
6、redis包的类 RedisCache.java:
public class RedisCache {
//redis的缓冲池
private JedisPool jedisPool;
public JedisPool getJedisPool() {
return jedisPool;
}
public void setJedisPool(JedisPool jedisPool) {
this.jedisPool = jedisPool;
}
/**
* 设置redis缓存信息
*
* @param key
* @param value
*/
public <T> void setRedisDate(String key, T value) throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
if (value != null) {
String outStr = objectMapper.writeValueAsString(value);
jedisPool.getResource().set(key, outStr);
}
}
/**
* 获取redis的String的缓存信息
*
* @param key
* @return
*/
public String getRedisDate(String key) {
return jedisPool.getResource().get(key);
}
/**
* 获取redis的list集合的缓存信息
*
* @param <T>
* @return
* @throws Exception
*/
public <T> List<T> getRedisDateList(String key) throws Exception {
String readStr = jedisPool.getResource().get(key);
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(readStr, new TypeReference<List<T>>() {
});
}
/**
* 获取redis的单个对象的缓存信息
*
* @param key
* @param valueType
* @param <T>
* @return
* @throws Exception
*/
public <T> T getRedisDateObject(String key, Class<T> valueType) throws Exception {
String readStr = jedisPool.getResource().get(key);
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(readStr, valueType);
}
}
7、controller包的数据交互类 UsersController.java:
@Controller//定义为是一个控制器类
@RequestMapping("user")//提供初步的请求映射信息,相对于 WEB 应用的根目录
public class UsersController {
//创建一个公用的key值
private final String key = "com.zking.service.IUsersService";
@Resource(name = "IUsersService")
private IUsersService ius;
@Autowired
private RedisCache redisCache;
@ResponseBody//返回的对象为JSON数据
@RequestMapping(value = "findUserAll")//提供进一步的细分映射信息。相对于类定义处的 URL
public String findUserAll() throws Exception {
//判断是不是要读取缓存信息
//如果没有缓存信息,那么久先加载到缓存中,然后根据当前数据库的返回进行数据的返回
//如果有缓存则直接读取缓存信息里面的数据
String outStr = redisCache.getRedisDate(key);
if (outStr == null) {
redisCache.setRedisDate(key, ius.findUsersAll());
}
System.out.println("缓存值" + redisCache.getRedisDate(key));
return outStr;
}
//更新数据,读取redis的缓存,并将缓存转换为list的集合,然后重新写入到redis中,
//key值不改变的情况下,value会覆盖。
@RequestMapping("addUser")
@ResponseBody
public Map addUser(User user) throws Exception {
Map<String, String> map = new HashMap<>();
System.out.println("新增对象:" + user);
if (ius.addUsers(user) > 0) {
//首先获取缓存中的集合,将当前这个对象加入到缓存集合中,将集合重新写入到缓存中
List<User> userList = redisCache.getRedisDateList(key);
userList.add(user);
redisCache.setRedisDate(key, userList);
map.put("message", "Y");
} else {
map.put("message", "N");
}
return map;
}
/**
* 编辑数据
*
* @param user
* @return
* @throws Exception
*/
@RequestMapping("editUser")
@ResponseBody
public Map editUser(User user) throws Exception {
Map<String, String> map = new HashMap<>();
System.out.println("编辑对象:" + user);
if (ius.editUsers(user) > 0) {
//首先获取缓存中的集合,将当前这个对象加入到缓存集合中,将集合重新写入到缓存中
List<User> userList = redisCache.getRedisDateList(key);
for (User u : userList) {
if (u.getUser_id().equals(user.getUser_id())) {
u.setUser_name(user.getUser_name());
u.setUser_pwd(user.getUser_pwd());
u.setUser_type(user.getUser_type());
}
}
redisCache.setRedisDate(key, userList);
map.put("message", "Y");
} else {
map.put("message", "N");
}
return map;
}
/**
* 删除数据
*
* @param user
* @return
* @throws Exception
*/
@RequestMapping("removeUser")
@ResponseBody
public Map removeUser(User user) throws Exception {
Map<String, String> map = new HashMap<>();
System.out.println("删除对象:" + user);
if (ius.removeUser(user) > 0) {
//首先获取缓存中的集合,将当前这个对象加入到缓存集合中,将集合重新写入到缓存中
List<User> userList = redisCache.getRedisDateList(key);
for (User u : userList) {
if (u.getUser_id().equals(user.getUser_id())) {
userList.remove(user);
map.put("message", "Y");
break;
}
}
redisCache.setRedisDate(key, userList);
} else {
map.put("message", "N");
}
return map;
}
}
三、配置信息(resources文件夹下):
1、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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--1) 排除扫描@Component、@Repository、@Service 注解-->
<context:component-scan base-package="com.zking.controller"></context:component-scan>
<!--2) 此标签默认注册DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter -->
<!--两个bean,这两个bean是spring MVC为@Controllers分发请求所必须的。并提供了数据绑定支持,-->
<!--@NumberFormatannotation支持,@DateTimeFormat支持,@Valid支持,读写XML的支持(JAXB),读写JSON的支持(Jackson)-->
<mvc:annotation-driven></mvc:annotation-driven>
<!--但是,从spring3.1开始DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter的使用已经过时-->
<!--spring3.1开始我们应该用RequestMappingHandlerMapping 来替换DefaultAnnotationHandlerMapping,-->
<!--spring3.1开始我们应该用用RequestMappingHandlerAdapter 来替换AnnotationMethodHandlerAdapter-->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="mappingJackson2HttpMessageConverter"/>
</list>
</property>
</bean>
<bean id="mappingJackson2HttpMessageConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<!--处理中文乱码以及避免IE执行AJAX时,返回JSON出现下载文件-->
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
<value>text/json;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
<!--3) ViewResolver -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!--4) 单独处理图片、样式、js等资源 -->
<!--<mvc:resources location="/css/" mapping="/css/**"/>-->
<!--<mvc:resources location="/images/" mapping="/images/**"/>-->
<!--<mvc:resources location="/js/" mapping="/js/**"/>-->
<!-- <mvc:resources location="/jquery-easyui/" mapping="/jquery-easyui/**"/>-->
<!-- ********************* 国际化配置开始***************** -->
<!--修改springmvc-servlet.xml-->
<!--1) 配置国际化资源文件 -->
<!--<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">-->
<!--<property name="basenames">-->
<!--<list>-->
<!--<value>i18n</value>-->
<!--</list>-->
<!--</property>-->
<!--</bean>-->
<!--<!–2) 指定语言区域解析器,由它来确定使用哪个语言 –>-->
<!--<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver">-->
<!--</bean>-->
<!--<!–3) 配置国际化操作拦截器–>-->
<!--<mvc:interceptors>-->
<!--<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"/>-->
<!--</mvc:interceptors>-->
<!-- ********************* 文件上传配置开始***************** -->
<!--<bean id="multipartResolver"-->
<!--class="org.springframework.web.multipart.commons.CommonsMultipartResolver">-->
<!--<!– 必须和用户JSP 的pageEncoding属性一致,以便正确解析表单的内容 –>-->
<!--<property name="defaultEncoding" value="UTF-8"></property>-->
<!--<!– 文件最大大小(字节) 1024*1024*100=50M–>-->
<!--<property name="maxUploadSize" value="52428800"></property>-->
<!--<!–resolveLazily属性启用是为了推迟文件解析,以便捕获文件大小异常–>-->
<!--<property name="resolveLazily" value="true"/>-->
<!--</bean>-->
</beans>
2、spring-mybatis.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.xsd">
<!--配置注解扫描-->
<context:component-scan base-package="com.zking"/>
<!--配置dbcp的数据库连接池-->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<!--连接对象-->
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<!--连接地址-->
<property name="url" value="jdbc:mysql://localhost:3306/chencao"/>
<!--用户名-->
<property name="username" value="root"/>
<property name="password" value="sasa"/>
<!-- 初始化连接大小 -->
<property name="initialSize" value="20"></property>
<!-- 连接池最大数量 -->
<property name="maxActive" value="100"></property>
<!-- 连接池最大空闲 -->
<property name="maxIdle" value="20"></property>
<!-- 连接池最小空闲 -->
<property name="minIdle" value="1"></property>
<!-- 获取连接最大等待时间 -->
<property name="maxWait" value="6000"></property>
</bean>
<!--创建sessionFactory工厂-->
<bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="typeAliasesPackage" value="com.zking.pojo"></property>
<property name="mapperLocations" value="classpath*:com/zking/mapper/*.xml"></property>
</bean>
<!--自动扫描 将Mapper接口生成代理注入到Spring-->
<bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.zking.mapper"></property>
<property name="sqlSessionFactoryBeanName" value="sessionFactory"></property>
</bean>
<!--创建驱动-->
<bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--驱动管理-->
<tx:annotation-driven transaction-manager="dataSourceTransactionManager"/>
<!--配置redis的缓冲池-->
<bean id="jedisPool" class="redis.clients.jedis.JedisPool">
<!--ip连接地址-->
<constructor-arg name="host" value="192.168.42.150"></constructor-arg>
<!--端口号-->
<constructor-arg name="port" value="6379"></constructor-arg>
</bean>
<!--创建redis缓存类对象-->
<bean id="redisCache" class="com.zking.redis.RedisCache">
<property name="jedisPool" ref="jedisPool"></property>
</bean>
</beans>
3、在web.xml文件里配置:
<!--加载spring配置文件-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mybatis.xml</param-value>
</context-param>
<!-- 在Spring框架中是如何解决从页面传来的字符串的编码问题的呢?
下面我们来看看Spring框架给我们提供过滤器CharacterEncodingFilter
这个过滤器就是针对于每次浏览器请求进行过滤的,然后再其之上添加了父类没有的功能即处理字符编码。
其中encoding用来设置编码格式,forceEncoding用来设置是否理会 request.getCharacterEncoding()方法,设置为true则强制覆盖之前的编码格式。-->
<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>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>springmvc</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>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
四、页面调用(这里只是去测试用,实际页面操作根据情况更改):
<body>
<a href="/user/findUserAll.action">获取Json</a>
<a href="/user/addUser.action?user_name=张三&user_pwd=111&user_type=1">新增数据</a>
<a href="/user/editUser.action?user_id=4c830c1e-ecd4-11e8-9fb6-80fa5b5015f0&user_name=李四&user_pwd=222&user_type=1">编辑数据</a>
<a href="/user/removeUser.action?user_id=4c830c1e-ecd4-11e8-9fb6-80fa5b5015f0">删除数据</a>
</body>