【重温SSM框架系列】14 - SSM的整合(Spring + SpringMVC + Mybatis)

SSM的整合

  • 搭建SSM环境
  • ==SSM框架demo工程已上传至github:[https://github.com/Bryant6/SSM_Demo.git](https://github.com/Bryant6/SSM_Demo.git)==
    • 创建maven工程
    • 创建工程结构
    • 引入所需依赖pom.xml
    • 创建数据库表
  • 创建配置文件
    • MySQL数据库连接信息db.properties
    • Spring核心配置文件applicationContext.xml
    • SpringMVC核心配置文件springmvc.xml
    • mybatis核心配置文件sqlMapConfig.xml
    • 日志配置文件log4j.properties
    • 监听器、过滤器、前端控制器等配置web.xml
  • 各层类的创建(以插入user为例)
    • 创建User实体类
    • 创建UserMapper【dao层】
    • 创建UserService及实现类UserServiceImpl【service层】
    • 创建UserController【controller层】
    • 创建前端jsp页面
    • 启动Tomcat测试

大家好,我是【1+1=王】, 热爱java的计算机(人工智能)渣硕研究生在读。
如果你也对java、人工智能等技术感兴趣,欢迎关注,抱团交流进大厂!!!
Good better best, never let it rest, until good is better, and better best.

近期会重新温习一下SSM的相关知识,相应的博客会更新至专栏【SSM框架】中,欢迎大家关注!
SSM专栏:https://blog.csdn.net/weixin_43598687/category_11652306.html

搭建SSM环境

SSM框架demo工程已上传至github:https://github.com/Bryant6/SSM_Demo.git

创建maven工程

1. File–>New–>Project
【重温SSM框架系列】14 - SSM的整合(Spring + SpringMVC + Mybatis)_第1张图片
**2. 选择Maven工程,并指定JDK,然后添加工程模板。

【重温SSM框架系列】14 - SSM的整合(Spring + SpringMVC + Mybatis)_第2张图片
3. 填写项目名、存储路径、GroupId
【重温SSM框架系列】14 - SSM的整合(Spring + SpringMVC + Mybatis)_第3张图片
4. 指定maven的安装路径、配置文件以及仓库
【重温SSM框架系列】14 - SSM的整合(Spring + SpringMVC + Mybatis)_第4张图片

创建工程结构

【重温SSM框架系列】14 - SSM的整合(Spring + SpringMVC + Mybatis)_第5张图片

引入所需依赖pom.xml

整合SSM的基础依赖如下:

  <properties>
    
    <spring.version>5.0.8.RELEASEspring.version>
    <mybais.version>3.4.6mybais.version>
    <mybatis-spring.version>1.3.2mybatis-spring.version>
    <mysql-connector.version>5.1.46mysql-connector.version>
    <ojdbc7.version>12.1.0.2.0ojdbc7.version>
    <druid.version>1.0.16druid.version>
    <aopalliance.version>1.0aopalliance.version>
    <aspectj.weaver.version>1.6.4.RELEASEaspectj.weaver.version>
    <commons.logging.version>1.1.1commons.logging.version>
    <jstl.version>1.2jstl.version>
    <log4j.version>1.2.16log4j.version>
    <slf4j-api.version>1.6.1slf4j-api.version>
    <slf4j-nop.version>1.6.4slf4j-nop.version>
    <fileupload.version>1.3.1fileupload.version>
    <jackson.version>2.9.6jackson.version>
    <junit.version>4.9junit.version>
    <servlet-api.version>8.5.32servlet-api.version>
    <jsp-api.version>8.5.32jsp-api.version>

    
    <maven-compiler-plugin.version>3.8.0maven-compiler-plugin.version>
    <tomcat7-maven-plugin.version>2.2tomcat7-maven-plugin.version>
  properties>

完整的pom.xml见:SSM整合依赖包pom.xml:https://blog.csdn.net/weixin_43598687/article/details/124066660

创建数据库表

创建一个user表。
【重温SSM框架系列】14 - SSM的整合(Spring + SpringMVC + Mybatis)_第6张图片

创建配置文件

MySQL数据库连接信息db.properties

jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/ssm_demo?useUnicoid=true&characterEncoding=UTF8&useSSL=false
jdbc.user=root
jdbc.password=123456

Spring核心配置文件applicationContext.xml


<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-4.3.xsd
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context-4.3.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:component-scan base-package="com.demo.service"/>

    
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/ssm_demo"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    bean>

    <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
    bean>

    
    <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactory" ref="sessionFactory"/>
        <property name="basePackage" value="com.demo.mapper"/>
    bean>

    
    
    <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"/>
            <tx:method name="*"/>
        tx:attributes>
    tx:advice>
    
    <aop:config>
        <aop:advisor advice-ref="txAdvice" pointcut="execution(public * com.demo.service.*ServiceImpl.*(..))"/>
    aop:config>
beans>

SpringMVC核心配置文件springmvc.xml


<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:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">

    
    <context:component-scan base-package="com.demo.controller"/>
    
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/views/"/>
        <property name="suffix" value=".jsp"/>
    bean>
    

    
    <mvc:annotation-driven/>
beans>

mybatis核心配置文件sqlMapConfig.xml


DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    
    <environments default="mysql">
        <environment id="mysql">
            <transactionManager type="JDBC">transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/ssm_demo"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            dataSource>
        environment>
    environments>
    
 
    <mappers>
        <package name="com.demo.mapper"/>
    mappers>
configuration>

日志配置文件log4j.properties

log4j.rootCategory=ERROR, CONSOLE 

log4j.logger.com.demo.mapper=DEBUG

log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%C %d{YYYY-MM-dd hh:mm:ss}  %m %n

log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=E:/my.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%m %n

监听器、过滤器、前端控制器等配置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 Applicationdisplay-name>

  
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
  listener>

  <context-param>
    <param-name>contextConfigLocationparam-name>
    <param-value>classpath:applicationContext.xmlparam-value>
  context-param>

  <filter>
    <filter-name>characterEncodingFilterfilter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
    <init-param>
      <param-name>encodingparam-name>
      <param-value>UTF-8param-value>
    init-param>
  filter>
  <filter-mapping>
    <filter-name>characterEncodingFilterfilter-name>
    <url-pattern>/*url-pattern>
  filter-mapping>

  
  <servlet>
    <servlet-name>dispatcherServletservlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>

    <init-param>
      <param-name>contextConfigLocationparam-name>
      <param-value>classpath:springmvc.xmlparam-value>
    init-param>
    
    <load-on-startup>1load-on-startup>
  servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServletservlet-name>
    <url-pattern>/url-pattern>
  servlet-mapping>
web-app>

各层类的创建(以插入user为例)

【重温SSM框架系列】14 - SSM的整合(Spring + SpringMVC + Mybatis)_第7张图片

创建User实体类

package com.demo.domain;

import java.io.Serializable;

public class User implements Serializable {
    private Integer id;
    private String username;
    private String password;

    public User() {
    }

    public User(Integer id, String username, String password) {
        this.id = id;
        this.username = username;
        this.password = password;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

创建UserMapper【dao层】

UserMapper

public interface UserMapper {
    @Insert(value = "insert into user(username,password) values(#{username},#{password})")
    void save(User user);
}

创建UserService及实现类UserServiceImpl【service层】

UserService

public interface UserService {

    //保存用户
    void save(User user);
}

UserServiceImpl

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public void save(User user) {
        userMapper.save(user);
    }
}

创建UserController【controller层】

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/save")
    public String save(User user){
        System.out.println("controller层:保存账户。。。");

        userService.save(user);

        return "success";
    }
}

创建前端jsp页面

【重温SSM框架系列】14 - SSM的整合(Spring + SpringMVC + Mybatis)_第8张图片
success.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Titletitle>
head>
<body>
    <h3>成功了h3>
body>
html>

list.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Titletitle>
head>
<body>
<%--    <h3>用户列表页面h3>--%>
<%--    <a href="/user/findAll">查询所有a>--%>

    <h3>测试新增h3>
    <form action="/user/save" method="post">
        姓名:<input type="text" name="username">
        密码:<input type="password" name="password">
        <input type="submit" value="提交">
    form>
body>
html>

启动Tomcat测试

启动成功,访问:http://localhost:8080/list.jsp
【重温SSM框架系列】14 - SSM的整合(Spring + SpringMVC + Mybatis)_第9张图片
填入数据,点击提交。
【重温SSM框架系列】14 - SSM的整合(Spring + SpringMVC + Mybatis)_第10张图片
提交成功,查看数据库写入
【重温SSM框架系列】14 - SSM的整合(Spring + SpringMVC + Mybatis)_第11张图片
SSM环境整合成功!!!

SSM矿建demo工程已上传至github:https://github.com/Bryant6/SSM_Demo.git

SSM专栏:https://blog.csdn.net/weixin_43598687/category_11652306.html

你可能感兴趣的:(SSM框架,SSM,整合,spring,springmvc,mybatis)