整合SSM

SSM整合

整合思路

  • 各自搭建SSM環(huán)境
  • 使用Spring整合Mybatis
  • 使用Spring整合SpringMVC

搭建Mybatis環(huán)境

創(chuàng)建工程

Maven項(xiàng)目-web工程

引入mybatis坐標(biāo)

<dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.0</version>
        </dependency>
<!--        輔助-->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.12</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

創(chuàng)建pojo

public class Account {
    private Integer aid;
    private String name;
    private Float balance;

    @Override
    public String toString() {
        return "Account{" +
                "aid=" + aid +
                ", name='" + name + '\'' +
                ", balance=" + balance +
                '}';
    }

    public Integer getAid() {
        return aid;
    }

    public void setAid(Integer aid) {
        this.aid = aid;
    }

    public String getName() {
        return name;
    }

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

    public Float getBalance() {
        return balance;
    }

    public void setBalance(Float balance) {
        this.balance = balance;
    }
}

創(chuàng)建接口IAccountDao

public interface IAccountDao {
    List<Account> findAll();
}

創(chuàng)建dao映射文件sql

<mapper namespace="com.itheima.dao.IAccountDao">
    <select id="findAll" resultType="account">
        SELECT * FROM tb_account;
    </select>
</mapper>

加入主配置文件

mybatis-config.xml

<configuration>
    <!--    引入數(shù)據(jù)庫外部配置文件-->
    <properties resource="db.properties"/>
    <!--    引入別名-->
    <typeAliases>
        <package name="com.itheima.domain"/>
    </typeAliases>
    <environments default="dev">
        <environment id="dev">
            <transactionManager type="JDBC"/>

            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.user}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <package name="com.itheima.dao"/>
    </mappers>
</configuration>
  • db.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///spring_lsn
jdbc.user=root
jdbc.password=xml123xml
  • 測試
 @Test
    public void testAccountDao() {
        //讀取配置文件
        try {
            InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
            SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            SqlSession sqlSession = sessionFactory.openSession();
            IAccountDao accountDao = sqlSession.getMapper(IAccountDao.class);
            List<Account> accounts = accountDao.findAll();
            accounts.stream().forEach(account -> System.out.println(account));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

搭建Spring的環(huán)境

  • 創(chuàng)建IAccountService
public interface IAccountService {
    
    List<Account> findAll();
}
  • 創(chuàng)建IAccountServiceImpl實(shí)現(xiàn)類
public class AccountService implements IAccountService {
    @Autowired
    private IAccountDao accountDao;
    
    @Override
    public List<Account> findAll() {
        return accountDao.findAll();
    }
}
  • 測試
 @Override
    public List<Account> findAll() {
        System.out.println("findAll");
        return null;
//        return accountDao.findAll();
    }

搭建SpringMVC環(huán)境

  • 引入坐標(biāo)
<!--springMVC 相關(guān)-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.1.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
  • 加入springmvc的配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://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/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">

    <!--        配置注解掃描-->
    <context:component-scan base-package="com.itheima.controller"/>
    <!--    配置三大組件-->
    <mvc:annotation-driven/>
    <!--    配置視圖解析器-->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>
  • 加入web配置文件
<?xml version="1.0" encoding="utf-8"?>
<web-app version="3.0"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
        http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <!--    配置前端適配器-->
    <servlet>
        <servlet-name>dispatcherServlet</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>
    </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>
    </filter>
    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>
  • 請(qǐng)求頁面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<a href="${pageContext.request.contextPath}/account/list">賬戶列表</a>
</body>
</html>
  • 控制器
/**
 * @author wangxin
 * @date 2019/12/15 16:48
 * @description: TODO
 * GOOD LUCK!
 */
@Controller
public class AccountController {
    @RequestMapping("/account/list")
    public String list(Model model) {
        model.addAttribute("list", "list");
        return "list";
    }

}
  • 響應(yīng)頁面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
${list}
</body>
</html>

Spring整合Mybatis

整合思路

將Mybatis的SqlSessionFactory托管到Spring的IOC容器中

將mybatis的所有配置信息轉(zhuǎn)移到Spring的配置文件中

mybatis提供一個(gè)對(duì)接spring的中間包

加入整合包

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

將mybatis的所有配置文件轉(zhuǎn)移到spring的配置文件中

<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 http://www.springframework.org/schema/context/spring-context.xsd">
    <!--    注解掃描-->
    <context:component-scan base-package="com.itheima.service"/>
    <!--    引入外部配置-->
    <context:property-placeholder location="classpath:db.properties"/>
    <!--    數(shù)據(jù)源-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.user}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
    <!--    配置事務(wù)管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!--    配置sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="typeAliasesPackage" value="com.itheima.domain"/>
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>
    <!--    引入mapper的配置文件-->
    <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.itheima.dao"/>
    </bean>
</beans>
  • 將dao注入到Service
@Service
public class AccountServiceImpl implements IAccountService {
    @Autowired
    private IAccountDao accountDao;

    @Override
    public List<Account> findAll() {
        List<Account> accounts = accountDao.findAll();
        System.out.println(accounts);
        return null;
//        return accountDao.findAll();
    }
}

Spring整合SpringMVC

Spring和SpringMVC是同一家產(chǎn)品,是不需要整合的

但是現(xiàn)在的Spring容器自己無法啟動(dòng),我們需要在啟動(dòng)Web容器的時(shí)候加載Spring的配置文件倚喂,啟動(dòng)Spring容器那么這個(gè)工作是在spring-web包中監(jiān)聽器來做的斋泄,這個(gè)包不用單獨(dú)導(dǎo)入杯瞻,他已經(jīng)在Spring-webmvc包中了,它會(huì)監(jiān)聽WEB容器的啟動(dòng)和停止炫掐,然后就可以控制Spring容器的啟動(dòng)和停止了

  • 配置監(jiān)聽器
<listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
  • 向SpringMVC中注入service
@Service
public class AccountServiceImpl implements IAccountService {
    @Autowired
    private IAccountDao accountDao;

    @Override
    public List<Account> findAll() {
        List<Account> accounts = accountDao.findAll();
        System.out.println(accounts);
        return null;
//        return accountDao.findAll();
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末魁莉,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子募胃,更是在濱河造成了極大的恐慌旗唁,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,427評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件痹束,死亡現(xiàn)場離奇詭異检疫,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)祷嘶,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,551評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門屎媳,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人论巍,你說我怎么就攤上這事烛谊。” “怎么了嘉汰?”我有些...
    開封第一講書人閱讀 165,747評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵丹禀,是天一觀的道長。 經(jīng)常有香客問我鞋怀,道長双泪,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,939評(píng)論 1 295
  • 正文 為了忘掉前任密似,我火速辦了婚禮焙矛,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘残腌。我一直安慰自己薄扁,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,955評(píng)論 6 392
  • 文/花漫 我一把揭開白布废累。 她就那樣靜靜地躺著,像睡著了一般脱盲。 火紅的嫁衣襯著肌膚如雪邑滨。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,737評(píng)論 1 305
  • 那天钱反,我揣著相機(jī)與錄音掖看,去河邊找鬼匣距。 笑死,一個(gè)胖子當(dāng)著我的面吹牛哎壳,可吹牛的內(nèi)容都是我干的毅待。 我是一名探鬼主播,決...
    沈念sama閱讀 40,448評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼归榕,長吁一口氣:“原來是場噩夢(mèng)啊……” “哼尸红!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起刹泄,我...
    開封第一講書人閱讀 39,352評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤外里,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后特石,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體盅蝗,經(jīng)...
    沈念sama閱讀 45,834評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,992評(píng)論 3 338
  • 正文 我和宋清朗相戀三年姆蘸,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了墩莫。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,133評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡逞敷,死狀恐怖狂秦,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情兰粉,我是刑警寧澤故痊,帶...
    沈念sama閱讀 35,815評(píng)論 5 346
  • 正文 年R本政府宣布,位于F島的核電站玖姑,受9級(jí)特大地震影響愕秫,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜焰络,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,477評(píng)論 3 331
  • 文/蒙蒙 一戴甩、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧闪彼,春花似錦甜孤、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,022評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至描馅,卻和暖如春把夸,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背铭污。 一陣腳步聲響...
    開封第一講書人閱讀 33,147評(píng)論 1 272
  • 我被黑心中介騙來泰國打工恋日, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留膀篮,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,398評(píng)論 3 373
  • 正文 我出身青樓岂膳,卻偏偏與公主長得像誓竿,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子谈截,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,077評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容