书评网项目SSM框架整合
今天开始做一个书评网的项目,首先从搭建环境开始,一步步整合SSM。这篇主要总结一下如何整合Spring、Mybatis、SpringMVC。
1. 创建Maven项目进行依赖管理
? New Project --> Maven --> next --> name/路径 等信息自拟 --> Finish
? 在pom.xml文件中写入
? 以下pom.xml是最后整合好的所有依赖,刚开始搭建环境的时候不需要一次性全部加进来,可以一点一点的加,这样也更利于理解每个部分的jar包都有什么作用,当然,一次都加进来也是可以的。
? 需要注入的依赖如下:
<?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>com.posion</groupId>
<artifactId>reader</artifactId>
<version>1.0-SNAPSHOT</version>
//aliyun镜像加速jar下载
<repositories>
<repository>
<id>aliyun</id>
<name>aliyun</name>
<url>https://maven.aliyun.com/repository/public</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.30</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.11.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.11.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.4</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.3</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.14</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>3.3.2</version>
</dependency>
</dependencies>
</project>
2. 生成一个web项目
? File --> project Structure
完成后在 WEB-INF 下新建文件夹 ftl 后续使用
按照下图建立包、文件等
3. 搭建Spring环境
?
3.1 配置文件applicationContext.xml
? 打开src --> main --> resources --> applicationContext.xml。 此文件为Spring配置文件。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:task="http://www.springframework.org/schema/task"
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
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="com.posion"/>
</beans>
3.2 测试Spring 的I0C环境
? 我们写一个普通的java类java.util.Date类来测试一下Spring IoC是否正常,如果在测试程序中能正常注入,则说明Spring的IoC环境搭建成功,下面我们写一个测试用例:
使用此测试用例前需要注入测试依赖spring-test 以及 junit
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class SSMTest {
@Resource
private Date date;
@Test
public void springIoc() {
System.out.println(date);
}
}
? 最后能正常输出:Thu Apr 28 22:45:13 CST 2021。说明Date对象已经被Spring给注入进来了,从而验证了Spring IoC功能正常,为此,Spring的环境搭建完成。
4. Spring 与 SpringMVC环境配置
1. 在注入pom.xml 中注入依赖
2. 配置DispatcherServlet前端控制器
3. 开启SprimgMVC注解
4. 解决中文乱码,指定请求或者响应的编码格式
5. 配置Freemarker模板引擎
6. JSON(Jackson)序列化输出配置
4.1 搭建SpringMVC环境
? 对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_3_1.xsd"
version="3.1">
<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:applicationContext*.xml</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<filter-name>characterFilter</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>
</filter>
<filter-mapping>
<filter-name>characterFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
? 如上,
**load-on-startup:**表示启动容器时初始化该Servlet;
**url-pattern:**表示哪些请求交给Spring Web MVC处理, “/” 是用来定义默认servlet映射的。也可以如 “*.html” 表示拦截所有以html为扩展名的请求。
**contextConfigLocation:**表示用于加载Bean的配置文件;以此来进行初始化上下文。
4.2 SpringMVC开启
在applicatiomContext.xml写入以下配置
<context:component-scan base-package="com.posion"/>
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=utf-8</value>
<value>application/json;charset=utf-8</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<mvc:default-servlet-handler/>
<bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPath" value="/WEB-INF/ftl"/>
<property name="freemarkerSettings">
<props>
<prop key="defaultEncoding">UTF-8</prop>
</props>
</property>
</bean>
<bean id="ViewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<property name="contentType" value="text/html;charset=utf-8"/>
<property name="suffix" value=".ftl"/>
</bean>
5. Spring与Mybatis整合
5.1 Mybatis配置
- pom.xml注入相关依赖
- 配置数据源dataSource
- SqlSessionFactoryBean用于根据配置信息创建SqlSessionFactory
- 配置Mapper扫描器
- MyBatis配置文件地址
? 在applicationContext.xml文件中进行以下配置:
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/reader?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
<property name="initialSize" value="5"/>
<property name="maxActive" value="20"/>
</bean>
<bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mapperLocations" value="classpath:mappers/*.xml"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.posion.reader.mapper"/>
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<tx:annotation-driven/>
? 在创建的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>
<plugins>
<plugin interceptor="com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor"/>
</plugins>
</configuration>
5.2 mybatis-Plus配置
? 1. 注入依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>3.3.2</version>
</dependency>
-
将原生SqlSessionFactoryBean对象指向 com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean
<bean id="sessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mapperLocations" value="classpath:mappers/*.xml"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
5.3 测试
? 1. 在数据库reader 下创建表 test 提供字段 id,content
? 2. 在entity包下创建创建实体类Test 提供getter和setter方法
@TableName("test")
public class Test {
@TableId(type = IdType.AUTO)
@TableField("id")
private Integer id;
@TableField("content")
private String content;
}
? 3. 在mpaaer包下创建TestMapper接口继承BaseMapper
public interface TestMapper extends BaseMapper<Test> {
}
? 4. 在resources下mappers创建test.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.posion.reader.mapper.TestMapper">
</mapper>
? 5. 测试类 使用此测试用例前需要注入测试依赖spring-test 以及 junit
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class MybatisPlusTest {
@Resource
private TestMapper testMapper;
@org.junit.Test
public void testInsert(){
Test test = new Test();
test.setContent("mybatis plus 测试");
testMapper.insert(test);
}
@org.junit.Test
public void testUpdate(){
Test test = testMapper.selectById(16);
test.setContent("update 测试");
testMapper.updateById(test);
}
@org.junit.Test
public void testDelete(){
testMapper.deleteById(15);
}
@org.junit.Test
public void testSelect(){
QueryWrapper<Test> queryWrapper = new QueryWrapper<Test>();
queryWrapper.eq("id", 16);
queryWrapper.gt("id", 10);
List<Test> list = testMapper.selectList(queryWrapper);
System.out.println(list);
}
}
6. 其他组件
6.1 日志组件
? 注入日志组组件依赖后,在logback.xml中进行以下配置
<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>%d{HH:mm:ss} %-5level [%thread] %logger{30} - %msg%n</pattern>
<charser>UTF-8</charser>
</encoder>
</appender>
<root level="debug">
<appender-ref ref="console"/>
</root>
</configuration>
注入日志组组件依赖后,在logback.xml中进行以下配置
<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>%d{HH:mm:ss} %-5level [%thread] %logger{30} - %msg%n</pattern>
<charser>UTF-8</charser>
</encoder>
</appender>
<root level="debug">
<appender-ref ref="console"/>
</root>
</configuration>
|