SSM框架整合开发

SSM框架整合开发

前言

  • 学完了SSM框架,准备做一个SSM项目练练手,结果以来就被SSM框架整合坑到了,各种报错,搭建不成功,花了两天,看了N个视频,总算搭建出一个能用的。也算是对SSM的一个总结和回顾。

    实验环境

    JDK 13.0.2

    MySQL 8.0…22

    IDEA 2020.1.1

    Maven 3.6.3

    Tomcat 9.0.30

1、创建一个测试表

CREATE TABLE `books` (
  `bookID` int NOT NULL AUTO_INCREMENT COMMENT '书id',
  `bookName` varchar(100) NOT NULL COMMENT '书名',
  `bookPage` int NOT NULL COMMENT '页数',
  `detail` varchar(200) NOT NULL COMMENT '描述',
  KEY `bookID` (`bookID`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

2、pom文件添加依赖

  • 这里也只是一些比较基本的依赖,项目开始,后面可能还会加log4j依赖,jackson依赖等。
<?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.lwl</groupId>
  <artifactId>SSM2-project</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

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

  <dependencies>
    <!--SpringMVC-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.2.8.RELEASE</version>
    </dependency>

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

    <!--Spring JDBC-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>5.2.8.RELEASE</version>
    </dependency>

    <!--Spring AOP-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>5.2.8.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aspects</artifactId>
      <version>5.2.8.RELEASE</version>
    </dependency>

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

    <!--MyBatis整合Spring-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.1</version>
    </dependency>

    <!--MySQL驱动-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.22</version>
    </dependency>

    <!--C3P0-->
    <dependency>
      <groupId>com.mchange</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.5.4</version>
    </dependency>

    <!--JSTL-->
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>

    <!--ServletAPI-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
    </dependency>

    <!--lombok插件-->
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>1.18.16</version>
    </dependency>

    <!--单元测试-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>


  </dependencies>

  <!--确保配置文件能够被扫描到-->
  <build>
    <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>

3、项目整体结构(初步)

先构建好Spring的大致框架

SSM框架整合开发

  • controller 控制层,调用service层,并与前端进行交互。
  • dao (也可以写作repository) 数据持久层,与数据库进行交互。
  • domain(pojo,entity)用来存放实体类,一个表对应一个实体类。
  • service 业务层,调用dao层,进行业务处理的地方。

3.1实体类(domain)

采用了lombok插件,用注解的方式代替了set,get,tostring等大量重复代码。

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Book {
    private Integer bookID;
    private String bookName;
    private Integer bookPage;
    private String detail;
}

3.2数据持久层(dao)

@Repository//把这个类交给IOC容器去托管
public interface BookMapper {
    //添加书籍
    void saveBook(Book book);

    //查询书籍
    List<Book> findAll();

}

BookMapper.xml文件,这里有可能(版本不同可能会有影响,建议先不改,SQL语句提示有问题再改)需要在idea中添加数据库连接,然后选择对应的表,最后编写SQL语句时,在表前面加上数据库名。例如:

select name from library.user

SSM框架整合开发

<?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.lwl.dao.BookMapper">
    <insert id="saveBook" parameterType="com.lwl.domain.Book">
        insert into ssmbuild.books(bookID,bookName,bookPage,detail)
        values(#{bookID},#{bookName},#{bookPage},#{detail})
    </insert>

    <select id="findAll" resultType="com.lwl.domain.Book">
        select * from ssmbuild.books
    </select>
</mapper>

3.3业务层(service)

先写一个mapper对应的接口,里面的方法和mapper里的方法一样,直接复制粘贴就行。

public interface BookService {
    //添加书籍
    void saveBook(Book book);

    //查询书籍
    List<Book> findAll();
}

然后在service里建一个Impl包,写一个service的实现类

@Service("bookService")//把Service注解的这个类交给spring的ioc去管理
public class BookServiceImpl implements BookService {

    private BookMapper bookMapper;

    @Autowired//把Mapper注入到这个类
    public BookServiceImpl(BookMapper bookMapper) {
        this.bookMapper = bookMapper;
    }

    @Override
    public void saveBook(Book book) {
        System.out.println("添加书籍");
        bookMapper.saveBook(book);
    }

    @Override
    public List<Book> findAll() {
        System.out.println("查找所有书籍");
        return bookMapper.findAll();
    }
}

3.4创建spring配置文件

在resources目录下建一个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: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/context https://www.springframework.org/schema/context/spring-context.xsd">

    <!--开启注解扫描,Spring只处理service和dao层,controller层由SpringMVC框架去处理-->
    <context:component-scan base-package="com.lwl"><!--扫描这个包及子包下的所有注解-->
        <!--过滤掉Controller这个注解-->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
</beans>

3.5编写一个SpringTest类

能正常调用findAll方法则说明applicationContext.xml文件配置正确,spring框架搭建好了

public class SpringTest {
    @Test
    public void test(){
        //加载Spring配置文件
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        //获取对象
        BookService bookService = (BookService) applicationContext.getBean("bookService");
        //调用方法
        bookService.findAll();//输出查找所有书籍
    }
}

4、Spring整合SpringMVC

先搭建好SpringMVC的大致框架,在进行Spring整合SpringMVC。在上一步基础上,加入下面目录结构。

SSM框架整合开发

4.1配置web.xml

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>

  <!--配置前端控制器-->
  <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!--加载spring.xml配置文件-->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <!--启动服务器,创建该servlet-->
    <load-on-startup>1</load-on-startup><!---->
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

  <!--解决中文乱码的过滤器-->
  <filter>
    <filter-name>characterEncodingFilter</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>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

</web-app>

这里<web-app>会有下划线提醒,原因是里面标签顺序不对,不影响使用。若想改正,按照下面的的顺序将

<web-app>里面的标签排下序即可。

The content of element type “web-app” must match “(icon?,display-name?,description?,distributable?,context-param*,filter*,filter-mapping*,listener*,servlet*,servlet-mapping*,session-config?,mime-mapping*,welcome-file-list?,error-page*,taglib*,resource-env-ref*,resource-ref*,security-constraint*,login-config?,security-role*,env-entry*,ejb-ref*,ejb-local-ref*)”.

4.2配置springmvc.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:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-3.0.xsd
            http://www.springframework.org/schema/mvc
            http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <!--开启注解扫描-->
    <context:component-scan base-package="com.lwl">
        <!--只扫描Controller注解-->
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

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

    <!--过滤静态资源-->
    <mvc:resources location="/css/" mapping="/css/**" />
    <mvc:resources location="/imgs/" mapping="/imgs/**" />
    <mvc:resources location="/js/" mapping="/js/**" />

    <!--开启SpringMVC注解的支持-->
    <mvc:annotation-driven/>

</beans>

4.3编写controller来测试环境是否搭建成功

@Controller
@RequestMapping("/book")
public class BookController {


    private BookService bookService;

    @Autowired
    public BookController(BookService bookService) {
        this.bookService = bookService;
    }

    @RequestMapping("/findAll")
    public String findAll(Model model){
        System.out.println("表现层,查询所有书籍");
        List<Book> books = bookService.findAll();
        model.addAttribute("books",books);
        return "books";
    }
    @PostMapping("/save")
    public void save(Book book, HttpServletRequest request, HttpServletResponse response) throws IOException {
        bookService.saveBook(book);
        //进行添加书籍操作之后,自动查出所有书籍信息
        response.sendRedirect(request.getContextPath() + "/book/findAll");
    }
}

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h3>已查出所有图书信息</h3>
    ${books}

</body>
</html>

浏览器输入http://localhost:8080/book/findAll,得到信息已查出所有图书信息证明SpringMVC环境搭建成功。

4.4Spring整合SpringMVC

SSM框架整合开发

  • 在web.xml文件中加入如下配置
<!--配置Spring的监听器,默认只加载WEB-INF目录下的applicationContext.xml配置文件-->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
  <!--设置监听器需要加载的配置文件的路径-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  • 测试controller
@Controller
@RequestMapping("/book")
public class BookController {


    private BookService bookService;
    
    @Autowired//不建议直接注入
    public BookController(BookService bookService) {
        this.bookService = bookService;
    }

    @RequestMapping("/findAll")
    public String findAll(){
        System.out.println("查询所有书籍");//查询所有书籍
        bookService.findAll();//查询所有书籍
        return "books";
    }
}

5、Spring整合MyBatis框架

配置文件

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useUnicode=true;characterEncoding=UTF-8
jdbc.username=root
jdbc.password=****

applicationContext.xml添加mybatis相关配置

<?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"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:jdbc="http://www.springframework.org/schema/jdbc"
       xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.1.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">

    <!--开启注解扫描,Spring只处理service和dao层,controller层由SpringMVC框架去处理-->
    <context:component-scan base-package="com.lwl"><!--扫描这个包及子包下的所有注解-->
        <!--过滤掉Controller这个注解-->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!--Spring整合MyBatis框架-->

    <!--1.关联数据库配置文件-->
    <context:property-placeholder location="classpath:db.properties"/>

    <!--2.配置连接池-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!--配置连接池属性,使用了EL表达式-->
        <property name="driverClass" value="${jdbc.driver}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
     </bean>

    <!--3.配置SqlSessionFactory工厂-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/><!--引入上面的连接池-->

    </bean>

    <!--4.配置AccountDao接口所在包-->
    <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--要扫描的dao包-->
        <property name="basePackage" value="com.lwl.dao"/>
    </bean>

    <!--配置Spring框架声明时事务管理-->
    <!--配置事务管理器-->
    <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="find*" read-only="true"/><!--find开头的方法为只读属性-->
            <tx:method name="*" isolation="DEFAULT"/><!--其他方法JDBC默认属性-->
        </tx:attributes>
    </tx:advice>

    <!--配置AOP增强-->
    <aop:config>
        <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.lwl.service.Impl.*ServiceImpl.*(..))"/>
    </aop:config>
</beans>

到此SSM框架整合完毕,进行测试无误后,就可以开始进行项目设计了。

上一篇:【Python基础】Python正则表达式入门到入魔


下一篇:ios 监听app从后台恢复到前台