ssm+声明式事务+druid(sql监控)+pagehelper+task(Scheduled)+aop+文件上传

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>demo</name>
    <description>Demo</description>

    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>utf-8</project.build.sourceEncoding>
        <spring.version>5.0.2.RELEASE</spring.version>
        <aspectj.version>1.8.13</aspectj.version>
        <mybatis.version>3.2.8</mybatis.version>
        <mybatis.spring.version>1.2.2</mybatis.spring.version>
        <pagehelper.version>5.0.0</pagehelper.version>
        <mysql.version>5.1.32</mysql.version>
        <mssql.version>8.4.1.jre8</mssql.version>
        <ojdbc6.version>11.2.0.4.0-atlassian-hosted</ojdbc6.version>
        <druid.version>1.0.9</druid.version>
        <jsp-api.version>2.0</jsp-api.version>
        <jstl.version>1.2</jstl.version>
        <fastjson.version>1.2.50</fastjson.version>
        <commoms-lang3.version>3.4</commoms-lang3.version>
        <slf4j-log4j12-version>1.6.6</slf4j-log4j12-version>
        <lombok.version>1.18.12</lombok.version>
        <commons-fileupload.version>1.3.1</commons-fileupload.version>
        <junit.version>4.13.1</junit.version>
    </properties>

    <dependencies>
        <!-- Spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</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-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--aop的aspects工具包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--单元测试spring工具-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
            <scope>test</scope>
        </dependency>
        <!--单元测试工具-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
        <!-- Mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>${mybatis.version}</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>${mybatis.spring.version}</version>
        </dependency>
        <!--pagehelper mybatis分页插件-->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>${pagehelper.version}</version>
        </dependency>
        <!-- alibaba.druid连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>${druid.version}</version>
        </dependency>
        <!--mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </dependency>
        <!--sqlServer驱动-->
        <!--<dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>mssql-jdbc</artifactId>
            <version>${mssql.version}</version>
        </dependency>-->
        <!--oracle驱动-->
        <!--<dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc6</artifactId>
            <version>${ojdbc6.version}</version>
        </dependency>-->

        <!--servlet-api-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jsp-api</artifactId>
            <version>${jsp-api.version}</version>
            <scope>provided</scope>
        </dependency>
        <!--JSP标准标签库-->
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>${jstl.version}</version>
        </dependency>

        <!--日志工具包-->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${slf4j-log4j12-version}</version>
        </dependency>
        <!--json转换工具包-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>${fastjson.version}</version>
        </dependency>
        <!--commons-lang3工具包-->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>${commoms-lang3.version}</version>
        </dependency>
        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>${lombok.version}</version>
        </dependency>
        <!-- 文件上传组件 -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>${commons-fileupload.version}</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

配置文件目录:

ssm+声明式事务+druid(sql监控)+pagehelper+task(Scheduled)+aop+文件上传

spring配置: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:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:task="http://www.springframework.org/schema/task"
       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/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd
       http://www.springframework.org/schema/task
       http://www.springframework.org/schema/task/spring-task.xsd">
    <context:component-scan base-package="com.emr">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    <context:property-placeholder location="classpath:config/*.properties" />
    <!--启动任务定时器-->
    <task:annotation-driven/>
    <!--配置数据源-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driver}"/>  <!--数据库连接驱动-->
        <property name="url" value="${jdbc.url}"/>     <!--数据库地址-->
        <property name="username" value="${jdbc.username}"/>   <!--用户名-->
        <property name="password" value="${jdbc.password}"/>   <!--密码-->
        <property name = "filters" value = "${filters}" />
        <!-- 最大并发连接数 -->
        <property name = "maxActive" value = "${maxActive}" />
        <!-- 初始化连接数量 -->
        <property name = "initialSize" value = "${initialSize}" />
        <!-- 配置获取连接等待超时的时间 -->
        <property name = "maxWait" value = "${maxWait}" />
        <!-- 最小空闲连接数 -->
        <property name = "minIdle" value = "${minIdle}" />
        <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
        <property name = "timeBetweenEvictionRunsMillis" value ="${timeBetweenEvictionRunsMillis}" />
        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
        <property name = "minEvictableIdleTimeMillis" value ="${minEvictableIdleTimeMillis}" />
        <property name = "validationQuery" value = "${validationQuery}" />
        <property name = "testWhileIdle" value = "${testWhileIdle}" />
        <property name = "testOnBorrow" value = "${testOnBorrow}" />
        <property name = "testOnReturn" value = "${testOnReturn}" />
        <property name = "maxOpenPreparedStatements" value ="${maxOpenPreparedStatements}" />
        <!-- 打开 removeAbandoned 功能 -->
        <property name = "removeAbandoned" value = "${removeAbandoned}" />
        <!-- 1800 秒,也就是 30 分钟 -->
        <property name = "removeAbandonedTimeout" value ="${removeAbandonedTimeout}" />
        <!-- 关闭 abanded 连接时输出错误日志 -->
        <property name = "logAbandoned" value = "${logAbandoned}" />
    </bean>
    <!-- ====================== 配置和MyBatis的整合 ======================== -->
    <!--配置session工厂MyBatis的整合-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 指定mybatis全局配置文件的位置 -->
        <property name="configLocation" value="classpath:config/mybatis-config.xml"/>
        <property name="dataSource" ref="dataSource"/>
        <!-- 指定mybatis,mapper文件的位置 -->
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
    </bean>
    <!-- 配置扫描器,将mybatis接口的实现加入到IOC容器中 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!-- 扫描所有的dao接口的实现,加入到ioc容器 -->
        <property name="basePackage" value="com.emr.dao"/>
    </bean>
    <!-- 配置一个可以执行批量的sqlSession -->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/>
        <constructor-arg name="executorType" value="BATCH"/>
    </bean>
    <!-- ====================== 事物管理器配置  ======================== -->
    <!--声明式事务-->
    <!-- 事物管理器配置  -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!-- 开启基于注解的事务,使用xml配置形式的事务(必须主要的都是使用配置式) -->
    <aop:config>
        <!-- 配置事务增强 -->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint"/>
        <aop:aspect ref="transactionManager">
            <!-- 切入表达式 -->
            <!--前面第一个*:所有返回类型;..:所有包、子孙包;后面第一次*:所有类名;第二个*:所有方法名;(..):任意类型参数且参数个数不限-->
            <aop:pointcut expression="execution(* com.emr.service..*.*(..))" id="txPoint"/>
        </aop:aspect>
    </aop:config>
    <!-- 配置事务增强 ,事务如何切入-->
    <tx:advice id="txAdvice">
        <!-- 所有方法都是事务方法 -->
        <tx:attributes>
            <tx:method name="insert*" propagation="REQUIRED"/>
            <tx:method name="add*" propagation="REQUIRED"/>
            <tx:method name="create*" propagation="REQUIRED"/>
            <tx:method name="delete*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
            <tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
            <tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
            <tx:method name="*"/>
        </tx:attributes>
    </tx:advice>
    <!-- 上传文件 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="utf-8"/>
        <!-- 最大内存大小 -->
        <property name="maxInMemorySize" value="10240"/>
        <!-- 最大文件大小,-1为不限制大小 -->
        <property name="maxUploadSize" value="-1"/>
    </bean>
</beans>

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>
    <settings>
        <!-- 列自动映射 -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
    <typeAliases>
        <package name="com.emr.entity"/>
    </typeAliases>
    <plugins>
        <!-- com.github.pagehelper为PageHelper类所在包名 -->
        <plugin interceptor="com.github.pagehelper.PageInterceptor">
            <!--分页参数合理化-->
            <property name="reasonable" value="true"/>
        </plugin>
    </plugins>
</configuration>

dispatcherServlet-servlet.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd">
    <context:component-scan base-package="com.emr.controller"/>
    <!--开启aop-->
    <aop:aspectj-autoproxy/>
    <!--自定义消息转换器-->
    <mvc:annotation-driven>
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <constructor-arg value="utf-8"/>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>
    <!-- 静态资源映射 -->
    <mvc:resources mapping="/static/**" location="/static/" />
    <!--配置视图解析器,方便页面返回  -->
    <bean id="jspViewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

jdbc.properties:

#mysql
#数据库IP
dataBaseIp=localhost
#数据库名称
dataBaseName=gmpower
数据库账号
dataBaseUserName=root
#数据库密码
dataBasePassword=docus702

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc\:mysql\://${dataBaseIp}\:3306/${dataBaseName}?useUnicode\=true&characterEncoding\=utf-8
jdbc.username=${dataBaseUserName}
jdbc.password=${dataBasePassword}

filters: stat
maxActive: 20
initialSize: 1
maxWait: 60000
minIdle: 10
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 'x'
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
maxOpenPreparedStatements: 20
removeAbandoned: true
removeAbandonedTimeout: 1800
logAbandoned: true


#sqlServer
#数据库IP
#dataBaseIp=localhost
##数据库名称
#dataBaseName=emr_record
#数据库账号
#dataBaseUserName=sa
##数据库密码
#dataBasePassword=docus702

#jdbc.driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
#jdbc.url=jdbc\:sqlserver\://${dataBaseIp}:1433;databaseName=${dataBaseName}
#jdbc.username=${dataBaseUserName}
#jdbc.password=${dataBasePassword}

#oracle
#数据库IP
#dataBaseIp=localhost
##数据库名称
#dataBaseName=ORCL
##数据库账号
#dataBaseUserName=docus
##数据库密码
#dataBasePassword=docus702

#jdbc.driver=oracle.jdbc.driver.OracleDriver
#jdbc.url=jdbc:oracle:thin:@${dataBaseIp}:1521/${dataBaseName}
#jdbc.username=${dataBaseUserName}
#jdbc.password=${dataBasePassword}

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"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         id="WebApp_ID" version="3.0">
    <!-- 连接池 启用 Web 监控统计功能    start-->
    <filter>
        <filter-name>DruidWebStatFilter</filter-name>
        <filter-class>com.alibaba.druid.support.http.WebStatFilter</filter-class>
        <init-param>
            <param-name>exclusions</param-name>
            <param-value>*. js ,*. gif ,*. jpg ,*. png ,*. css ,*. ico ,/ druid /*</param-value>
        </init-param>
    </filter>
    <filter-mapping >
        <filter-name>DruidWebStatFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <servlet >
        <servlet-name>DruidStatView</servlet-name>
        <servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>DruidStatView</servlet-name>
        <url-pattern>/druid/*</url-pattern>
    </servlet-mapping >
    <!-- 连接池 启用 Web 监控统计功能    end-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:config/applicationContext.xml</param-value>
    </context-param>
    <!-- 启动listener-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!--加载日志slf4j.proerties-->
    <context-param>
        <param-name>webAppRootKey</param-name>
        <param-value>demo.root</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.util.WebAppRootListener</listener-class>
    </listener>
    <!-- springMVC的前端控制器,拦截所有的请求 -->
    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

log4j.properties:

#log4j.rootLogger=info,myLog,errorMsg
log4j.appender.myLog=org.apache.log4j.DailyRollingFileAppender
log4j.appender.myLog.File=D:\\logs\\demo\\info\\info_log
log4j.appender.myLog.DatePattern=-yyyy-MM-dd'.log'
log4j.appender.myLog.Append = true
log4j.appender.myLog.Threshold = debug
log4j.appender.myLog.layout=org.apache.log4j.PatternLayout
log4j.appender.myLog.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss}:%m%n

log4j.appender.errorMsg=org.apache.log4j.DailyRollingFileAppender
log4j.appender.errorMsg.File=D:\\logs\\demo\\error\\error_log
log4j.appender.errorMsg.DatePattern=-yyyy-MM-dd'.log'
log4j.appender.errorMsg.Append = true
log4j.appender.errorMsg.Threshold = error
log4j.appender.errorMsg.layout=org.apache.log4j.PatternLayout
log4j.appender.errorMsg.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss}:%m%n

#Console sql
log4j.rootLogger=debug,myLog,errorMsg,CONSOLE
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern =%d %-5p [%c{5}] - %m%n

log4j.logger.com.emr=debug
log4j.logger.com.alibaba=error
log4j.logger.org=error

单元测试:

import com.emr.entity.Power_Role;
import com.emr.service.PowerRoleService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:config/applicationContext.xml"})
public class DemoApplicationTests {
    @Autowired
    private PowerRoleService powerRoleService;
    @Test
    public void contextLoads() {
        List<Power_Role> list = powerRoleService.selectAll();
        System.out.println(list.toString());
    }
}

druid(sql监控)访问地址:ip:端口/项目名/druid/index.html或者ip:端口/项目名/druid/sql.html

###########################################附加###########################################

定时任务代码:

依赖:

<dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context-support</artifactId>
      <version>${spring.version}</version>
</dependency>

applicationContext.xml其中的代码:

<beans xmlns:task="http://www.springframework.org/schema/task"
       http://www.springframework.org/schema/task
       http://www.springframework.org/schema/task/spring-task.xsd">
    <context:component-scan base-package="com.emr">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
</beans>
    <!--启动任务定时器-->
    <task:annotation-driven/>
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class task {
    //@Scheduled(fixedDelay = 1000)
    @Scheduled(cron = "0/5 * * * * ?")
    public void task(){
        System.out.println("任务启动成功");
    }
}

aop代码:

依赖:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context-support</artifactId>
    <version>${spring.version}</version>
</dependency>
<!--aop的aspects工具包-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aspects</artifactId>
    <version>${spring.version}</version>
</dependency>

dispatcherServlet-servlet.xml其中的代码:

<beans xmlns:aop="http://www.springframework.org/schema/aop"
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd">
    <!--开启aop-->
    <aop:aspectj-autoproxy/>

ssm+声明式事务+druid(sql监控)+pagehelper+task(Scheduled)+aop+文件上传

代码:

testAnnotation.java:

import java.lang.annotation.*;

@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface testAnnotation {
    String modelName() default "";
}

LogAopService.java:

import com.emr.annotation.testAnnotation;
import com.emr.entity.Power_Role;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Aspect
@Component
public class LogAopService{
    @Resource
    private PowerRoleService roleService;

    // 配置接入点,即为所要记录的action操作目录
    @Pointcut("@annotation(com.emr.annotation.testAnnotation)")
    private void controllerAspect() {
    }

    @Around("controllerAspect()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();
        // 拦截的实体类,就是当前正在执行的controller
        Object target = pjp.getTarget();
        // 拦截的方法名称。当前正在执行的方法
        String methodName = pjp.getSignature().getName();
        // 拦截的放参数类型
        Signature sig = pjp.getSignature();
        MethodSignature msig = null;
        if (!(sig instanceof MethodSignature)) {
            throw new IllegalArgumentException("该注解只能用于方法");
        }
        msig = (MethodSignature) sig;
        Class[] parameterTypes = msig.getMethod().getParameterTypes();
        Object object = null;
        // 获得被拦截的方法
        Method method = null;
        try {
            method = target.getClass().getMethod(methodName, parameterTypes);
        } catch (NoSuchMethodException e1) {
            e1.printStackTrace();
        }
        if (null != method) {
            testAnnotation op = method.getAnnotation(testAnnotation.class);
            String module = op.modelName();
            System.out.println("注解属性值:"+module);
            //插入表操作
            insertLog(method,pjp);
        }
        object = pjp.proceed();
        //接受客户端的数据
        Map<String,String[]> map = request.getParameterMap();
        // 解决获取参数乱码
        Map<String,String[]> newmap = new HashMap<String,String[]>();
        for(Map.Entry<String, String[]> entry : map.entrySet()){
            String name = entry.getKey();
            String[] values = entry.getValue();

            if(values==null){
                newmap.put(name, new String[]{});
                continue;
            }
            String[] newvalues = new String[values.length];
            for(int i=0; i<values.length;i++){
                String value = values[i];
                value = new String(value.getBytes("iso8859-1"),request.getCharacterEncoding());
                newvalues[i] = value; //解决乱码后封装到Map中
            }
            newmap.put(name, newvalues);
        }
        return object;
    }

    private void insertLog(Method method,ProceedingJoinPoint pjp) {
        List<Power_Role> power_roles = roleService.selectAll();
        System.out.println(power_roles.toString());
    }
}

上传文件代码:

其中依赖

 <!-- 文件上传组件 -->
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>${commons-fileupload.version}</version>
</dependency>

配置:applicationContext.xml:

<!-- 上传文件 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="utf-8"/>
        <!-- 最大内存大小 -->
        <property name="maxInMemorySize" value="10240"/>
        <!-- 最大文件大小,-1为不限制大小 -->
        <property name="maxUploadSize" value="-1"/>
    </bean>

jsp:

<form action="/demo/test4" method="post" enctype="multipart/form-data">
    <input type="file" name="file" value="现在">
    <input type="submit" value="提交">
</form>

后台代码:

 @RequestMapping(value="test4",method = RequestMethod.POST)
    public void test2(MultipartFile file) throws Exception{
        String originalFilename = file.getOriginalFilename();
        System.out.println(originalFilename);
        file.transferTo(new File("d:\\1.jpg"));
    }

 

上一篇:Spring Boot使用@Scheduled定时器任务


下一篇:SpringBoot实现定时器