当前位置:网站首页>SSM 整合

SSM 整合

2022-07-07 05:23:00 熙攘。

SSM框架,即Spring+SpringMVC+Mybatis,由Spring、MyBatis两个开源框架整合而成(SpringMVC是Spring的部分内容)。至此我对SSM的学习告一段落。

 

注意事项:

如果Mybatis中的mapper.xml与Mapper接口同名且分别在java目录和resources目录的同名包下,那么spring扫描Mapper接口的同时会自动扫描同名的Mapper.xml并装配;

如果Mapper.xml与Mapper接口不同名或者不在同名包下,就必须在applicationContext.xml中配置sessionFactory的mapperLocations属性来指定mapper.xml的位置,此时spring通过识别mapper.xml的namespace来确定对应的Mapper接口。

利用Maven构建完整的SSM项目

一、导入坐标至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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>org.example</groupId>
  <artifactId>finalSSM</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>


  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.13.1</version>
    </dependency>

    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.9.5</version>
    </dependency>

    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.2.8</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.0.5.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>5.0.5.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>5.0.5.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.0.5.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.0.1</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>javax.servlet.jsp-api</artifactId>
      <version>2.2.1</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.9.0</version>
    </dependency>

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.0</version>
    </dependency>

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>2.9.0</version>
    </dependency>

    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.1</version>
    </dependency>

    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.3</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>5.0.5.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>5.0.5.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter</artifactId>
      <version>RELEASE</version>
      <scope>compile</scope>
    </dependency>

    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.26</version>
    </dependency>

    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.4.6</version>
    </dependency>

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

    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
    </dependency>

    <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper</artifactId>
      <version>5.2.0</version>
    </dependency>

    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>

  </dependencies>

  <build>
    <finalName>finalSSM</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

二、 数据库

目标数据库中的account表:

三、实体类

set方法便于Spring注入

package Domain;
/*
   实体类
 */
public class Account {
    private int id;
    private String name;
    private int money;

    public int getId() {
        return id;
    }

    public Account setId(int id) {
        this.id = id;
        return this;
    }

    public String getName() {
        return name;
    }

    public Account setName(String name) {
        this.name = name;
        return this;
    }

    public int getMoney() {
        return money;
    }

    public Account setMoney(int money) {
        this.money = money;
        return this;
    }

    @Override
    public String toString() {
        return "account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                '}';
    }
}

四、Mapper接口

尽量与mapper.xml同名且在同名包下

package Mapper;

import Domain.Account;
import java.util.List;
/*
   mapper接口
 */
public interface AccountMapper {
    public void save(Account user);

    public List<Account> findAll();

}

五、Service

主要为后端与数据库的交互

接口:

package Service;

import Domain.Account;
import java.io.IOException;
import java.util.List;

public interface AccountService {
    public void save(Account user) throws IOException;

    public List<Account> findAll() throws IOException;

}

实现:

package Service.Impl;

import Domain.Account;
import Mapper.AccountMapper;
import Service.AccountService;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
/*
   后端与数据库交互
 */
@Service("accountService")
public class serviceImpl implements AccountService {
    @Autowired
    private AccountMapper accountMapper;

    @Override
    public void save(Account user) throws IOException {
        //传统Mybatis方法
        /*InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        AccountMapper mapper = sqlSession.getMapper(AccountMapper.class);
        mapper.save(user);
        sqlSession.commit();
        sqlSession.close();*/

        //整合方法
        accountMapper.save(user);
    }

    @Override
    public List<Account> findAll() throws IOException {
        //Mybatis方法
        /*InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        AccountMapper mapper = sqlSession.getMapper(AccountMapper.class);
        List<Account> list = mapper.findAll();
        sqlSession.commit();
        sqlSession.close();
        return list;*/

        //整合方法
        return accountMapper.findAll();
    }
}

六、Control

主要为SpringMVC的前端控制

package Control;

import Domain.Account;
import Service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import java.io.IOException;
/*
   前端控制
 */
@Controller
public class controller {
    @Autowired
    private AccountService accountService;//指向serviceImpl

    @RequestMapping( "/save")
    @ResponseBody
    public String save(Account a) throws IOException {
        accountService.save(a);

        return "success";
    }

    @RequestMapping("/findAll")
    public ModelAndView findAll() throws IOException {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("accountList",accountService.findAll());
        modelAndView.setViewName("accountList");

        return modelAndView;
    }
}

七、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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/tx
                           http://www.springframework.org/schema/tx/spring-tx.xsd
                           http://www.springframework.org/schema/aop
                           http://www.springframework.org/schema/aop/spring-aop.xsd
                           http://www.springframework.org/schema/context
                           http://www.springframework.org/schema/context/spring-context.xsd">
<!--Spring-->
    <!--组件扫描 注解相关-->
    <context:component-scan base-package="Service"/>
    <context:component-scan base-package="Mapper"/>


<!--整合Mybatis,将Session创建与事务管理交由Spring控制-->
    <!--加载propeties文件-->
    <context:property-placeholder location="classpath:jdbc.properties"/>

    <!--配置数据源信息-->
    <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${driverClass}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${user}"/>
        <property name="password" value="${password}"/>
    </bean>

    <!--配置sessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--数据源-->
        <property name="dataSource" ref="dataSource"></property>
        <!--别名-->
        <property name="typeAliasesPackage" value="Domain"/>
        <!--扫描mapper.xml-->
        <property name="mapperLocations" value="classpath*:Mapper/*.xml"/>
        <!--加载Mybatis配置文件-->
        <!--<property name="configLocation" value="classpath:SqlMapConfig-spring.xml"></property>-->
    </bean>

    <!--实例化mapper-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--value为xml文件所在包-->
        <property name="basePackage" value="Mapper"/>
    </bean>

    <!--注意:
        1.配置sessionFactory时,除数据源外的其他属性可在Mybatis配置文件中设置,但要加载Mybatis配置文件:
        2.如果Mapper.xml与Mapper.class在同一个包下且同名,spring扫描Mapper.class的同时
          会自动扫描同名的Mapper.xml并装配到Mapper.class;如果Mapper.xml与Mapper.class
          不在同一个包下或者不同名,就必须配置属性mapperLocations来指定mapper.xml的位置,此时
          spring通过识别mapper.xml的namespace来确定对应的Mapper.class。
    -->


    <!--声明式事务控制-->

    <!--平台事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!--配置事务增强-->
    <tx:advice id="txAdvice">
        <tx:attributes>
            <tx:method name="*"/>
        </tx:attributes>
    </tx:advice>

    <!--事务的aop织入-->
    <aop:config>
        <aop:advisor advice-ref="txAdvice" pointcut="execution(* Service.Impl.*.*(..))"/>
    </aop:config>

</beans>

八、SpringMVC配置文件

spring-mvc.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"
       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">

    <!--mvc注解驱动-->
    <mvc:annotation-driven>
        <!-- 转换字符编码,springmvc默认为ISO-8859-1 -->
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <constructor-arg value="#{T(java.nio.charset.Charset).forName('UTF-8')}"/>
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/plain;charset=UTF-8</value>
                        <value>text/html;charset=UTF-8</value>
                        <value>applicaiton/javascript;charset=UTF-8</value>
                    </list>
                </property>
                <property name="writeAcceptCharset"><value>false</value></property>
            </bean>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>application/json; charset=UTF-8</value>
                        <value>application/x-www-form-urlencoded; charset=UTF-8</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

    <!-- controller前端控制器扫描 -->
    <context:component-scan base-package="Control">
        <!-- 扫描带有Controller注解的类 -->
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!--内部资源视图解析器-->
    <bean id="resourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

    <!--开放静态资源访问权限-->
    <mvc:default-servlet-handler></mvc:default-servlet-handler>



    <!-- 配置文件上传解析器 -->
    <!--<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        &lt;!&ndash;字符集&ndash;&gt;
        <property name="defaultEncoding" value="UTF-8"/>
        &lt;!&ndash;文件大小/bit&ndash;&gt;
        <property name="maxUploadSize" value="500000"/>
    </bean>-->

    <!-- 配置拦截器 -->
    <!--<mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/IV"/>
            <bean class=""/>
        </mvc:interceptor>
    </mvc:interceptors>-->

    <!-- 配置异常处理器 -->
    <!--<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="defaultErrorView" value="/error.jsp"/>
        <property name="exceptionMappings">
            <map>
                <entry key="java.lang.ClassCastException" value="/error.jsp"/>
                <entry key="V_异常处理.异常.自定义异常" value="/error.jsp"/>
            </map>
        </property>
    </bean>-->

    <!--通过HandlerAdapter配置映射器,可用<mvc:annotation-driven>代替-->
    <!--<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="messageConverters">
            <list>
                <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
            </list>
        </property>
    </bean>-->

</beans>

九、Mybatis配置文件

Mapper/AccountMapper.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="Mapper.AccountMapper">
<!-- 编写映射文件 -->

    <!--保存-->
    <select id="save" parameterType="account">
        insert into account value (#{id},#{name},#{money})
    </select>

    <!--查询-->
    <select id="findAll" resultType="account">
        select * from account
    </select>

</mapper>

SqlMapConfig.xml:

经整合可省去。

十、其他配置文件

jdbc.properties

log4j.properties

原网站

版权声明
本文为[熙攘。]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_57389269/article/details/125646740