使用RestfulTool插件模拟前端向后端发送请求体,通过SpringMVC结合MyBaits响应返回体

✨✨博主简介:一个会bbox的‍

✨✨个人主页:沫洺的主页

 系列专栏:  JavaWeb专栏 JavaSE专栏  Java基础专栏vue3专栏

如果文章对你有所帮助请留下三连✨✨

搭建案例环境

创建数据库db5,表user_email

使用RestfulTool插件模拟前端向后端发送请求体,通过SpringMVC结合MyBaits响应返回体_第1张图片

 

创建maven Web项目,pom.xml添加坐标依赖,配置tomcat

pom.xml




  4.0.0

  com.beiyou
  cms-api
  1.0-SNAPSHOT
  war

  cms-api Maven Webapp
  
  http://www.example.com

  
    UTF-8
    1.8
    1.8
  

  
    
    
      org.springframework
      spring-webmvc
      5.3.2
    
    
      javax.servlet
      javax.servlet-api
      3.1.0
      provided
    
    
      cn.hutool
      hutool-all
      5.8.5
    
    
      org.projectlombok
      lombok
      1.16.10
    


    
      com.fasterxml.jackson.core
      jackson-databind
      2.12.0
    

    
      org.springframework
      spring-context-support
      5.3.2
    
    
      mysql
      mysql-connector-java
      8.0.19
      runtime
    
    
    
      org.mybatis
      mybatis
      3.5.9
    

    
      org.mybatis
      mybatis-spring
      2.0.6
    

    
      org.springframework
      spring-jdbc
      5.3.2
    
    
      com.alibaba
      druid
      1.1.12
    


    
      junit
      junit
      4.11
      test
    
  


  
    
      
        org.apache.tomcat.maven
        tomcat7-maven-plugin
        2.2
        
          
          8080
          
          /
          
          utf-8
        
      
    
    cms-api
    
      
        
          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
        
      
    
  

搭建SpringMVC运行环境

web.xml配置前端控制器DispatcherServlet




  
  
    springDispatcherServlet
    org.springframework.web.servlet.DispatcherServlet
    
      contextConfigLocation
      classpath:spring.xml
    
    1
  
  
    springDispatcherServlet
    /
    
  



resources下创建spring.xml



    

    
    
    
    
    

    
    
    
    

java下新建com/moming/config/WebConfig

package com.moming.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * mvc配置文件
 */
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void extendMessageConverters(List> converters) {
        for (HttpMessageConverter converter:converters){
            if(converter instanceof StringHttpMessageConverter){
                ((StringHttpMessageConverter)converter).setDefaultCharset(StandardCharsets.UTF_8);
            }
            if(converter instanceof MappingJackson2HttpMessageConverter){
                ((MappingJackson2HttpMessageConverter)converter).setDefaultCharset(StandardCharsets.UTF_8);
            }

        }
    }
}

配置MyBatis

在resources下创建druid.properties

username=root
password=123456
url=jdbc:mysql:///db5?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&allowMultiQueries=true
driverClassName=com.mysql.cj.jdbc.Driver
initialSize=5
maxActive=10
maxWait=3000

创建config/DbConfig

package com.moming.config;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;

import javax.sql.DataSource;
import java.io.InputStream;
import java.util.Properties;

/**
 * 数据库配置文件
 */
@Configuration
@MapperScan("com.moming.dao")
public class DbConfig {

    /**
     * 手动注册 Druid dataSource 数据源
     * @return DataSource
     */
    @Bean
    public DataSource dataSource() throws Exception {

        InputStream resourceAsStream = DbConfig.class.getClassLoader().getResourceAsStream("druid.properties");
        Properties prop = new Properties();
        prop.load(resourceAsStream);
        DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);
        return dataSource;
    }



    /**
     * 手动注册 JdbcTemplate
     * @return JdbcTemplate
     */
    @Bean
    public JdbcTemplate jdbcTemplate(DataSource dataSource){

        JdbcTemplate jdbcTemplate  = new JdbcTemplate();
        jdbcTemplate.setDataSource(dataSource);
        return jdbcTemplate;

    }

    /**
     * 事务管理器
     * @param dataSource
     * @return
     */
    @Bean
    public DataSourceTransactionManager dataSourceTransactionManager(DataSource dataSource){
        DataSourceTransactionManager  transactionManager  = new DataSourceTransactionManager();
        transactionManager.setDataSource(dataSource);
        return transactionManager;
    }

    /**
     * 事务模板
     * @param dataSourceTransactionManager
     * @return
     */
    @Bean
    public TransactionTemplate transactionTemplate(DataSourceTransactionManager dataSourceTransactionManager){

        TransactionTemplate transactionTemplate  = new TransactionTemplate(dataSourceTransactionManager);
        //transactionTemplate.setTransactionManager(dataSourceTransactionManager);
        return transactionTemplate;

    }
    /**
     * SqlSessionFactory
     * @param
     * @return
     */

    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource());
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource[] resources = resolver.getResources("classpath:mapper/**.xml");
        sqlSessionFactoryBean.setMapperLocations(resources);
        sqlSessionFactoryBean.setTypeAliasesPackage("com.moming.entity");
        return  sqlSessionFactoryBean.getObject();
    }
}

在resources下创建mapper/user.xml






创建com/moming/entity/UserEntity实体类

package com.moming.entity;

import lombok.Data;

/**
 * 对应数据表的实体类
 */
@Data
public class UserEntity {
    private Integer id;
    private String email;
    private String password;
}

创建com/moming/entity/UserEntityQuery查询参数类

package com.moming.entity;

import lombok.Data;

/**
 * 查询参数类
 */
@Data
public class UserEntityQuery {

    private Integer id;
    private String email;
    private Integer[] ids;
}

创建拦截器对响应数据进行协议包装

com/moming/advice/MyResponseAdvice

package com.moming.advice;

import cn.hutool.json.JSONUtil;
import com.moming.dto.ResponseDto;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 拦截器
 */
@ControllerAdvice
@ResponseBody
public class MyResponseAdvice implements ResponseBodyAdvice {

    @ExceptionHandler(Exception.class)
    public Object processException(Exception ex){
        ResponseDto responseDto  = new ResponseDto();
        responseDto.setCode(1);
        responseDto.setMessage(ex.getMessage());
        return  responseDto;
    }

    @Override
    public boolean supports(MethodParameter returnType, Class> converterType) {
        return true;
    }
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {

        if(body instanceof  ResponseDto){
            return  body;
        }
        ResponseDto  responseDto  = new ResponseDto();
        responseDto.setCode(0);
        responseDto.setMessage("请求成功");
        responseDto.setData(body);

        if (selectedConverterType == StringHttpMessageConverter.class) {
            return JSONUtil.toJsonStr(responseDto);
        } else {
            return responseDto;
        }


    }
}
 
   

创建com/moming/dto/ResponseDto数据传输类

package com.moming.dto;

import lombok.Data;

/**
 * 数据传输对象
 */
@Data
public class ResponseDto {
    private int code;
    private  String message;
    private Object  data;
}

SpringMVC

数据访问层

创建com/moming/dao/UserDao

package com.moming.dao;

import com.moming.entity.UserEntity;
import com.moming.entity.UserEntityQuery;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 数据访问层
 */
//@Repository
@Mapper
public interface UserDao {
    /**
     * 查
     * @param query
     * @return
     */
    @Select("select * from user_email where id=#{id}")
    List select(UserEntityQuery query);

    /**
     * 增
     * @param userEntity
     * @return
     */
    @Insert("insert into user_email (email,password) values (#{email},#{password})")
    @SelectKey(statement = "select LAST_INSERT_ID() as id", keyProperty = "id", keyColumn = "id", before = false, resultType = Integer.class)
    int insert(UserEntity userEntity);

    /**
     * 改
     * @param userEntity
     * @return
     */
    @Update("update user_email set email=#{email},password=#{password} where id=#{id} ")
    int update(UserEntity userEntity);

    /**
     * 删
     * @param id
     * @return
     */
    @Delete("delete from user_email where id=#{id}")
    int delete(int id);
}

业务层

创建com/moming/service/UserService

package com.moming.service;

import com.moming.dao.UserDao;
import com.moming.entity.UserEntity;
import com.moming.entity.UserEntityQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 业务层
 */
@Service
public class UserService {

    @Autowired
    private UserDao userDao;

    /**
     * 查
     * @param id
     * @return
     */
    public List select(int id){
        UserEntityQuery query = new UserEntityQuery();
        query.setId(id);
        return userDao.select(query);
    }

    /**
     * 增
     * @param userEntity
     * @return
     */
    public int insert(UserEntity userEntity){
        return userDao.insert(userEntity);
    }

    /**
     * 改
     * @param userEntity
     * @return
     */
    public int update(UserEntity userEntity){
        return userDao.update(userEntity);
    }

    /**
     * 删
     * @param id
     * @return
     */
    public int delete(int id){
        return userDao.delete(id);
    }
}

接口层

创建com/moming/controller/UserController

package com.moming.controller;

import com.moming.entity.UserEntity;
import com.moming.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 接口层
 */
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 查
     * @param id
     * @return
     */
    @GetMapping("/select")
    public List select(@RequestParam("id") int id){
        return userService.select(id);
    }

    /**
     * 增
     * @param userEntity
     * @return
     */
    @PostMapping("/insert")
    public int insert(@RequestBody UserEntity userEntity){
        int rowNum = userService.insert(userEntity);
        return rowNum;
    }

    /**
     * 改
     * @param userEntity
     * @return
     */
    @PutMapping("/update")
    public int update(@RequestBody UserEntity userEntity){
        return userService.update(userEntity);
    }

    /**
     * 删
     * @param id
     * @return
     */
    @GetMapping("/delete")
    public int delete(@RequestParam("id") int id){
        return userService.delete(id);
    }

}

使用插件模拟前端向后端发送请求体

模拟查询

注意get不识别请求体,可以通过url传参

使用RestfulTool插件模拟前端向后端发送请求体,通过SpringMVC结合MyBaits响应返回体_第2张图片

运行发送请求体

使用RestfulTool插件模拟前端向后端发送请求体,通过SpringMVC结合MyBaits响应返回体_第3张图片

模拟添加

使用RestfulTool插件模拟前端向后端发送请求体,通过SpringMVC结合MyBaits响应返回体_第4张图片

 运行发送请求体

使用RestfulTool插件模拟前端向后端发送请求体,通过SpringMVC结合MyBaits响应返回体_第5张图片

使用RestfulTool插件模拟前端向后端发送请求体,通过SpringMVC结合MyBaits响应返回体_第6张图片

模拟修改

使用RestfulTool插件模拟前端向后端发送请求体,通过SpringMVC结合MyBaits响应返回体_第7张图片

 运行发送请求体

使用RestfulTool插件模拟前端向后端发送请求体,通过SpringMVC结合MyBaits响应返回体_第8张图片

使用RestfulTool插件模拟前端向后端发送请求体,通过SpringMVC结合MyBaits响应返回体_第9张图片

模拟删除

使用RestfulTool插件模拟前端向后端发送请求体,通过SpringMVC结合MyBaits响应返回体_第10张图片

 运行发送请求体

使用RestfulTool插件模拟前端向后端发送请求体,通过SpringMVC结合MyBaits响应返回体_第11张图片

使用RestfulTool插件模拟前端向后端发送请求体,通过SpringMVC结合MyBaits响应返回体_第12张图片

你可能感兴趣的:(MyBatis,SpringMVC,java,spring,mybatis)