栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SSM框架整合--一篇就够了(springboot基础)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SSM框架整合--一篇就够了(springboot基础)

现在随着Springboot的流行,我们发现在撰写一个web项目已经变得很简单了,但是好多朋友可能没有学过springmvc,直接学习的springboot,对springmvc的原理,框架的整合思路不是很了解,下来,帮助小伙伴们梳理下。

关于作者
金山老师:从事Java、大数据、Python职业化培训6年,项目管理、软件开发14年。欢迎添加我的微信号【jshand】,最近建了一些微信交流群,扫描下方二维码添加公众号,回复:进群
部分讲课录屏已经上传到bilibili,欢迎搜索“是金山老师”

文章目录
  • 1. SSM框架整合
    • 1.1. 创建webapp骨架的项目
    • 1.2. 添加依赖
    • 1.3. 整合思路
    • 1.4. 搭建SpringMVC框架
      • 1.4.1. IOC配置文件(SpringMVC.xml)
      • 1.4.2. Web.xml中配置前端控制器
      • 1.4.3. 编写Controller进行测试
      • 1.4.4. 发布Tomcat使用浏览器访问测试mvc程序
      • 1.4.5. 配置日志组件log4j
        • 1.4.5.1. 在classpath下添加log4j.properties
        • 1.4.5.2. 自定义的的日志调用
      • 1.4.6. 全局的异常处理器
      • 1.4.7. 全局的数据校验
    • 1.5. 搭建Mybatis的程序
      • 1.5.1. 添加依赖
      • 1.5.2. SqlMapConfig.xml
      • 1.5.3. 在dao包下配置Mapper代理
      • 1.5.4. 配置Mapper.xml
      • 1.5.5. 将Mapper添加到SqlMapConfig.xml中
      • 1.5.6. 使用main的形式访问mybatis(单元测试)
    • 1.6. 将SQLSessionFactory放到IOC容器中
      • 1.6.1. UserService
      • 1.6.2. UserController
      • 1.6.3. 使用**IOC容器自动的生成Mapper代理对象并使用容器管理
      • 1.6.4. 使用mybatis工具生成Mapper接口
        • 1.6.4.1. 要求mapper.java和Mapper.xml在同一个包下
      • 1.6.5. 使用mybatis工具生成Mapper接口
      • 1.6.6. 修改了下UserController和UserService的代码(依赖关系)
        • 1.6.6.1. UserController
        • 1.6.6.2. UserService
        • 1.6.6.3. 测试
    • 1.7. 管理事务
    • 1.8. 测试的逻辑
  • 2. SSM单表增删改查
    • 2.1. 查询列表
      • 2.1.1. TProductMapper通过工具生成 √
      • 2.1.2. ProductService查询功能(依赖dao)
      • 2.1.3. ProductController控制器方法查询集合
      • 2.1.4. 展示列表的页面
    • 2.2. 添加
      • 2.2.1. 添加页面
      • 2.2.2. Service的添加方法
      • 2.2.3. 控制器:
      • 2.2.4. 解决中文乱码
    • 2.3. 修改
      • 2.3.1. product_list.jsp
      • 2.3.2. product_edit.jsp
      • 2.3.3. Service的根据主键查询
      • 2.3.4. Service的修改方法
      • 2.3.5. Controller的方法
    • 2.4. 删除
      • 2.4.1. 在列表页中添加删除按钮,(普通的get删除、ajax删除两种情况都有)
      • 2.4.2. 详见修改时的[列表页面]
      • 2.4.3. 后端的Controller的删除方法
      • 2.4.4. Service的删除方法

1. SSM框架整合
  • Spring

  • SpringMVC

  • Mybatis

1.1. 创建webapp骨架的项目

1.2. 添加依赖

Spring-容器

Spring-text

Springmvc-模块

Springmvc-jdbc

SpringMVC依赖的Jackson的json库

SpringMVC的校验框架

文件上传下载的类库

Jsp、Servlet API()

Jstl 标签库

Mybatis的类库

Mybatis的分页插件

mybatis-spring 需要使用Spring的IOC容器管理SQLSessionFactory::SQLSessionFactoryBean

数据库驱动:mysql-connector-java 5.4. 1

数据源的类库:(C3p0、DBCP、HikariCP)

事务: Springmvc-事务

事务使用的面向切面aop织入(aspectjweaver)

日志的类库:lo4j的日志




  4.0.0

  com.neuedu
  ssm
  1.0
  war

  ssm Maven Webapp
  
  http://www.example.com

  
    UTF-8
    1.7
    1.7
  

  
    
    
      junit
      junit
      4.12
      test
    

    
    
      org.springframework
      spring-webmvc
      5.2.4.RELEASE
    

    
    
      org.springframework
      spring-jdbc
      5.2.4.RELEASE
    
    
    
      org.springframework
      spring-tx
      5.2.4.RELEASE
    
    
    
      org.springframework
      spring-test
      5.2.4.RELEASE
    

    
    
      org.aspectj
      aspectjweaver
      1.9.5
    




    
    
    
      com.fasterxml.jackson.core
      jackson-core
      2.9.9
    

    
    
      com.fasterxml.jackson.core
      jackson-annotations
      2.9.9
    

    
    
      com.fasterxml.jackson.core
      jackson-databind
      2.9.9.1
    
    


    
    
      org.hibernate
      hibernate-validator
      5.1.0.Final
    


    
    
      commons-fileupload
      commons-fileupload
      1.4
    

    
    
      javax.servlet
      javax.servlet-api
      3.0.1
      provided
    


    
    
    
      javax.servlet.jsp
      javax.servlet.jsp-api
      2.3.3
      provided
    



    
    
    
      javax.servlet
      jstl
      1.2
    
    
    
      taglibs
      standard
      1.1.2
    
    


    
    
      org.mybatis
      mybatis
      3.5.3
    

    
    
      mysql
      mysql-connector-java
      5.1.48
    

  
    
      com.github.pagehelper
      pagehelper
      5.1.11
    


    
    
      org.mybatis
      mybatis-spring
      2.0.4
    


    
    
      commons-dbcp
      commons-dbcp
      1.4
    


    
    
      log4j
      log4j
      1.2.17
    

    
    
      org.springframework
      spring-tx
      5.2.4.RELEASE
    


  

  
    ssm
    
      
        
          maven-clean-plugin
          3.1.0
        
        
        
          maven-resources-plugin
          3.0.2
        
        
          maven-compiler-plugin
          3.8.0
        
        
          maven-surefire-plugin
          2.22.1
        
        
          maven-war-plugin
          3.2.2
        
        
          maven-install-plugin
          2.5.2
        
        
          maven-deploy-plugin
          2.8.2
        
      
    
  

1.3. 整合思路

由spring管理SQLSessionFactory

Spring和Mybatis整合生成代理对象(通过Spring生成Mapper的代理对象)

1 )搭建Spirng(SpringMVC的程序)

  1. 搭建Mybatis的程序(控制台程序)

  2. 将SQLSessionFactory交给Spring容器管理

1.4. 搭建SpringMVC框架 1.4.1. IOC配置文件(SpringMVC.xml)

1) 包扫描

2) 开启mvc:annotation-driven注解驱动

3) 可以配置视图解析器(前缀、后缀)此处默认不进行配置

4) 因为RESTful风格需要mvc:default-servlet-handler 用于处理静态资源

5) 配置文件上传的解析器




    
    

    
    

    
    


    
    
        
        
    
    

1.4.2. Web.xml中配置前端控制器



  Archetype Created Web Application

  
  
    DispatcherServlet
    org.springframework.web.servlet.DispatcherServlet
    
      
      contextConfigLocation
      classpath:springmvc.xml
    

    1

  

  
    DispatcherServlet
    /
  



1.4.3. 编写Controller进行测试
package com.neuedu.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class IndexController {

    @RequestMapping("/index")
    public String index(){
        return "index";
    }

}
1.4.4. 发布Tomcat使用浏览器访问测试mvc程序

1.4.5. 配置日志组件log4j

官网:

http://logging.apache.org/log4j/1.2/manual.html

博客:

https://www.cnblogs.com/wangzhuxing/p/7753420.html

添加组件依赖(开始已经完成).

设置日志组件,

1.4.5.1. 在classpath下添加log4j.properties
#配置全局的日志级别和输出方式
log4j.rootLogger=DEBUG, stdout  



#单独针对org.springframework包设置级别INFO
#log4j.logger.org.springframework=INFO
#单独针对RequestMappingHandlerMapping类设置级别INFO
#log4j.logger.org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping=ERROR
#log4j.logger.org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping=DEBUG


#自定义包(自己写的)
log4j.logger.com.neuedu=NONE
#log4j.logger.com.neuedu.dao=DEBUG

#设置sql输出
#log4j.logger.com.neuedu.framework=DEBUG
#log4j.logger.java.sql.Statement=DEBUG
#log4j.logger.java.sql.PreparedStatement=DEBUG
#log4j.logger.java.sql.ResultSet=DEBUG


#设置外观(如何除数日志)
#外观ConsoleAppender ---向控制台输出,文件
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
#设置日志的布局类型
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout  
#设置输出日志的格式
log4j.appender.stdout.layout.ConversionPattern=[%p]:%d{HH:mm:ss} %c(%Lu884C) %m%n
1.4.5.2. 自定义的的日志调用
@RestController
public class IndexController {

    Logger logger = Logger.getLogger(IndexController.class);

    @RequestMapping("/index")
    public String index(){
        logger.trace("trace..............");// TRACE DEBUG INFO ERROR FATAL
        logger.debug("DEBUG..............");//DEBUG INFO ERROR FATAL
        logger.info("info.............."); // INFO ERROR FATAL
        logger.error("error..............");//ERROR FATAL
        logger.fatal("fatal..............");//FATAL


        return "index";
    }
}
1.4.6. 全局的异常处理器

1.4.7. 全局的数据校验

1.5. 搭建Mybatis的程序 1.5.1. 添加依赖

参考全局的依赖

1.5.2. SqlMapConfig.xml



    


        
            
            
                
                
                
                
            
        


    
    
        
    

1.5.3. 在dao包下配置Mapper代理
package com.neuedu.dao;


public interface TestMapper {

    public int selectUserCount();
}
1.5.4. 配置Mapper.xml




    


1.5.5. 将Mapper添加到SqlMapConfig.xml中

1.5.6. 使用main的形式访问mybatis(单元测试)

package com.neuedu.dao;

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.Before;
import org.junit.Test;

import java.io.InputStream;

import static org.junit.Assert.*;


public class TestMapperTest {

    SqlSessionFactory factory = null;
    String config = "SqlMapConfig.xml";
    @Before
    public void setUp() throws Exception {

        InputStream is = Resources.getResourceAsStream(config);
        factory = new SqlSessionFactoryBuilder().build(is);
    }

    @Test
    public void selectUserCount() {
        SqlSession session = factory.openSession();

        TestMapper dao =  session.getMapper(TestMapper.class);
        int count = dao.selectUserCount();

        System.out.println("count:"+count);


        session.close();
    }
}

1.6. 将SQLSessionFactory放到IOC容器中

提前编写Controller、Service并设置依赖关系(UserController依赖UserService,UserService依赖TestMapper)

1.6.1. UserService
package com.neuedu.service;

import com.neuedu.dao.TestMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class UserService {

    @Autowired
    TestMapper testMapper;


    public List queryAll(){
        int count = testMapper.selectUserCount();
        System.out.println("count :"+count );
        return null;
    }

}
1.6.2. UserController
package com.neuedu.controller;

import com.neuedu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;


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

    @Autowired
    private UserService userService;



    @ResponseBody
    @RequestMapping("/list")
    public String list(){
        List list = userService.queryAll();
        return "user - list ";
    }

}

启动的时候会抛出依赖失败的异常

1.6.3. 使用**IOC容器自动的生成Mapper代理对象并使用容器管理

1 )配置DataSource 使用的是dbcp

2)配置SQLSessionFactoryBean

3) 配置单个TestMapper(弃用)

4)启动包扫描的形式注册多个Mapper接口的代理对象




    
    

    
    


    
    


    
    
        
        
    


    
    
        
        
        
        
        
    

    
    
       
        
    

    









    
    
          
        
    




1.6.4. 使用mybatis工具生成Mapper接口 1.6.4.1. 要求mapper.java和Mapper.xml在同一个包下

同一个包下的xml默认不编译需要添加maven配置使maven编译时复制xml到target

1.6.5. 使用mybatis工具生成Mapper接口 1.6.6. 修改了下UserController和UserService的代码(依赖关系) 1.6.6.1. UserController
package com.neuedu.controller;

import com.neuedu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;


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

    @Autowired
    private UserService userService;

    @ResponseBody
    @RequestMapping("/list")
    public List list(){
        List list = userService.queryAll();
        return list;
    }

}
1.6.6.2. UserService
package com.neuedu.service;

import com.neuedu.dao.TUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class UserService {

//    @Autowired
//    TestMapper testMapper;

    @Autowired
    TUserMapper tUserMapper;

    public List queryAll(){
//        int count = testMapper.selectUserCount();
//        System.out.println("count :"+count );
        return tUserMapper.selectByExample(null);
    }


}
 

将原来的自己写的TestMapper删掉了,单元测试的TestMapperTest类注释掉了

1.6.6.3. 测试

http://127.0.0.1:8080/ssm/user/list

1.7. 管理事务



    
    

    
    


    
    


    
    
        
        
    


    
    
        
        
        
        
        
    

    
    
        
        
    

    
    

    

    
    
        
        
    


    

    
    
        
        
    


    
    
        
            
            
            
            
            
            
        
    


    
    
        
        
    



在service、Controller的基础上追加save方法

package com.neuedu.controller;

import com.neuedu.entity.TUser;
import com.neuedu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


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

    @Autowired
    private UserService userService;

    @ResponseBody
    @RequestMapping("/list")
    public List list(){
        List list = userService.queryAll();
        return list;
    }


    
    @ResponseBody
    @RequestMapping("/save")
    public Map save(TUser user) throws Exception {
       boolean success = userService.save(user);

       Map result = new HashMap();
       result.put("success",success);

       return result;
    }

}
package com.neuedu.service;

import com.neuedu.dao.TUserMapper;
import com.neuedu.entity.TUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service
public class UserService {

//    @Autowired
//    TestMapper testMapper;

    @Autowired
    TUserMapper tUserMapper;

    public List queryAll(){
//        int count = testMapper.selectUserCount();
//        System.out.println("count :"+count );
        return tUserMapper.selectByExample(null);
    }


    
    public boolean save(TUser user) throws Exception {



        int count = tUserMapper.insertSelective(user);

        if(!"男".equals(user.getGender()) || !"女".equals(user.getGender())){
            throw new Exception("性别不正确");
        }

        return count>0;
    }


}

正常的请求

http://127.0.0.1:8080/ssm/user/save?userId=50&userName=abcdef&gender=%E7%94%B7&status=0

有可能产生异常的

http://127.0.0.1:8080/ssm/user/save?userId=50&userName=abcdef&gender=xx&status=0

1.8. 测试的逻辑 2. SSM单表增删改查

以t_product为例

2.1. 查询列表 2.1.1. TProductMapper通过工具生成 √ 2.1.2. ProductService查询功能(依赖dao)

依赖dao(TProductMapper)

package com.neuedu.service;

import com.neuedu.dao.TProductMapper;
import com.neuedu.entity.TProduct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class ProductService {

    @Autowired
    TProductMapper productMapper;

    public List queryPage(){
        return productMapper.selectByExample(null);
    }

}
2.1.3. ProductController控制器方法查询集合

让控制器依赖ProductService

分页展示列表

package com.neuedu.controller;

import com.neuedu.entity.TProduct;
import com.neuedu.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;


@Controller
@RequestMapping("/product")
public class ProductControlller {
    @Autowired
    ProductService productService;


    
    @RequestMapping("/list")
    public String listPage(Model model){

        List list = productService.queryPage();
        //将查询集合放到作用域中,并展示到jsp的列表
        model.addAttribute("productList",list);


        return "/product/product_list.jsp";
    }
    
}
2.1.4. 展示列表的页面

/product/product_list.jsp

<%--
  Created by IntelliJ IDEA.
  User: root
  Date: 2020/4/3
  Time: 13:49
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>


    Title
    


后台管理>产品列表


        
序号 数据id 产品名称 价格 操作
${stat.count} ${product.pid} ${product.name} ${product.price} 修改 删除 ajax删除
2.2. 添加 2.2.1. 添加页面
%--
  Created by IntelliJ IDEA.
  User: root
  Date: 2020/4/3
  Time: 14:10
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    产品添加




产品id
名称
单价
2.2.2. Service的添加方法
public boolean save(TProduct product){
    int count =  productMapper.insertSelective(product);
    return count>0;
}
2.2.3. 控制器:

1)跳转到添加页

2)保存产品的方法

@RequestMapping("/toAdd")
public String toAdd(Model model){
    return "/product/product_add.jsp";
}



@RequestMapping("/save")
public String save(TProduct product){

    boolean success = productService.save(product);

    if(success){
        //跳转到查询列表
        return "redirect:/product/list";
    }else{
        //跳转回添加页 展示错误信息
        return "product/product_add.jsp";
    }

}
2.2.4. 解决中文乱码

  CharacterEncodingFilter
  org.springframework.web.filter.CharacterEncodingFilter
  
    encoding
    UTF-8
  
  
    forceRequestEncoding
    true
  
  
    forceResponseEncoding
    true
  


2.3. 修改

修改的入口,在列表页中添加一列“修改”按钮,当点击修改按钮跳转到product_edit.jsp,jsp提供展示表单的作用(待修改的 数据展示)。点击页面的保存按钮提交修改的信息到数据库中,并刷新列表。

2.3.1. product_list.jsp
<%--
  Created by IntelliJ IDEA.
  User: root
  Date: 2020/4/3
  Time: 13:49
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>


    Title
    


后台管理>产品列表


        
序号 数据id 产品名称 价格 操作
${stat.count} ${product.pid} ${product.name} ${product.price} 修改 删除 ajax删除
2.3.2. product_edit.jsp
<%--
  Created by IntelliJ IDEA.
  User: root
  Date: 2020/4/3
  Time: 14:10
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    产品添加




产品id
名称
单价
2.3.3. Service的根据主键查询
public TProduct selectById(String pid){
    return  productMapper.selectByPrimaryKey(pid);
}
2.3.4. Service的修改方法
public boolean update(TProduct product){
    int count = productMapper.updateByPrimaryKeySelective(product);
    return count>0;
}
2.3.5. Controller的方法
@RequestMapping("/toEdit")
public String toEdit(Model model,String id){
    TProduct product = productService.selectById(id);
    model.addAttribute("product",product);
    return "/product/product_edit.jsp";
}

@RequestMapping("/edit")
public String edit(TProduct product){
    boolean success = productService.update(product);
    if(success){
        //跳转到查询列表
        return "redirect:/product/list";
    }else{
        //跳转回添加页 展示错误信息
        return "product/product_edit.jsp";
    }
}
2.4. 删除 2.4.1. 在列表页中添加删除按钮,(普通的get删除、ajax删除两种情况都有) 2.4.2. 详见修改时的[列表页面] 2.4.3. 后端的Controller的删除方法
@RequestMapping("/deleteById")
public String deleteById(String id){

    boolean success = productService.deleteBydId(id);

    //需要携带异常消息

    return "redirect:/product/list";
}


@ResponseBody
@RequestMapping("/ajaxDeleteById")
public Map ajaxDeleteById(String id){

    boolean success = productService.deleteBydId(id);

    //需要携带异常消息
    Map result = new HashMap();
    result.put("success",success);

    return result;
}
2.4.4. Service的删除方法
public boolean deleteBydId(String id) {
    return productMapper.deleteByPrimaryKey(id)>0;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/838987.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号