SSM框架整合開發

風之詩理工發表於2020-12-23

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的大致框架

在這裡插入圖片描述

  • 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

在這裡插入圖片描述

<?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。在上一步基礎上,加入下面目錄結構。

在這裡插入圖片描述

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

在這裡插入圖片描述

  • 在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框架整合完畢,進行測試無誤後,就可以開始進行專案設計了。

相關文章