文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

从零开始SSM搭建步骤(图文)

2024-04-02 19:55

关注

本文介绍了从零开始SSM搭建步骤,分享给大家,有助于更好的搭建ssm,具体如下:

第一章:搭建整合环境

1. 搭建整合环境

整合说明:SSM整合可以使用多种方式,咱们会选择XML + 注解的方式
整合的思路
2.1. 先搭建整合的环境
2.2. 先把Spring的配置搭建完成
2.3. 再使用Spring整合SpringMVC框架
2.4. 最后使用Spring整合MyBatis框架
创建数据库和表结构
3.1创建数据库


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

4.创建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>

编写实体类,在ssm_domain项目中编写


package com.qcby.entity;

import java.io.Serializable;

public class Account implements Serializable {
    // 主键
    private int id;
    // 账户名称
    private String name;
    // 账号的金额
    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接口和实现类


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("业务层:查询所有");
        return null;
    }
}

第二章:Spring框架代码的编写

1. 搭建和测试Spring的开发环境

在ssm_web项目中创建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项目中编写测试方法,进行测试


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. 搭建和测试SpringMVC的开发环境

在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>
 <!-- 启动加载-->
  <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请求中文乱码的过滤器-->
<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>
    @RequestMapping("/findAll")
    public ModelAndView findAll(){
        System.out.println("表现层:查询所有");
        ModelAndView mv = new ModelAndView();
        mv.setViewName("suc");
        return mv;
    }
}

2. Spring整合SpringMVC的框架

目的:在controller中能成功的调用service对象中的方法。

在项目启动的时候,就去加载spring.xml的配置文件,在web.xml中配置
ContextLoaderListener监听器(该监听器只能加载WEB-INF目录下的applicationContext.xml的配置文
件,所以要配置全局的变量加载类路径下的配置文件)。


<!--配置Spring的监听器-->
<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对象,调用service对象的方法进行测试


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;
    
    @RequestMapping("/findAll")
    public ModelAndView findAll(){
        System.out.println("表现层:查询所有");
        //调用service的方法
        List<Account> list = accountService.findAll();
        ModelAndView mv = new ModelAndView();
        mv.setViewName("suc");
        return mv;
    }
}

第四章:Spring整合MyBatis框架

1. 搭建和测试MyBatis的环境

在web项目中编写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都可以,默认是忽略大写的-->
        <!--<typeAlias type="com.qcby.entity.User" alias="user"/>-->

        <!--针对com.qcby.entity包下的所有的类,都可以使用当前的类名做为别名-->
        <package name="com.qcby.entity"/>
    </typeAliases>

    <environments default="mysql">
        <environment id="mysql">
            <!--配置事务的类型,使用本地事务策略-->
            <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>

编写测试的方法


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);
        }
        //关闭资源
        session.close();
        in.close();
    }
}

2. Spring整合MyBatis框架

目的:把SqlMapConfig.xml配置文件中的内容配置到applicationContext.xml配置文件中
在service中注入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"
       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">
   <!-- 加载数据库配置属性文件-->
    <context:property-placeholder location="classpath:jdbc.properties"/>
    <!--开启注解扫描,要扫描的是service-->
    <context:component-scan base-package="com.qcby.service"/>
    <!--配置数据库连接池-->
    <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创建工厂对象-->
    <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 注入数据库连接池 -->
        <property name="dataSource" ref="dataSource"/>
        <!-- 扫描entity包 使用别名 -->
        <property name="typeAliasesPackage" value="com.qcby.entity" />
        <!-- 扫描sql配置文件:mapper需要的xml文件 -->
        <property name="mapperLocations" value="classpath:mapper
    @RequestMapping("/findAll")
    public ModelAndView findAll(){
        System.out.println("表现层:查询所有");
        //调用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配置声明式事务管理


<!-- 配置声明式事务管理-->
 <!--平台事务管理器-->
 <bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
     <property name="dataSource" ref="dataSource"/>
 </bean>
 <!--配置事务的通知-->
 <tx:advice id="txAdvice" transaction-manager="dataSourceTransactionManager">
     <tx:attributes>
         <tx:method name="find*" read-only="true"/>
         <tx:method name="*" />
     </tx:attributes>
 </tx:advice>
 <!--配置事务的增强-->
 <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;
    
    @RequestMapping("/findAll")
    public ModelAndView findAll(){
        System.out.println("表现层:查询所有");
        //调用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接口和实现类代码


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("业务层:查询所有");
        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>

到此这篇关于从零开始SSM搭建步骤(图文)的文章就介绍到这了,更多相关SSM搭建内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯