一、搭建web环境
- 打开idea后,新建一个工程
- 选择Maven并点击Next
- 输入项目名称和路径后点击finish
- 规定工程的打包方式为war
(1)在pom文件中添加相关依赖,出现了两个问题:①大量提示"...not found",这是由于在复制粘贴时,附带了大量透明的符号,这个我放到notepad++利用xml Tools格式化后没有解决问题;②我使用的IDEA版本为2019.3.5,其建立的Maven工程配置完依赖后无法自动下载,一种方法是自己手动更新,如图所示:
(2)还有一种方法是让其自动下载,这里需要点击File---settings---Maven---importing---勾选Import Maven projects automatically;
(3)还有一种情况需要注意,就是当开启代理服务器时,可以按方法一下载,但是它不会自动下载相关依赖,奇怪的是重新启动代理服务器后,它又行了???
- 下面是SSM整合需要的pom文件配置,需要手动设置自己的mysql版本,jdk版本
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>SSM</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<dependencies>
<!--单元测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!--springmvc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
<!--servlet-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
<scope>provided</scope>
</dependency>
<!--文件上传-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<!--jackson-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.11.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.11.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.2</version>
</dependency>
<!--mybatiis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<!--jdbc-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.10.RELEASE</version>
</dependency>
<!--未知-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
<!--spring-mybatis整合-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.2</version>
</dependency>
<!--druid-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.18</version>
</dependency>
<!--log-->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.30</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<!--源代码使用的JDK版本-->
<source>1.8</source>
<!--目标class文件的编译版本-->
<target>1.8</target>
<encoding>utf-8</encoding>
</configuration>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
</project>
- 在src/main/新建包,名为webapp
- 在webapp下新建目录WEB-INF,WEB-INF下新建web.xml
- 在web.xml配置基本信息
<?xml version="1.0" encoding="UTF-8"?>
<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_4_0.xsd"
version="4.0">
</web-app>
- 新建index.jsp,用于测试是否web环境搭建成功
- 配置tomcat
- 修改服务器名称、工程路径、端口号及资源更新
二、配置文件整合
- 在src/main/resources下,新建数据源配置文件:db.properties
- db.properties的内容如下
#若mysql使用8.0以上版本,则驱动为com.mysql.cj.jdbc.Driver
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/naruto?useUnicode=true&characterEncoding=utf8&useSSL=false
#若mysql使用8.0以上版本,需要配置时区
#jdbc.url=jdbc:mysql://localhost:3306/naruto?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true
jdbc.username=root
jdbc.password=root
filters=wall,stat
maxActive=20
initialSize=3
maxWait=5000
minIdle=3
maxIdle=15
timeBetweenEvictionRunsMillis=60000
minEvictableIdleTimeMillis=300000
validationQuery=SELECT 'x'
testWhileIdle=true
testOnBorrow=false
testOnReturn=false
maxOpenPreparedStatements=20
removeAbandoned=true
removeAbandonedTimeout=1800
logAbandoned=true
- 在src/main/resources下,新建spring配置文件application.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.xsd
http://www.springframework.org/schema/context
https://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">
<!-- 加载外部的数据库信息 classpath:不叫会报错具体原因下边解释-->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 加入springmvc的配置 -->
<import resource="classpath:springmvc-servlet.xml"/>
<context:component-scan base-package="cn.itnanls"/>
<!-- Mapper 扫描器 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 扫描 cn.wmyskxz.mapper 包下的组件 -->
<property name="basePackage" value="cn.itnanls.dao"/>
</bean>
<!--配置数据源:数据源有非常多,可以使用第三方的,也可使使用Spring的-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<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>
<!--配置SqlSessionFactory-->
<bean id="sqlSessionFactory"
class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!--关联Mybatis-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="mapperLocations" value="classpath:mappers/*.xml"/>
</bean>
<!--注册sqlSessionTemplate , 关联sqlSessionFactory-->
<!--<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!–利用构造器注入–>
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>-->
<!--配置事务管理器-->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!--配置事务通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!--配置哪些方法使用什么样的事务,配置事务的传播特性-->
<tx:method name="add*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="search*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!--配置aop织入事务-->
<aop:config>
<aop:pointcut id="txPointcut" expression="execution(*cn.itnanls.service.impl.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
</aop:config>
</beans>
- webapp下新建三个文件
- 在src/main/resources下,新建mapper目录
- 在src/main/resources下,新建配置文件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="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>
<!-- 下划线转驼峰式 -->
<setting name="mapUnderscoreToCamelCase" value="true"/>
<setting name="logPrefix" value="sql."/>
</settings>
<typeAliases>
<package name="cn.itnanls.entity"/>
</typeAliases>
</configuration>
- 更新web.xml中的内容
<?xml version="1.0" encoding="UTF-8"?>
<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_4_0.xsd"
version="4.0">
<!--注册DispatcherServlet,这是springmvc的核心-->
<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:application.xml</param-value>
</init-param>
<!--加载时先启动-->
<load-on-startup>1</load-on-startup>
</servlet>
<!--/ 匹配所有的请求,不包括.jsp-->
<!--/* 匹配所有的请求,包括.jsp-->
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
- 重启服务器,没有报错
三、Easy Code自动生成代码
- idea添加mysql数据源
- 点击go to Driver
- 选择jdbc驱动和合适的jdbc的jar包版本,jar包在maven的本地仓库里找就可以,找不到就自己下载一个,点击apply后回到上一步
- 可以自定义数据源名称、配置数据库地址、端口号、用户名、密码,url地址就是db.properties文件中的url地址
- 使用Easy Code检查表格中字段的类型是否正确,比如id应该为Integer,不正确就直接修改
- Easy Code自动生成代码,结果如右图所示,将右图中的AdminDefault.java删除,不然启动tomcat会报错;
- 启动tomcat,测试控制器下的selectOne方法,请求地址为:http://localhost:1724/SSM/admin/selectOne?id=1,可以得到一行数据
- 注意,如果出现500错误,可以从这几个方向去排查:①看数据库配置文件里数据源的配置是否符合其版本,比如mysql8.0与它以下的版本配置是不一样的;②500错误页面有很多异常,先不要仔细去看,先看看这些异常是不是从某个配置文件里的某一行有问题,很多时候,一个空格就能导致大量异常;
四、配置druid数据源
- 在web.xml中开启web服务,配置内容如下
<!--配置druid数据源-->
<!-- 连接池 启用 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>
<init-param>
<!-- 用户名 -->
<param-name>loginUsername</param-name>
<param-value>itnanls</param-value>
</init-param>
<init-param>
<!-- 密码 -->
<param-name>loginPassword</param-name>
<param-value>123</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>DruidStatView</servlet-name>
<url-pattern>/druid/*</url-pattern>
</servlet-mapping>
- 重启tomcat,访问:http://localhost:1724/SSM/druid/可跳转至登录界面,然后输入上述配置文件中的用户名与密码即可
五、整合logback日志
- 在src/main/resources下,新建logback.xml,并配置以下内容,根据需要修改日志级别、生成路径等
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="60 seconds" debug="false">
<!-- 定义参数常量 -->
<!-- 日志级别 TRACE<DEBUG<INFO<WARN<ERROR -->
<!-- logger.trace("msg") logger.debug... -->
<property name="log.level" value="debug"/>
<property name="log.maxHistory" value="30"/>
<property name="log.filePath" value="D:/log"/>
<property name="log.pattern"
value="%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level
%logger{50} - %msg%n"/>
<!-- 控制台输出设置 -->
<appender name="consoleAppender"
class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>${log.pattern}</pattern>
</encoder>
</appender>
<!-- DEBUG级别文件记录 -->
<appender name="debugAppender"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 文件路径 -->
<file>${log.filePath}/debug.log</file>
<!-- 滚动日志文件类型,就是每天都会有一个日志文件 -->
<rollingPolicy
class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 文件名称 -->
<fileNamePattern>${log.filePath}/debug/debug.%d{yyyy-MM-
dd}.log.gz
</fileNamePattern>
<!-- 文件最大保存历史数量 -->
<maxHistory>${log.maxHistory}</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${log.pattern}</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>DEBUG</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!-- INFO -->
<appender name="infoAppender"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 文件路径 -->
<file>${log.filePath}/info.log</file>
<rollingPolicy
class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 文件名称 -->
<fileNamePattern>${log.filePath}/info/info.%d{yyyy-MM-dd}.log.gz
</fileNamePattern>
<!-- 文件最大保存历史数量 -->
<maxHistory>${log.maxHistory}</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${log.pattern}</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>INFO</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!-- cn.itnanls 开头的日志对应形式 -->
<logger name="cn.itnanls" level="${log.level}" additivity="true">
<appender-ref ref="debugAppender"/>
<appender-ref ref="infoAppender"/>
</logger>
<!-- <root> 是必选节点,用来指定最基础的日志输出级别,只有一个level属性 -->
<root level="info">
<appender-ref ref="consoleAppender"/>
</root>
<!-- 捕捉sql开头的日志 -->
<appender name="MyBatis"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.filePath}/sql_log/mybatis-sql.log</file>
<rollingPolicy
class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<FileNamePattern>${log.filePath}/sql_log/mybatis-
sql.log.%d{yyyy-MM-dd}
</FileNamePattern>
<maxHistory>30</maxHistory>
</rollingPolicy>
<encoder
class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>%thread|%d{yyyy-MM-dd
HH:mm:ss.SSS}|%level|%logger{36}|%m%n
</pattern>
</encoder>
</appender>
<logger name="sql" level="DEBUG">
<appender-ref ref="MyBatis"/>
</logger>
</configuration>
六、整合pageHelper
- 在pom.xml中添加相关依赖
<!--添加分页依赖-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.2.0</version>
</dependency>
- 在spring的配置文件中sqlSessionFactory里配置拦截器插件
<property name="plugins">
<array>
<bean class="com.github.pagehelper.PageInterceptor">
<property name="properties">
<!--使用下面的方式配置参数,一行配置一个 -->
<value>
helperDialect=mysql
</value>
</property>
</bean>
</array>
</property>
七、整合thymeleaf
- 在pom文件中引入相关依赖
<!--添加thymleaf相关依赖-->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf</artifactId>
<version>3.0.12.RELEASE</version>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
<version>3.0.12.RELEASE</version>
</dependency>
- 删除springmvc配置文件中的视图解析器
<!--视图解析器:DispatcherServlet给他的ModelAndView-->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="InternalResourceViewResolver">
<!--前缀-->
<property name="prefix" value="/WEB-INF/page/"/>
<!--后缀-->
<property name="suffix" value=".jsp"/>
</bean>
- 在springmvc配置文件中添加thymeleaf的模板解析器、模板引擎与视图解析器
<!--配置模板解析器和模板引擎-->
<!-- SpringResourceTemplateResolver automatically integrates with Spring's own -->
<!-- resource resolution infrastructure, which is highly recommended. -->
<bean id="templateResolver"
class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
<property name="prefix" value="/WEB-INF/templates/" />
<property name="suffix" value=".html" />
<!-- HTML is the default value, added here for the sake of clarity. -->
<property name="templateMode" value="HTML" />
<!-- Template cache is true by default. Set to false if you want -->
<!-- templates to be automatically updated when modified. -->
<property name="cacheable" value="true" />
</bean>
<!-- SpringTemplateEngine automatically applies SpringStandardDialect and -->
<!-- enables Spring's own MessageSource message resolution mechanisms. -->
<bean id="templateEngine"
class="org.thymeleaf.spring5.SpringTemplateEngine">
<property name="templateResolver" ref="templateResolver" />
<!-- Enabling the SpringEL compiler with Spring 4.2.4 or newer can speed up -->
<!-- execution in most scenarios, but might be incompatible with specific -->
<!-- cases when expressions in one template are reused across different data -->
<!-- ypes, so this flag is "false" by default for safer backwards -->
<!-- compatibility. -->
<property name="enableSpringELCompiler" value="true" />
</bean>
<bean class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
<property name="templateEngine" ref="templateEngine" />
<!-- NOTE 'order' and 'viewNames' are optional -->
<property name="order" value="1" />
<property name="viewNames" value="*.html,*.xhtml" />
</bean>