spring+springmvc+mybatis+Redis的配置文件

web.xml文件

<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<display-name>finishFight</display-name>
<welcome-file-list>
<welcome-file>/WEB-INF/login.html</welcome-file>
</welcome-file-list>
<!--用来处理Session-->
<listener>
<!-- 处理session的类的位置 -->
<listener-class>com.hp.listener.LoginSessionListner</listener-class>
</listener>
<!--设置session有效时间15分钟-->
<session-config>
<session-timeout>15</session-timeout>
</session-config>
<!-- 配置filter拦截器 更改字符编码 -->
<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>

<!-- 配置servlet的核心DispatcherServlet控制器 -->
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 配置 SpringMVC的配置文件地址 <param-name> 的名字是规定死的-->
<init-param>
<param-name>contextConfigLocation</param-name>
<!-- 配置springMVC的地址 -->
<param-value>classpath:config/spring-mvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

<!--对静态资源文件的访问-->
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.js</url-pattern>
<url-pattern>*.css</url-pattern>
<url-pattern>*.png</url-pattern>
<url-pattern>*.jpg</url-pattern>
<url-pattern>*.svg</url-pattern>
<url-pattern>*.ttf</url-pattern>
<url-pattern>*.woff</url-pattern>
<url-pattern>*.woff2</url-pattern>
<url-pattern>*.eot</url-pattern>
<url-pattern>*.gif</url-pattern>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
</web-app>

用来处理Session的.Java文件
package com.hp.listener;

import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.HashMap;
import java.util.Map;
/**
* @program: finishFight
* @description: 里面的两个map实现了单点登录
* @author: li hui
* @create: 2020-11-23 16:23
*/
public class LoginSessionListner implements HttpSessionListener {

public static Map sessionMap = new HashMap();
    public static Map map = new HashMap();

/**
* @Author: li hui
* @Param: [httpSessionEvent]
* @return: void
* @date: 2020/11/23
* @Description: 本项目中,每次创建session都会执行一次sessionCreated
*/
@Override
public void sessionCreated(HttpSessionEvent httpSessionEvent) {
System.out.println("创建一个session,这个sessionID为:"+httpSessionEvent.getSession().getId());
sessionMap.put(httpSessionEvent.getSession().getId(),httpSessionEvent.getSession());
}

/**
* @Author: li hui
* @Param: [httpSessionEvent]
* @return: void
* @date: 2020/11/23
* @Description: 本项目中,每次销毁session都会执行一次sessionDestroyed
*/
@Override
public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
System.out.println("销毁一个session,这个sessionID为:"+httpSessionEvent.getSession().getId());
sessionMap.remove(httpSessionEvent.getSession().getId());
//lambda 表达式
     
/*map.forEach((key, value) -> {
System.out.println("key:"+key+" "+"value:"+value);
if(value.equals(httpSessionEvent.getSession().getId())) {
System.out.println("key:"+key+"---------"+"value:"+value);
map.remove(key);
}
});*/
}
}
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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">

<!--扫描注解-->
<context:component-scan base-package="com.hp"/>
<!--启动注解-->
<mvc:annotation-driven/>
<!-- 引入配置文件 -->
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:config/redis.properties" />
</bean>
<!--配置视图解析器-->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--前缀
<property name="prefix" value=""/>-->
<!--后缀
<property name="suffix" value=""/>-->
</bean>

<!--数据库连接 (数据源)-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<!-- mysql的驱动 -->
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<!-- mysql的连接 -->
<property name="url" value="jdbc:mysql://localhost:3306/finishfight?useUnicode=true&amp;characterEncoding=UTF-8"/>
<!-- mysql的账号 -->
<property name="username" value="root"/>
<!-- mysql的密码 -->
<property name="password" value="root"/>
</bean>
<!--配置jdbcTemplate的bean -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<!-- 注入数据源 -->
<property name="dataSource" ref="dataSource"/>
</bean>


<!--SpringMVC 拦截器-->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<!-- <mvc:exclude-mapping> 意思是不拦截那个地址 -->
<!--pc端的登录-->
<mvc:exclude-mapping path="/login"/>
<!-- 图片的验证 -->
<mvc:exclude-mapping path="/verifyCode"/>
<!-- mobile的短信验证 -->
<mvc:exclude-mapping path="/mobile/info"/>
<!-- mobile的登录 -->
<mvc:exclude-mapping path="/mobile/login"/>
<!-- 拦截之后需要处理,在那个类的处理的位置 -->
<bean class="com.hp.interceptor.LoginInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>


<!--Mybatis 的连接注入-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入数据源 -->
<property name="dataSource" ref="dataSource"/>
<!-- 配置 mybatis的配置文件位置 -->
<property name="configLocation" value="classpath:config/mybatis-config.xml"/>
</bean>
<!--Mapper代理开发,使用Spring自动扫描MyBatis的接口并装配
(Spring将指定包中所有被@Mapper注解标注的接口自动装配为MyBatis的映射接口) -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- mybatis-spring组件的扫描器 -->
<property name="basePackage" value="com.hp.dao"/>
<!--注入 mybatis -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>


<!--对静态资源处理 方案一
<mvc:resources mapping="/static/**" location="/static/" />
-->
<!-- 静态资源处理 方案二 方案三在web.xml文件中-->
<!-- <mvc:default-servlet-handler/> -->


<!-- Nosql 数据库 Redis的配置 -->
<!-- spring data redis -->
<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="usePool" value="true"/>
<property name="hostName" value="${redis.host}" />
<property name="port" value="${redis.port}" />
<!-- <property name="password" value=""/> -->
<property name="timeout" value="${redis.timeout}" />
<property name="database" value="${redis.default.db}"/>
<constructor-arg ref="jedisPoolConfig" />
</bean>
<!-- jedis pool配置 -->
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxTotal" value="${redis.maxActive}" />
<property name="maxIdle" value="${redis.maxIdle}" />
<property name="maxWaitMillis" value="${redis.maxWait}" />
</bean>
<!-- Redis Template StringRedisTemplate只能存String类型,RedisTemplate可以存的多一些 -->
<!-- <bean id="redisTemplate" class="org.springframework.data.redis.core. ">-->
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="jedisConnectionFactory" />
</bean>
</beans>
spring-mvc.xml引入的Redis的配置文件(redis.properties)
#redis的服务器地址
redis.host=127.0.0.1
#redis的服务端口
redis.port=6379
#密码
redis.pass=root
#链接数据库
redis.default.db=0
#客户端超时时间单位是毫秒
redis.timeout=100000
#最大连接数
redis.maxActive=300
#最大空闲数
redis.maxIdle=100
#最大建立连接等待时间
redis.maxWait=1000
#指明是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个
#DBSync.testOnBorrow=true
redis.clientName=local

springMVC的拦截的.Java文件
package com.hp.interceptor;
import com.hp.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
* @program: finishFight
* @description:
* @author: li hui
* @create: 2020-11-17 18:12
*/
public class LoginInterceptor implements HandlerInterceptor{

@Autowired
private RedisUtil redisUtil;

@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
String username = (String) httpServletRequest.getSession().getAttribute("username");
String session = httpServletRequest.getSession().getId();
if(username!=null){
redisUtil.set(username,session,60*15);
return true;
}else{
httpServletResponse.sendRedirect("/login");
return false;
}
}

@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

}

@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

}
}


mybatis-config.xml文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--mybatis的插件配置-->
<plugins>
<!-- mybatis的插件类的位置 -->
<plugin interceptor="com.hp.interceptor.MybatisInterceptor">
<property name="dbName" value="mysql"/>
<property name="version" value="5.7"/>
</plugin>
</plugins>
<mappers>
<!-- 用户功能 的mapper文件-->
<mapper resource="com/hp/dao/mapper/UserMapper.xml"/>
<!--客户功能 的mapper文件-->
<mapper resource="com/hp/dao/mapper/CustomerMapper.xml"/>
<!--订单功能 的mapper文件-->
<mapper resource="com/hp/dao/mapper/OrdersMapper.xml"/>
</mappers>
</configuration>

mybatis的插件的.Java文件
package com.hp.interceptor;
import com.hp.util.ReflectHelper;
import org.apache.ibatis.executor.statement.BaseStatementHandler;
import org.apache.ibatis.executor.statement.RoutingStatementHandler;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import java.sql.Connection;
import java.util.Map;
import java.util.Properties;

/**
* @program: finishFight
* @description: 用到了一个类 (ReflectHelper类)
* @author: li hui
* @create: 2020-11-17 16:39
*/
@Intercepts({
@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})
})
public class MybatisInterceptor implements Interceptor {

@Override
public Object intercept(Invocation invocation) throws Throwable {
RoutingStatementHandler rsh=(RoutingStatementHandler)invocation.getTarget();
BaseStatementHandler delegate = (BaseStatementHandler) ReflectHelper.getValueByFieldName(rsh, "delegate");
MappedStatement mappedStatement = (MappedStatement) ReflectHelper.getValueByFieldName(delegate, "mappedStatement");
String id=mappedStatement.getId().toString();
BoundSql boundSql = delegate.getBoundSql();
Map map = (Map) rsh.getParameterHandler().getParameterObject();
if(id.substring(id.lastIndexOf(".")+1, id.length()).equals("query")) {
Integer limit = (Integer.valueOf(map.get("limit")==null ? "10" : map.get("limit").toString()));
Integer page = (Integer.valueOf(map.get("page")==null ? "1" : map.get("page").toString())-1)*limit;
ReflectHelper.setValueByFieldName(boundSql, "sql", rsh.getBoundSql().getSql()+ " limit "+page+","+limit);
}
//System.out.println("这是我获取的xml执行的id:"+id);
//System.out.println("这是传过来的参数:"+boundSql.getParameterObject());
//System.out.println("执行的sql:"+rsh.getBoundSql().getSql().replace("\n"," ").replace("\t"," ").replaceAll("\\s{1,}", " "));
return invocation.proceed();
}

@Override
public Object plugin(Object o) {
return Plugin.wrap(o,this);
}

@Override
public void setProperties(Properties properties) {
}
}

ReflectHelper类的.java文件
package com.hp.util;
import java.lang.reflect.Field;

/**
* 反射工具
* @version
*/
public class ReflectHelper {
/**
* @param obj
* @param fieldName
* @return
*获取需要反射的类
*/
public static Field getFieldByFieldName(Object obj, String fieldName) {
for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()) {
try {
return superClass.getDeclaredField(fieldName);
} catch (NoSuchFieldException e) {
}
}
return null;
}

/**
* @param obj
* @param fieldName
* @return
* @throws SecurityException
* @throws NoSuchFieldException
* @throws IllegalArgumentException
* @throws IllegalAccessException
* 获取某个参数的内容
*/
public static Object getValueByFieldName(Object obj, String fieldName)
throws SecurityException, NoSuchFieldException,
IllegalArgumentException, IllegalAccessException {
Field field = getFieldByFieldName(obj, fieldName);
Object value = null;
if(field!=null){
if (field.isAccessible()) {
value = field.get(obj);
} else {
field.setAccessible(true);
value = field.get(obj);
field.setAccessible(false);
}
}
return value;
}

/**
* @param obj
* @param fieldName
* @param value
* @throws SecurityException
* @throws NoSuchFieldException
* @throws IllegalArgumentException
* @throws IllegalAccessException
* 改变需要改变的内容
*/
public static void setValueByFieldName(Object obj, String fieldName,
Object value) throws SecurityException, NoSuchFieldException,
IllegalArgumentException, IllegalAccessException {
Field field = obj.getClass().getDeclaredField(fieldName);
if (field.isAccessible()) {
field.set(obj, value);
} else {
field.setAccessible(true);
field.set(obj, value);
field.setAccessible(false);
}
}
}

mybatis的mapper文件的配置
<?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.hp.dao.UserDao">

<!-- 使用时只需修改sql标签的内容 和 下方query,row 字段改了即可 -->
<!-- 数据库的表名 -->
<sql id="tableName">
user
</sql>
<!-- 字段名 -->
<sql id="column">
id,
username,
password,
phone,
sex
</sql>
<!-- 主要用于批量添加 -->
<sql id="batch">
#{item.id},
#{item.username},
#{item.password},
#{item.phone},
#{item.sex},
</sql>


<!-- 用于单查 -->
<select id="find" resultType="map" parameterType="map">
select
<include refid="column"/>
from
<include refid="tableName"/>
<where>
<foreach collection="map" item="val" index="key" separator="and">
${key} = #{val}
</foreach>
</where>
</select>


<!-- 用于多差 -->
<select id="query" resultType="map" parameterType="map">
select
<include refid="column"/>
from
<include refid="tableName"/>
<where>
<if test="like!=null and like!=''">
<!-- 这里的username 字段名 -->
username like '%${like}%'
</if>
</where>
</select>


<!-- 用于新增 注意内外的参数 传值时需注意 -->
<insert id="save" parameterType="map" keyProperty="sid" useGeneratedKeys="true">
insert into
<include refid="tableName"/>
<foreach collection="map" item="val" index="key" open="(" separator="," close=")">
${key}
</foreach>
values
<foreach collection="map" item="val" index="key" open="(" separator="," close=")">
#{val}
</foreach>
</insert>

<!-- 用于批量添加 注意内外的参数 传值时需注意 -->
<insert id="batchSave" parameterType="list" keyProperty="sid" useGeneratedKeys="true">
insert into
<include refid="tableName"/>
(<include refid="column"/>)
values
<foreach collection="list" item="item" separator=",">
(<include refid="batch"/>)
</foreach>
</insert>

<!-- 用于修改 注意内外的参数 传值时需注意 -->
<update id="upd" parameterType="map">
update
<include refid="tableName"/>
<set>
<foreach collection="map" item="val" index="key" separator=",">
${key} = #{val}
</foreach>
</set>
where id = #{map.id}
</update>

<!-- 用于删除单条 -->
<delete id="del" parameterType="map">
delete
from
<include refid="tableName"/>
where id=#{id}
</delete>

<!--用于批量删除 注意传的参数-->
<delete id="batchDel" parameterType="list">
delete
from
<include refid="tableName"/>
<where>
id in
<foreach collection="list" item="item" open="(" separator=", " close=")">
#{item}
</foreach>
</where>
</delete>


<!-- 用于返回数据的条目数 并且加上了条件 -->
<select id="row" parameterType="map" resultType="map">
select
count(*) count
from
<include refid="tableName"/>
<where>
<if test="like!=null and like!=''">
<!-- 这里的username 字段名 -->
username like '%${like}%'
</if>
</where>
</select>
</mapper>
 
posted @ 2020-11-25 14:41  小韩呐~  阅读(141)  评论(0编辑  收藏  举报