App下載

從零開始 詳細(xì)介紹SSM框架的搭建過程

超甜的布丁 2021-08-13 14:30:41 瀏覽數(shù) (3839)
反饋

第一章:搭建整合環(huán)境

1. 搭建整合環(huán)境

整合說明:SSM整合可以使用多種方式,咱們會(huì)選擇XML + 注解的方式
整合的思路
2.1. 先搭建整合的環(huán)境
2.2. 先把Spring的配置搭建完成
2.3. 再使用Spring整合SpringMVC框架
2.4. 最后使用Spring整合MyBatis框架
創(chuàng)建數(shù)據(jù)庫和表結(jié)構(gòu)
3.1創(chuàng)建數(shù)據(jù)庫

create database ssm;
create table account(
id int primary key auto_increment,
name varchar(20),
money double
);

4.創(chuàng)建maven工程

<properties>
  <spring.version>5.0.2.RELEASE</spring.version>
  <slf4j.version>1.6.6</slf4j.version>
  <log4j.version>1.2.12</log4j.version>
  <mysql.version>5.1.6</mysql.version>
  <mybatis.version>3.4.5</mybatis.version>
</properties>
<dependencies>
  <!--spring-->
  <dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.6.8</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aop</artifactId>
    <version>${spring.version}</version>
  </dependency><dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-context</artifactId>
  <version>${spring.version}</version>
</dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>${spring.version}</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>${spring.version}</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>${spring.version}</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
    <version>${spring.version}</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>${spring.version}</version>
  </dependency>
  <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
  </dependency>
  <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>${mysql.version}</version>
  </dependency>
  <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>servlet-api</artifactId>
    <version>2.5</version>
    <scope>provided</scope>
  </dependency>
  <dependency>
    <groupId>javax.servlet.jsp</groupId>
    <artifactId>jsp-api</artifactId>
    <version>2.0</version>
    <scope>provided</scope>
  </dependency>
  <dependency>
    <groupId>jstl</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
  </dependency>
  <!--log start-->
  <dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>${log4j.version}</version>
  </dependency>
  <dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>${slf4j.version}</version>
  </dependency>
  <dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>${slf4j.version}</version>
  </dependency>
 <!-- log end-->
  <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>${mybatis.version}</version>
  </dependency>
  <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>1.3.0</version>
  </dependency>
  <!--連接池-->
  <dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.10</version></dependency>
</dependencies>
<build>
  <finalName>ssm</finalName>
  <pluginManagement>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.2</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
          <encoding>UTF-8</encoding>
          <showWarnings>true</showWarnings>
        </configuration>
      </plugin>
    </plugins>
  </pluginManagement>
</build>

編寫實(shí)體類,在ssm_domain項(xiàng)目中編寫

package com.qcby.entity;

import java.io.Serializable;

public class Account implements Serializable {
    // 主鍵
    private int id;
    // 賬戶名稱
    private String name;
    // 賬號(hào)的金額
    private Double money;

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public Double getMoney() {
        return money;
    }

    public void setMoney(Double money) {
        this.money = money;
    }

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

編寫service接口和實(shí)現(xiàn)類

package com.qcby.service;

import com.qcby.entity.Account;
import java.util.List;

public interface AccountService {

    //查詢所有
    public List<Account> findAll();
}


package com.qcby.service;

import com.qcby.entity.Account;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class AccountServiceImpl implements AccountService {
    //查詢所有
    @Override
    public List<Account> findAll() {
        System.out.println("業(yè)務(wù)層:查詢所有");
        return null;
    }
}

第二章:Spring框架代碼的編寫

1. 搭建和測(cè)試Spring的開發(fā)環(huán)境

在ssm_web項(xiàng)目中創(chuàng)建spring.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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
    <!--開啟注解掃描,要掃描的是service-->
    <context:component-scan base-package="com.qcby.service"/>
</beans>

在ssm_web項(xiàng)目中編寫測(cè)試方法,進(jìn)行測(cè)試

package com.qcby.demo;

import com.qcby.service.AccountService;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestSpring {
    @Test
    public void run(){
        ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("classpath:spring.xml");
        AccountService service = ac.getBean(AccountService.class);
        service.findAll();
    }
}

第三章:Spring整合SpringMVC框架

1. 搭建和測(cè)試SpringMVC的開發(fā)環(huán)境

在web.xml中配置DispatcherServlet前端控制器

<!--配置前端控制器-->
<servlet>
  <servlet-name>DispatcherServlet</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <!--加載springmvc.xml配置文件-->
  <init-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:springmvc.xml</param-value>
  </init-param>
 <!-- 啟動(dòng)加載-->
  <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
  <servlet-name>DispatcherServlet</servlet-name>
  <url-pattern>/</url-pattern>
</servlet-mapping>

在web.xml中配置DispatcherServlet過濾器解決中文亂碼

<!--解決post請(qǐng)求中文亂碼的過濾器-->
<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>

創(chuàng)建springmvc.xml的配置文件,編寫配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       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
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
    <!--掃描controller的注解,別的不掃描-->
    <context:component-scan base-package="com.qcby.controller"/>
   <!-- 配置視圖解析器-->
    <bean id="ViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--JSP文件所在的目錄-->
        <property name="prefix" value="/pages/"/>
        <!--文件的后綴名-->
        <property name="suffix" value=".jsp"/>
    </bean>
    <!--設(shè)置靜態(tài)資源不過濾-->
    <mvc:resources mapping="/source/css/**" location="/source/css/"/>
    <mvc:resources mapping="/source/js/**" location="/source/js/"/>
    <mvc:resources mapping="/source/images/**" location="/source/images/"/>

    <!--開啟springmvc-->
    <mvc:annotation-driven/>
</beans>

測(cè)試SpringMVC的框架搭建是否成功

4.1. 編寫index.jsp和list.jsp編寫,超鏈接

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <a href="/account/findAll" rel="external nofollow" rel="external nofollow" >查詢所有</a>
</body>
</html>

4.2. 創(chuàng)建AccountController類,編寫方法,進(jìn)行測(cè)試

package com.qcby.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/account")
public class AccountController {
    /**
     * 查詢所有
     * @return
     */
    @RequestMapping("/findAll")
    public ModelAndView findAll(){
        System.out.println("表現(xiàn)層:查詢所有");
        ModelAndView mv = new ModelAndView();
        mv.setViewName("suc");
        return mv;
    }
}

2. Spring整合SpringMVC的框架

目的:在controller中能成功的調(diào)用service對(duì)象中的方法。

在項(xiàng)目啟動(dòng)的時(shí)候,就去加載spring.xml的配置文件,在web.xml中配置
ContextLoaderListener監(jiān)聽器(該監(jiān)聽器只能加載WEB-INF目錄下的applicationContext.xml的配置文
件,所以要配置全局的變量加載類路徑下的配置文件)。

<!--配置Spring的監(jiān)聽器-->
<display-name>Archetype Created Web Application</display-name>
<listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--配置加載類路徑的配置文件-->
<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:spring.xml</param-value>
</context-param>

在controller中注入service對(duì)象,調(diào)用service對(duì)象的方法進(jìn)行測(cè)試

package com.qcby.controller;

import com.qcby.entity.Account;
import com.qcby.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.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("/account")
public class AccountController {
    //依賴注入
    @Autowired
    private AccountService accountService;
    /**
     * 查詢所有
     * @return
     */
    @RequestMapping("/findAll")
    public ModelAndView findAll(){
        System.out.println("表現(xiàn)層:查詢所有");
        //調(diào)用service的方法
        List<Account> list = accountService.findAll();
        ModelAndView mv = new ModelAndView();
        mv.setViewName("suc");
        return mv;
    }
}

第四章:Spring整合MyBatis框架

1. 搭建和測(cè)試MyBatis的環(huán)境

在web項(xiàng)目中編寫SqlMapConfig.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>

    <properties resource="jdbc.properties"></properties>
    <!--定義別名-->
    <typeAliases>
        <!--把com.qcby.entity.User使用user別名來顯示,別名user User USER都可以,默認(rèn)是忽略大寫的-->
        <!--<typeAlias type="com.qcby.entity.User" alias="user"/>-->

        <!--針對(duì)com.qcby.entity包下的所有的類,都可以使用當(dāng)前的類名做為別名-->
        <package name="com.qcby.entity"/>
    </typeAliases>

    <environments default="mysql">
        <environment id="mysql">
            <!--配置事務(wù)的類型,使用本地事務(wù)策略-->
            <transactionManager type="JDBC"></transactionManager>
            <!--是否使用連接池 POOLED表示使用鏈接池,UNPOOLED表示不使用連接池-->
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="mapper/AccountDao.xml"></mapper>
    </mappers>
</configuration>

AccountDao接口

package com.qcby.dao;

import com.qcby.entity.Account;

import java.util.List;

public interface AccountDao {
    //查詢所有
    public List<Account> findAll();
}

編寫AccountDao.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="com.qcby.dao.AccountDao">
    <select id="findAll" resultType="account">
        select * from account
    </select>
</mapper>

編寫測(cè)試的方法

package com.qcby.demo;

import com.qcby.dao.AccountDao;
import com.qcby.entity.Account;
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.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class TestMybatis {
    @Test
    public void run() throws IOException {
        InputStream in = Resources.getResourceAsStream("mybatis.xml");
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        SqlSession session = factory.openSession();
        AccountDao mapper = session.getMapper(AccountDao.class);
        List<Account> list = mapper.findAll();
        for (Account account : list) {
            System.out.println(account);
        }
        //關(guān)閉資源
        session.close();
        in.close();
    }
}

2. Spring整合MyBatis框架

目的:把SqlMapConfig.xml配置文件中的內(nèi)容配置到applicationContext.xml配置文件中
在service中注入dao對(duì)象,進(jìn)行測(cè)試

<?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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
   <!-- 加載數(shù)據(jù)庫配置屬性文件-->
    <context:property-placeholder location="classpath:jdbc.properties"/>
    <!--開啟注解掃描,要掃描的是service-->
    <context:component-scan base-package="com.qcby.service"/>
    <!--配置數(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.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
    <!--Spring整合MyBatis框架,SqlSessionFactoryBean創(chuàng)建工廠對(duì)象-->
    <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 注入數(shù)據(jù)庫連接池 -->
        <property name="dataSource" ref="dataSource"/>
        <!-- 掃描entity包 使用別名 -->
        <property name="typeAliasesPackage" value="com.qcby.entity" />
        <!-- 掃描sql配置文件:mapper需要的xml文件 -->
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
    </bean>
    <!--配置掃描Dao接口包,動(dòng)態(tài)實(shí)現(xiàn)Dao接口,注入到ioc容器中-->
    <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.qcby.dao"/>
    </bean>

</beans>

service代碼如下

package com.qcby.service;

import com.qcby.dao.AccountDao;
import com.qcby.entity.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class AccountServiceImpl implements AccountService {
    @Autowired
    private AccountDao accountDao;
    //查詢所有
    @Override
    public List<Account> findAll() {
        System.out.println("業(yè)務(wù)層:查詢所有");
        List<Account> list = accountDao.findAll();
        return list;
    }
}

controller代碼如下

package com.qcby.controller;

import com.qcby.entity.Account;
import com.qcby.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.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("/account")
public class AccountController {
    //依賴注入
    @Autowired
    private AccountService accountService;
    /**
     * 查詢所有
     * @return
     */
    @RequestMapping("/findAll")
    public ModelAndView findAll(){
        System.out.println("表現(xiàn)層:查詢所有");
        //調(diào)用service的方法
        List<Account> list = accountService.findAll();
        for (Account account : list) {
            System.out.println(account);
        }
        ModelAndView mv = new ModelAndView();
        mv.setViewName("suc");
        return mv;
    }
}

spring.xml配置聲明式事務(wù)管理

<!-- 配置聲明式事務(wù)管理-->
 <!--平臺(tái)事務(wù)管理器-->
 <bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
     <property name="dataSource" ref="dataSource"/>
 </bean>
 <!--配置事務(wù)的通知-->
 <tx:advice id="txAdvice" transaction-manager="dataSourceTransactionManager">
     <tx:attributes>
         <tx:method name="find*" read-only="true"/>
         <tx:method name="*" />
     </tx:attributes>
 </tx:advice>
 <!--配置事務(wù)的增強(qiáng)-->
 <aop:config>
     <aop:advisor advice-ref="txAdvice" pointcut="execution(public * com.qcby.service.*ServiceImpl.*(..))"/>
 </aop:config>

表單代碼

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <a href="/account/findAll" rel="external nofollow" rel="external nofollow" >查詢所有</a>
    <form action="/account/save" method="post">
        姓名:<input type="text" name="name" /><br/>
        金額:<input type="text" name="money" /><br/>
        <input type="submit" value="保存" />
    </form>
</body>
</html>

controller代碼

package com.qcby.controller;

import com.qcby.entity.Account;
import com.qcby.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.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("/account")
public class AccountController {
    //依賴注入
    @Autowired
    private AccountService accountService;
    /**
     * 查詢所有
     * @return
     */
    @RequestMapping("/findAll")
    public ModelAndView findAll(){
        System.out.println("表現(xiàn)層:查詢所有");
        //調(diào)用service的方法
        List<Account> list = accountService.findAll();
        for (Account account : list) {
            System.out.println(account);
        }
        ModelAndView mv = new ModelAndView();
        mv.setViewName("suc");
        return mv;
    }

    @RequestMapping("/save")
    public String save(Account account){
        //Service的保存方法
        accountService.save(account);
        return "suc";
    }
}

service接口和實(shí)現(xiàn)類代碼

package com.qcby.service;

import com.qcby.entity.Account;
import java.util.List;

public interface AccountService {

    //查詢所有
    public List<Account> findAll();
    
    //保存
    void save(Account account);
}
package com.qcby.service;

import com.qcby.dao.AccountDao;
import com.qcby.entity.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class AccountServiceImpl implements AccountService {
    @Autowired
    private AccountDao accountDao;
    //查詢所有
    @Override
    public List<Account> findAll() {
        System.out.println("業(yè)務(wù)層:查詢所有");
        List<Account> list = accountDao.findAll();
        return list;
    }

    @Override
    public void save(Account account) {
        accountDao.save(account);
    }
}

dao代碼

package com.qcby.dao;

import com.qcby.entity.Account;

import java.util.List;

public interface AccountDao {
    //查詢所有
    public List<Account> findAll();
    //保存
    void save(Account account);
}

dao.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="com.qcby.dao.AccountDao">
    <select id="findAll" resultType="account">
        select * from account
    </select>
    <insert id="save" parameterType="account">
        insert into account (name,money) values(#{name},#{money})
    </insert>
</mapper>

那么,關(guān)于SSM框架從零開始搭建的一個(gè)詳細(xì)過程介紹的文章就到此結(jié)束了,如果您對(duì)SSM框架的知識(shí)想要了解更多的內(nèi)容,請(qǐng)多多關(guān)注W3Cschool相關(guān)內(nèi)容的文章,也希望大家可以多多支持!


0 人點(diǎn)贊