前言 前段时间,需要验证一个东西,需要用到SSM框架,手头上没有现成的整合好的,就自己整合了一个。
在写代码之前我们先了解一下这三个框架分别是干什么的? 相信大以前也看过不少这些概念,我这就用大白话来讲,如果之前有了解过可以跳过这一大段,直接看代码!
SpringMVC:它用于web层,相当于controller(等价于传统的servlet和struts的action),用来处理用户请求。举个例子,用户在地址栏输入http://网站域名/login,那么springmvc就会拦截到这个请求,并且调用controller层中相应的方法,(中间可能包含验证用户名和密码的业务逻辑,以及查询数据库操作,但这些都不是springmvc的职责),最终把结果返回给用户,并且返回相应的页面(当然也可以只返回json/xml等格式数据)。springmvc就是做前面和后面过程的活,与用户打交道!!
Spring:太强大了,以至于我无法用一个词或一句话来概括它。但与我们平时开发接触最多的估计就是IOC容器,它可以装载bean(也就是我们java中的类,当然也包括service dao里面的),有了这个机制,我们就不用在每次使用这个类的时候为它初始化,很少看到关键字new。另外spring的aop,事务管理等等都是我们经常用到的。
MyBatis:如果你问我它跟鼎鼎大名的Hibernate有什么区别?我只想说,他更符合我的需求。第一,它能自由控制sql,这会让有数据库经验的人(当然不是说我啦捂脸)编写的代码能搞提升数据库访问的效率。第二,它可以使用xml的方式来组织管理我们的sql,因为一般程序出错很多情况下是sql出错,别人接手代码后能快速找到出错地方,甚至可以优化原来写的sql。
开发环境搭建:
IDEA 2019.3
MAVEN 3.6.0
Jdk 1.8.0_181
Tomcat 8.0.39
MySQL 5.7.20
创建项目 【File】->【New】->【Project】->【Maven】->【Create from archetype】->【maven-archetype-webapp】
项目结构 创建好的项目后添加必要的目录,结构如下
添加依赖 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 <dependencies > <dependency > <groupId > org.springframework</groupId > <artifactId > spring-core</artifactId > <version > ${org.springframework.version}</version > </dependency > <dependency > <groupId > org.springframework</groupId > <artifactId > spring-beans</artifactId > <version > ${org.springframework.version}</version > </dependency > <dependency > <groupId > org.springframework</groupId > <artifactId > spring-context</artifactId > <version > ${org.springframework.version}</version > </dependency > <dependency > <groupId > org.springframework</groupId > <artifactId > spring-jdbc</artifactId > <version > ${org.springframework.version}</version > </dependency > <dependency > <groupId > org.springframework</groupId > <artifactId > spring-tx</artifactId > <version > ${org.springframework.version}</version > </dependency > <dependency > <groupId > org.springframework</groupId > <artifactId > spring-web</artifactId > <version > ${org.springframework.version}</version > </dependency > <dependency > <groupId > org.springframework</groupId > <artifactId > spring-webmvc</artifactId > <version > ${org.springframework.version}</version > </dependency > <dependency > <groupId > org.springframework</groupId > <artifactId > spring-aop</artifactId > <version > ${org.springframework.version}</version > </dependency > <dependency > <groupId > org.springframework</groupId > <artifactId > spring-aspects</artifactId > <version > ${org.springframework.version}</version > </dependency > <dependency > <groupId > org.postgresql</groupId > <artifactId > postgresql</artifactId > <version > 9.4.1212</version > </dependency > <dependency > <groupId > mysql</groupId > <artifactId > mysql-connector-java</artifactId > <version > 5.1.47</version > <scope > runtime</scope > </dependency > <dependency > <groupId > com.alibaba</groupId > <artifactId > druid</artifactId > <version > 1.0.11</version > </dependency > <dependency > <groupId > org.mybatis</groupId > <artifactId > mybatis</artifactId > <version > 3.3.0</version > </dependency > <dependency > <groupId > org.mybatis</groupId > <artifactId > mybatis-spring</artifactId > <version > 1.2.3</version > </dependency > <dependency > <groupId > com.fasterxml.jackson.core</groupId > <artifactId > jackson-databind</artifactId > <version > 2.5.4</version > </dependency > <dependency > <groupId > com.alibaba</groupId > <artifactId > fastjson</artifactId > <version > 1.1.39</version > </dependency > <dependency > <groupId > ch.qos.logback</groupId > <artifactId > logback-classic</artifactId > <version > 1.1.1</version > </dependency > </dependencies >
配置文件 jdbc.properties 在resources
文件夹里新建一个jdbc.properties
文件。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 jdbc.driver =com.mysql.jdbc.Driver jdbc.url =jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8 jdbc.username =root jdbc.password =123456 jdbc.driver.pg =org.postgresql.Driver jdbc.url.pg =jdbc:postgresql://127.0.0.1:5432/test jdbc.username.pg =root jdbc.password.pg =123456 dataSource : postgresql jdbc.initialSize =3 jdbc.maxActive =1000 jdbc.minIdle =0 jdbc.maxWait =6000 jdbc.removeAbandoned =true jdbc.removeAbandonedTimeout =1800 jdbc.timeBetweenEvictionRunsMillis =60000 jdbc.minEvictableIdleTimeMillis =25200000 jdbc.validationQuery =select 1 jdbc.testWhileIdle =false jdbc.testOnBorrow =false jdbc.testOnReturn =false
mybatis-config,xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD SQL Map Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd" > <configuration > <settings > <setting name ="useGeneratedKeys" value ="true" /> <setting name ="useColumnLabel" value ="true" /> <setting name ="mapUnderscoreToCamelCase" value ="true" /> <setting name ="cacheEnabled" value ="true" /> <setting name ="lazyLoadingEnabled" value ="true" /> <setting name ="multipleResultSetsEnabled" value ="true" /> <setting name ="defaultExecutorType" value ="REUSE" /> <setting name ="defaultStatementTimeout" value ="25000" /> <setting name ="logImpl" value ="STDOUT_LOGGING" /> <setting name ="callSettersOnNulls" value ="true" /> </settings > </configuration >
spring-context.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 <?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" xsi:schemaLocation ="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd" > <context:annotation-config /> <context:component-scan base-package ="com.valten" > <context:exclude-filter type ="annotation" expression ="org.springframework.stereotype.Controller" /> </context:component-scan > <context:property-placeholder location ="classpath:jdbc.properties" /> <import resource ="classpath*:spring/spring-mybatis.xml" /> </beans >
spring-servlet.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 <?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" 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/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 http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd" > <mvc:annotation-driven /> <aop:aspectj-autoproxy proxy-target-class ="true" /> <context:component-scan base-package ="com.valten" > <context:include-filter type ="annotation" expression ="org.springframework.stereotype.Controller" /> </context:component-scan > <bean id ="mappingJacksonHttpMessageConverter" class ="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" > <property name ="supportedMediaTypes" > <list > <value > text/html;charset=UTF-8</value > </list > </property > </bean > <bean class ="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" > <property name ="messageConverters" > <list > <bean class ="org.springframework.http.converter.ByteArrayHttpMessageConverter" /> <ref bean ="mappingJacksonHttpMessageConverter" /> </list > </property > </bean > <bean id ="viewResolver" class ="org.springframework.web.servlet.view.InternalResourceViewResolver" > <property name ="prefix" value ="/" /> <property name ="suffix" value =".html" /> </bean > <bean id ="exceptionResolver" class ="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver" > <property name ="defaultStatusCode" value ="500" /> <property name ="warnLogCategory" value ="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver" /> </bean > <mvc:default-servlet-handler /> <task:executor id ="executor" pool-size ="5" /> <task:scheduler id ="scheduler" pool-size ="10" /> <task:annotation-driven executor ="executor" scheduler ="scheduler" /> </beans >
spring-mybatis.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 <?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:tx ="http://www.springframework.org/schema/tx" xsi:schemaLocation =" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd" > <bean name ="mysql" class ="com.alibaba.druid.pool.DruidDataSource" init-method ="init" 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 ="initialSize" value ="${jdbc.initialSize}" /> <property name ="maxActive" value ="${jdbc.maxActive}" /> <property name ="minIdle" value ="${jdbc.minIdle}" /> <property name ="maxWait" value ="${jdbc.maxWait}" /> <property name ="removeAbandoned" value ="${jdbc.removeAbandoned}" /> <property name ="removeAbandonedTimeout" value ="${jdbc.removeAbandonedTimeout}" /> <property name ="timeBetweenEvictionRunsMillis" value ="${jdbc.timeBetweenEvictionRunsMillis}" /> <property name ="minEvictableIdleTimeMillis" value ="${jdbc.minEvictableIdleTimeMillis}" /> <property name ="validationQuery" value ="${jdbc.validationQuery}" /> <property name ="testWhileIdle" value ="${jdbc.testWhileIdle}" /> <property name ="testOnBorrow" value ="${jdbc.testOnBorrow}" /> <property name ="testOnReturn" value ="${jdbc.testOnReturn}" /> <property name ="logAbandoned" value ="true" /> <property name ="filters" value ="stat" /> </bean > <bean name ="postgresql" class ="com.alibaba.druid.pool.DruidDataSource" init-method ="init" destroy-method ="close" > <property name ="driverClassName" value ="${jdbc.driver.pg}" /> <property name ="url" value ="${jdbc.url.pg}" /> <property name ="username" value ="${jdbc.username.pg}" /> <property name ="password" value ="${jdbc.password.pg}" /> <property name ="initialSize" value ="${jdbc.initialSize}" /> <property name ="maxActive" value ="${jdbc.maxActive}" /> <property name ="minIdle" value ="${jdbc.minIdle}" /> <property name ="maxWait" value ="${jdbc.maxWait}" /> <property name ="removeAbandoned" value ="${jdbc.removeAbandoned}" /> <property name ="removeAbandonedTimeout" value ="${jdbc.removeAbandonedTimeout}" /> <property name ="timeBetweenEvictionRunsMillis" value ="${jdbc.timeBetweenEvictionRunsMillis}" /> <property name ="minEvictableIdleTimeMillis" value ="${jdbc.minEvictableIdleTimeMillis}" /> <property name ="validationQuery" value ="${jdbc.validationQuery}" /> <property name ="testWhileIdle" value ="${jdbc.testWhileIdle}" /> <property name ="testOnBorrow" value ="${jdbc.testOnBorrow}" /> <property name ="testOnReturn" value ="${jdbc.testOnReturn}" /> <property name ="logAbandoned" value ="true" /> <property name ="filters" value ="stat" /> </bean > <bean id ="vendorProperties" class ="org.springframework.beans.factory.config.PropertiesFactoryBean" > <property name ="properties" > <props > <prop key ="PostgreSQL" > postgresql</prop > <prop key ="MySQL" > mysql</prop > </props > </property > </bean > <bean id ="databaseIdProvider" class ="org.apache.ibatis.mapping.VendorDatabaseIdProvider" > <property name ="properties" ref ="vendorProperties" /> </bean > <bean id ="sqlSessionFactory" class ="org.mybatis.spring.SqlSessionFactoryBean" > <property name ="dataSource" ref ="${dataSource}" /> <property name ="mapperLocations" value ="classpath:mapper/**/*.xml" /> <property name ="configLocation" value ="classpath:mybatis-config.xml" /> <property name ="typeAliasesPackage" value ="com.valten.**.model" /> <property name ="databaseIdProvider" ref ="databaseIdProvider" /> </bean > <bean id ="mapperScannerConfigurer" class ="org.mybatis.spring.mapper.MapperScannerConfigurer" > <property name ="basePackage" value ="com.valten.**.dao" /> <property name ="sqlSessionFactoryBeanName" value ="sqlSessionFactory" /> </bean > <bean id ="transactionManager" class ="org.springframework.jdbc.datasource.DataSourceTransactionManager" > <property name ="dataSource" ref ="${dataSource}" /> </bean > <tx:annotation-driven transaction-manager ="transactionManager" /> </beans >
logback.xml 我们在项目中经常会使用到日志,所以这里还有配置日志xml,在resources
文件夹里新建logback.xml
文件,所给出的日志输出格式也是最基本的控制台输出,大家有兴趣查看logback官方文档 。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 <?xml version="1.0" encoding="UTF-8"?> <configuration debug ="true" > <property name ="APP_NAME" value ="logtest" /> <property name ="LOG_HOME" value ="${log.dir:-logs}/${APP_NAME}" /> <property name ="ENCODER_PATTERN" value ="%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{80} - %msg%n" /> <contextName > ${APP_NAME}</contextName > <appender name ="STDOUT" class ="ch.qos.logback.core.ConsoleAppender" > <encoder class ="ch.qos.logback.classic.encoder.PatternLayoutEncoder" > <Pattern > ${ENCODER_PATTERN}</Pattern > </encoder > </appender > <appender name ="FILE" class ="ch.qos.logback.core.rolling.RollingFileAppender" > <rollingPolicy class ="ch.qos.logback.core.rolling.TimeBasedRollingPolicy" > <fileNamePattern > ${LOG_HOME}/output.%d{yyyy-MM-dd}.log</fileNamePattern > <maxHistory > 7</maxHistory > </rollingPolicy > <encoder class ="ch.qos.logback.classic.encoder.PatternLayoutEncoder" > <pattern > ${ENCODER_PATTERN}</pattern > </encoder > </appender > <appender name ="ERROR_FILE" class ="ch.qos.logback.core.rolling.RollingFileAppender" > <rollingPolicy class ="ch.qos.logback.core.rolling.TimeBasedRollingPolicy" > <fileNamePattern > ${LOG_HOME}/error.%d{yyyy-MM-dd}.log</fileNamePattern > <maxHistory > 7</maxHistory > </rollingPolicy > <encoder class ="ch.qos.logback.classic.encoder.PatternLayoutEncoder" > <pattern > ${ENCODER_PATTERN}</pattern > </encoder > <filter class ="ch.qos.logback.classic.filter.ThresholdFilter" > <level > WARN</level > </filter > </appender > <appender name ="SYNC_FILE" class ="ch.qos.logback.core.rolling.RollingFileAppender" > <rollingPolicy class ="ch.qos.logback.core.rolling.TimeBasedRollingPolicy" > <fileNamePattern > ${LOG_HOME}/sync.%d{yyyy-MM-dd}.log</fileNamePattern > <maxHistory > 7</maxHistory > </rollingPolicy > <encoder class ="ch.qos.logback.classic.encoder.PatternLayoutEncoder" > <pattern > ${ENCODER_PATTERN}</pattern > </encoder > </appender > <logger name ="log.sync" level ="DEBUG" addtivity ="true" > <appender-ref ref ="SYNC_FILE" /> </logger > <root > <level value ="DEBUG" /> <appender-ref ref ="STDOUT" /> <appender-ref ref ="FILE" /> <appender-ref ref ="ERROR_FILE" /> </root > </configuration >
web.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 <web-app xmlns ="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation ="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version ="3.1" metadata-complete ="true" > <filter > <filter-name > encodingFilter</filter-name > <filter-class > org.springframework.web.filter.CharacterEncodingFilter</filter-class > <async-supported > true</async-supported > <init-param > <param-name > encoding</param-name > <param-value > UTF-8</param-value > </init-param > </filter > <filter-mapping > <filter-name > encodingFilter</filter-name > <url-pattern > /*</url-pattern > </filter-mapping > <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/spring-*.xml</param-value > </init-param > </servlet > <servlet-mapping > <servlet-name > springmvc</servlet-name > <url-pattern > /</url-pattern > </servlet-mapping > <welcome-file-list > <welcome-file > /index.jsp</welcome-file > <welcome-file > /index.html</welcome-file > <welcome-file > /reg.html</welcome-file > </welcome-file-list > </web-app >
附上源码地址:https://gitee.com/valten/valten-ssm-master.git
参考:
https://blog.csdn.net/qq598535550/article/details/51703190 https://www.jianshu.com/p/db57d92bffb7