SSM整合

1、環(huán)境要求以及JAR包導(dǎo)入

環(huán)境要求

  1. jdk1.8
  2. maven3.6.1
  3. tomcat9
  4. mysql8

jar導(dǎo)入

<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.18</version>
    </dependency>
    <dependency>
        <groupId>com.mchange</groupId>
        <artifactId>c3p0</artifactId>
        <version>0.9.5.5</version>
    </dependency>

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>2.5</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>jsp-api</artifactId>
        <version>2.2</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.3</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>2.0.3</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.2.3.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.2.3.RELEASE</version>
    </dependency>
</dependencies>

其他設(shè)置

<!--2.資源過濾以及其他配置-->
    <build>
    <!--1,資源過濾-->
        <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>
    <!--相關(guān)插件導(dǎo)入 -->
        <!--設(shè)置編譯器,以及字節(jié)碼的版本-->
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

2、Dao層整合

步驟

  1. 在resources目錄下創(chuàng)建連接數(shù)據(jù)庫(kù)的外部配置文件db.properties

    jdbc.driver=com.mysql.cj.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost:3306/stx?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
    jdbc.username=root
    jdbc.password=root
    
  1. 在resources目錄下創(chuàng)建mybatis主配置文件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>
        <typeAliases>
            <package name="com.stx.pojo"/>
        </typeAliases>
        <mappers>
            <package name="com.stx.mapper"/>
        </mappers>
    </configuration>
    
  1. 在resources目錄下創(chuàng)建mybatis,mapper映射文件存放文件夾

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.lehu.dao.UserMapper">
        <select id="getAll" resultType="T_user">
            select * from t_user
        </select>
    </mapper>
    
  2. 在resources目錄下創(chuàng)建spring-dao.xml配置文件來整合dao層

    <?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
            https://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context
            https://www.springframework.org/schema/context/spring-context.xsd">
        <!-- 1.導(dǎo)入連接數(shù)據(jù)庫(kù)的配置文件-->
        <context:property-placeholder location="classpath:db.properties"/>
        <!--2.創(chuàng)建數(shù)據(jù)庫(kù)連接池對(duì)象-->
        <bean class="org.springframework.jdbc.datasource.DriverManagerDataSource"                    name="dataSource">
            <property name="driverClassName" value="${jdbc.driver}"/>
            <property name="url" value="${jdbc.url}"/>
            <property name="username" value="${jdbc.username}"/>
            <property name="password" value="${jdbc.password}"/>
        </bean>
        <!--3.獲取SqlSessionFactoryBean對(duì)象->
        <bean class="org.mybatis.spring.SqlSessionFactoryBean" name="sqlSessionFactory">
            <property name="dataSource" ref="dataSource"/>
            <property name="configLocation" value="classpath:mybatis-config.xml"/>
            <property name="mapperLocations" value="classpath:/mybatis/UserMapper.xml"/>
        </bean>
        <!--4.1.方法1:配置dao/mapper接口掃描包,動(dòng)態(tài)的實(shí)現(xiàn)Dao接口注入到spring容器中-->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" id="configurer">
            <!--注入SqlSessionFactory-->
            <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
            <!--掃描dao/mapper包-->
            <property name="basePackage" value="com.stx.dao"/>
        </bean>
        <!--4.2.方法2.使用SqlSessionTemplate-->
        <!--    <bean class="org.mybatis.spring.SqlSessionTemplate" name="SqlSession">-->
        <!--        <constructor-arg ref="sqlSessionFactory"/>-->
        <!--    </bean>-->
        <!--注冊(cè)使用SqlSessionTemplate完成相關(guān)操作的對(duì)象-->
        <!--    <bean class="..." id="mapper">-->
        <!--        <property name="sessionTemplate" ref="SqlSession"/>-->
        <!--    </bean>-->
    </beans>
    
  3. 在com.stx.pojo中創(chuàng)建對(duì)應(yīng)實(shí)體類

3、Service層整合

步驟

  1. 在com.stx.service分別編寫UserService接口以及對(duì)應(yīng)的實(shí)現(xiàn)類

    • 接口

      package com.stx.service;
      
      import com.stx.pojo.User;
      
      import java.util.List;
      @Service
      public interface UserService {
          List<User> getAll();
      }
      
    • 實(shí)現(xiàn)類

      package com.stx.service;
      
      import com.stx.pojo.User;
      
      import java.util.List;
      @Service
      public class UserServiceImp implements UserService {
          @Override
          public List<User> getAll() {
              return null;
          }
      }
      
  1. 在resources目錄下編寫spring-service.xml文件整合service層,將Service層對(duì)象交給spring容器托管

    <?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">
    
        <context:component-scan base-package="com.stx.service"/>
    </beans>
    
  2. 使用注解的方式將service層接口交給容器托管,需要在service層接口/類上加上@Service注解,接口實(shí)現(xiàn)類使用@Autowired注解引用Dao層對(duì)象

    package com.stx.service;
    
    import com.stx.dao.UserMapper;
    import com.stx.pojo.User;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import java.util.List;
    @Service
    public class UserServiceImp implements UserService {
        @Autowired
        UserMapper userMapper;
        @Override
        public List<User> getAll() {
            return userMapper.getAll();
        }
    
    }    
    

注意

  1. dao層引入對(duì)象創(chuàng)建失敗問題

    六月 17, 2020 4:56:10 下午 org.springframework.context.support.AbstractApplicationContext refresh
    警告: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userServiceImp': Unsatisfied dependency expressed through field 'userMapper'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.stx.dao.UserMapper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    

    這是因?yàn)閟ervice層對(duì)象使用@Autowired注解引用dao層對(duì)象時(shí),無法在spring-service.xml找到dao層對(duì)象實(shí)例,只需要將spring-dao.xml和spring-service關(guān)聯(lián)起來即可,在spring-service.xml中使用<import resource="spring-dao.xml"/>引入spring-dao.xml的所有配置信息。

4、Controller層整合

步驟

  1. 創(chuàng)建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: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.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    
        <!--1.導(dǎo)入mvc獨(dú)用的注解驅(qū)動(dòng),不用導(dǎo)入普通的<context:annotation-config/>-->
        <mvc:annotation-driven>
            <mvc:message-converters>
                <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                    <constructor-arg value="UTF-8"/>
                </bean>
                <!--設(shè)置使用Jackson方式來轉(zhuǎn)換json格式,使用前提是必須導(dǎo)入Jackson這個(gè)依賴-->
    <!--            <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>
        <!--2.對(duì)靜態(tài)的資源進(jìn)行過濾-->
        <mvc:default-servlet-handler/>
        <!--3.掃描進(jìn)行注解配置裝配的包-->
        <context:component-scan base-package="com.stx.controller"/>
        <!--4.導(dǎo)入視圖解析器-->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
            <property name="prefix" value="/WEB-INF/jsp/"/>
            <property name="suffix" value=".jsp"/>
        </bean>
            <!--配置文件類型解析器-->
        <bean id="multipartResolver"             class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
            <property name="maxInMemorySize" value="10485760"/>
        </bean>
    </beans>
    
  1. 將所有的spring配置文件整合到applicaitonContex.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"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
        <import resource="spring-dao.xml"/>
        <import resource="spring-service.xml"/>
        <import resource="spring-mvc.xml"/>
    </beans>
    
  1. 在web.xml中配置前端控制器DispatcherServlet

    <?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">
        <!--0.配置applicationContext上下文加載監(jiān)聽器-->
        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext.xml</param-value>
        </context-param>
        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>
        <!--1.配置DisPatcherServlet分發(fā)器-->
        <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:spring-mvc.xml</param-value>
            </init-param>
            <load-on-startup>1</load-on-startup>
        </servlet>
        <servlet-mapping>
            <servlet-name>springmvc</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
        <!--2.設(shè)置過濾器:解決亂碼問題-->
        <filter>
            <filter-name>encodingFilter</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>encodingFilter</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
        <!--配置Session過期時(shí)間-->
        <session-config>
            <session-timeout>14</session-timeout>
        </session-config>
    </web-app>
    
  2. 編寫相關(guān)Controller實(shí)現(xiàn)類

    package com.stx.controller;
    
    import com.stx.service.UserService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    public class Test01 {
        @Autowired
        UserService userService;
        @RequestMapping("/hi")
        String h1() {
            return "hello 雙體系";
        }
        @RequestMapping("/getusers")
        String getUsers() {
            return userService.getAll().toString();
        }
    }
    
  1. 配置tomcat
  1. 運(yùn)行測(cè)試

注意

  1. 必須在spring-mvc.xml配置文件中加入以下內(nèi)容,因?yàn)閟pring默認(rèn)的消息轉(zhuǎn)換器的默認(rèn)編碼標(biāo)準(zhǔn)是ISO-8859-1,該編碼是西歐編碼,無法對(duì)中文編碼

        <mvc:annotation-driven>
            <mvc:message-converters>
                <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                    <constructor-arg value="UTF-8"/>
                </bean>
            </mvc:message-converters>
        </mvc:annotation-driven>
    
  1. 關(guān)于在IDEA中jar包無法導(dǎo)入到web項(xiàng)目中問題解決

    自行百度

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容