SpringMVC:SSM(Spring+SpringMVC+MyBatis)代码整理

SpringMVC - 07

SSM 框架代码整理

用到的环境

整体的项目结构如图所示:


一、准备工作

1. 分析需求、准备数据库

2. 新建一个项目,导入依赖:pom.xml

<dependencies>
    <!-- junit -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>

    <!-- mysql 数据库驱动 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.16</version>
    </dependency>

    <!-- 数据库连接池 c3p0 -->
    <dependency>
        <groupId>com.mchange</groupId>
        <artifactId>c3p0</artifactId>
        <version>0.9.5.5</version>
    </dependency>

    <!-- Servlet 依赖 -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
    </dependency>

    <!-- JSP 依赖 -->
    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>jsp-api</artifactId>
        <version>2.1</version>
    </dependency>

    <!-- JSTL 表达式依赖 -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>

    <!-- MyBatis -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.7</version>
    </dependency>

    <!-- mybatis-spring -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>2.0.6</version>
    </dependency>

    <!-- spring-webmvc -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.3.18</version>
    </dependency>

    <!-- aspectjweaver -->
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.9.6</version>
    </dependency>

    <!-- spring-jdbc -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.3.23</version>
    </dependency>

    <!-- jackson-databind -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.14.1</version>
    </dependency>
    
    <!-- 文件上传 -->
    <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.3.3</version>
    </dependency>
    
    <!-- lombok -->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.24</version>
    </dependency>
</dependencies>

<!-- 在 build 中配置 resources,来防止我们静态资源导出失败的问题 -->
<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>true</filtering>
        </resource>

        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>true</filtering>
        </resource>
    </resources>
</build>

3. 用 IDEA 连接数据库


二、MyBatis 层

1. 外部配置文件:db.properties

jdbc.drive=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/数据库名?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=Asia/Shanghai
jdbc.username=root
jdbc.password=1142553864qq

说明一定要是 jdbc.xxx ,根据实际情况填写要连接的数据库名、用户名及密码。

2. MyBatis 核心配置文件:mybatis-config.xml

<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-config.dtd">
<!-- configuration 核心配置文件 -->
<configuration>
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <setting name="cacheEnabled" value="true"/>
    </settings>

    <typeAliases>
        <typeAlias type="com.Sun3285.pojo.xxx" alias="xxx"/>
        <!--<package name="com.Sun3285.pojo"/>-->
    </typeAliases>
</configuration>

说明:在 MyBatis 核心配置文件中进行设置以及别名管理,其余设置在 Spring 配置文件中配置。

3. 实体类

@Data
@AllArgsConstructor
@NoArgsConstructor
public class xxx implements Serializable {

    private int 属性1;
    private String 属性2;
}

说明:实体类需要实现序列化:实现 Serializable 接口。

4. Dao 接口:xxxMapper.java

public interface xxxMapper {

    // 方法
    返回值类型 方法名(参数类型 参数);
}

说明:如果参数类型为基本数据类型或 String 类型,最好在参数前加注解 @Param(“xxx”) 声明。

5. Dao 实现类:xxxMapper.xml

<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.Sun3285.dao.xxxMapper">

    <cache/>

    <insert/delete/update/select id="方法名" parameterType="参数类型" resultType="返回值类型">
        sql 语句,取值用:#{参数}
    </insert>
</mapper>

说明:记得要在命名空间 namespace 中绑定实现的接口。

6. Service 接口:xxxService.java

public interface xxxService {
    
    // Dao 接口中定义的方法
    返回值类型 方法名(参数类型 参数);
    
    // 其他业务方法
    返回值类型 方法名(参数类型 参数);
}

说明

  • 其中 Dao 接口的方法,参数不需要加注解 @Param(“xxx”) 声明;
  • 在 Service 接口中,不仅包含 Dao 接口中所有的方法,还可以定义一些业务方法。

7. Service 实现类:xxxServiceImpl.java

public class xxxServiceImpl implements xxxService {

    // 接口类型的 mapper
    private xxxMapper mapper;

    // set 方法
    public void setMapper(xxxMapper mapper) {
        this.mapper = mapper;
    }

    // 重写 Service 接口的方法
    public 返回值类型 方法名(参数类型 参数) {
        // Service 层调用 Dao 层
        return mapper.方法名(参数);
    }
}

说明:Service 层调用 Dao 层,可以操作数据库或者得到数据库中的数据,并且可以在类中实现一些业务逻辑,完成需要的功能。这里是手动注册了业务实现类,也可以采用注解的方式,两种方式各自的实现如下:

  • 手动注册:这里用 set 方式注入,并且在 spring-service.xml 配置文件中手动注册 bean;
  • 注解方式自动装配):在业务实现类上加注解 @Service 声明,以及在 mapper 属性上加注解 @Autowired 以及 @Qualifier(“xxxMapper”) 完成自动装配代替之前的 set 方式注入,并且在 spring-service.xml 配置文件中配置扫描 service 包下的类。

三、Spring 层

1. Spring 整合 Dao 层配置文件:spring-dao.xml

<?xml version="1.0" encoding="UTF8"?>
<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
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx
        https://www.springframework.org/schema/tx/spring-tx.xsd">

    <!-- 外部配置文件 -->
    <context:property-placeholder ignore-unresolvable="true" location="classpath:db.properties"/>

    <!-- 注册 dataSource:c3p0 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.drive}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>

        <!-- c3p0 连接池的私有属性 -->
        <property name="maxPoolSize" value="30"/>
        <property name="minPoolSize" value="10"/>
        <!-- 关闭连接后,不自动提交 -->
        <property name="autoCommitOnClose" value="false"/>
        <!-- 设置连接超时时间:10s -->
        <property name="checkoutTimeout" value="10000"/>
        <!-- 设置获取连接失败时的重试次数 -->
        <property name="acquireRetryAttempts" value="2"/>
    </bean>

    <!-- Spring 原生的数据库连接池 -->
<!--    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">-->
<!--        <property name="driverClassName" value="${jdbc.drive}"/>-->
<!--        <property name="url" value="${jdbc.url}"/>-->
<!--        <property name="username" value="${jdbc.username}"/>-->
<!--        <property name="password" value="${jdbc.password}"/>-->
<!--    </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*:com/Sun3285/dao/*.xml"/>
    </bean>

    <!-- 配置 Dao 接口扫描,可以动态地实现 Dao 接口注入到 Spring 容器中 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 注入 sqlSessionFactory -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!-- 扫描 Dao 接口 -->
        <property name="basePackage" value="com.Sun3285.dao"/>
    </bean>
</beans>

说明

  • 数据库连接池 dataSource 可以任意选择,可以使用 Spring 原生的数据库连接池,也可以使用 c3p0 等其他的数据库连接池;
  • Dao 实现类 xxxMapper.xml 需要在本配置文件中注册;
  • 这里配置了 Dao 接口扫描,代替了 sqlSessionTemplate 的注册,可以动态地实现 Dao 接口注入到 Spring 容器中。这样,接下来在注册 Service 实现类时,可以直接从容器中拿到 mapper 对象。

2. Spring 整合 Service 层配置文件:spring-service.xml

<?xml version="1.0" encoding="UTF8"?>
<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
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx
        https://www.springframework.org/schema/tx/spring-tx.xsd">

	<!-- 通过注解注册实现类:扫描 service 包下的类 -->
<!--    <context:component-scan base-package="com.Sun3285.service"/>-->

    <!-- 注册业务类实现类 -->
    <bean id="xxxServiceImpl" class="com.Sun3285.service.xxxServiceImpl">
        <property name="mapper" ref="xxxMapper"/>
    </bean>

    <!-- 配置声明式事务 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!-- 结合 AOP 实现事务的织入 -->
    <!-- 配置事务通知(切面) -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!-- 给哪些方法配置事务、事务的传播特性(默认 REQUIRED) -->
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>

    <!-- 配置事务切入 -->
    <aop:config>
        <aop:pointcut id="pointcut" expression="execution(* com.Sun3285.service.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/>
    </aop:config>
</beans>

说明

  • 注册业务实现类时,可以手动注册,也可以使用注解,如果通过注解注册实现类,要在配置文件中配置扫描 service 包下的类,并在业务实现类上加注解 @Service 声明,以及在 mapper 属性上加注解 @Autowired 以及 @Qualifier(“xxxMapper”) 完成自动装配代替之前的 set 方式注入,这里注解 @Qualifier 中的值 xxxMapper 与手动注册时 ref 的 xxxMapper 相同;
  • 事务要放在 Service 层上,而不是 Dao 层,一个业务方法中的所有操作要么都成功,要么都失败

四、SpringMVC 层

1. 转为 Web 项目

把普通 Maven 项目转为 Web 项目,打开项目结构,添加 lib 目录,添加依赖

2. 配置 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 前端控制器 -->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- DispatcherServlet 绑定 Spring 的配置文件 -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext.xml</param-value>
        </init-param>
        <!-- 启动级别:1,和服务器一起启动 -->
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!-- 配置 SpringMVC 的乱码过滤器 -->
    <filter>
        <filter-name>encoding</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>encoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- 配置 Session 的过期时间:15 分钟 -->
    <session-config>
        <session-timeout>15</session-timeout>
    </session-config>
</web-app>

说明:这里 DispatcherServlet 绑定的 Spring 配置文件应该为总的配置文件:applicationContext.xml。

3. Spring 整合 Controller 层配置文件:spring-mvc.xml

<?xml version="1.0" encoding="UTF8"?>
<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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://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/mvc
        https://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!-- 自动扫描包,让指定包下的注解生效,由 IOC 容器统一管理 -->
    <context:component-scan base-package="com.Sun3285.controller"/>

    <!-- 让 SpringMVC 不处理静态资源 -->
    <mvc:default-servlet-handler/>

    <!-- 支持注解驱动 -->
    <mvc:annotation-driven/>

    <!-- 视图解析器 -->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 前缀 -->
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <!-- 后缀 -->
        <property name="suffix" value=".jsp"/>
    </bean>

    <!-- JSON 乱码问题配置 -->
    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <constructor-arg value="UTF-8"/>
            </bean>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="objectMapper">
                    <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
                        <property name="failOnEmptyBeans" value="false"/>
                    </bean>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>
</beans>

说明:需要在 WEB-INF 文件夹下新建 jsp 文件夹,用来存放 jsp 页面。

4. 整合 Spring 配置文件:applicationContext.xml

<?xml version="1.0" encoding="UTF8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- 导入 Spring 配置文件 -->
    <import resource="spring-dao.xml"/>
    <import resource="spring-service.xml"/>
    <import resource="spring-mvc.xml"/>
</beans>

说明:可以打开项目结构看到配置文件是否整合在了一起。

5. 编写控制类:xxxController.java

@Controller
@RequestMapping("/请求路径1")
public class xxxController {

    @Autowired
    @Qualifier("xxxServiceImpl")
    private xxxService xxxService;

    // 前端页面的每一个操作对应控制类中的一个方法
    @RequestMapping("/请求路径2")
    public String 方法名() {
        // Controller 层调用 Service 层
        xxxService.方法名();

        // 返回的字符串会经过视图解析器解析
        return "xxx";
        // 重定向到页面:return "redirect:/index.jsp";
        // 重定向到请求:return "redirect:/请求路径1/请求路径2";
    }
}

说明

  • Controller 层调用 Service 层;
  • 重定向到请求时,不用写项目名。

6. 编写前端页面

7. 配置 Tomcat,运行


五、总结

  1. 到此 SSM 框架搭建完毕,之后就是编写前端页面和控制类,使得前端页面的每一个操作都对应控制类中的一个方法
  2. 要保证在项目结构中,把所有的配置文件都放到一起;
  3. 框架搭建完毕后,要进行测试,确保框架没有问题后,进行具体项目的编写和完善;
  4. 如果最后报错,可以从以下几个方面排查错误
    • 查看 Bean 是否注入成功;
    • 用 Junit 单元测试,通过 new ClassPathXmlApplicationContext("applicationContext.xml") 得到容器 context,用容器取业务实现类对象 context.getBean("xxxServiceImpl") ,如果业务类方法可以执行成功,说明底层没有问题;
    • 通过错误提示信息,排查错误。
  5. 仍有问题请给我发私信。
  • 21
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Sun 3285

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值