零基础学JavaWeb开发(二十三)之 springmvc入门到精通(3)

5、spring+springmvc+mybatis整合

5.1、项目技术需求分析

1.使用ssm+layui技术开发 对用户表数据实现增删改查

采用前后端分离架构模式

零基础学JavaWeb开发(二十三)之 springmvc入门到精通(3)_第1张图片

零基础学JavaWeb开发(二十三)之 springmvc入门到精通(3)_第2张图片

5.2、SSM环境的整合之提供增删改查

整合数据库表结构

CREATE TABLE `mayikt_users` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
  `age` int DEFAULT NULL,
  `addres` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=48 DEFAULT CHARSET=utf8mb3;

整合maven依赖

spring/springmvc/mybatis




    4.0.0

    com.mayikt
    mayikt-ssm02
    1.0-SNAPSHOT
    war

    mayikt-ssm02 Maven Webapp
    
    http://www.example.com

    
        UTF-8
        1.7
        1.7
    

    
        
        
            org.springframework
            spring-webmvc
            5.2.10.RELEASE
        
        
        
            org.mybatis
            mybatis
            3.5.6
        
        
            org.springframework
            spring-jdbc
            5.2.10.RELEASE
        
        
            org.mybatis
            mybatis-spring
            1.3.0
        

        
            mysql
            mysql-connector-java
            8.0.13
        
        
        
            com.alibaba
            druid
            1.1.16
        


        
            javax.servlet
            javax.servlet-api
            3.1.0
            provided
        
        
        
            com.fasterxml.jackson.core
            jackson-databind
            2.9.0
        
    

    
        
            
                org.apache.tomcat.maven
                tomcat7-maven-plugin
                2.1
                
                    80
                    /
                
            
        
    


实体类层

com.mayikt.entity

数据库访问层

com.mayikt.mapper

业务逻辑层

com.mayikt.service

控制层

com.mayikt.controller

5.3、SSM环境的整合之配置整合

JdbcConfig

package com.mayikt.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;


public class JdbcConfig {
    /**
     * 定义数据源配置
     *
     * @return
     */
    @Bean
    public DataSource dataSource() {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName("com.mysql.jdbc.Driver");
        druidDataSource.setUrl("jdbc:mysql://localhost:3306/mayikt?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT");
        druidDataSource.setUsername("root");
        druidDataSource.setPassword("root");
        return druidDataSource;
    }

    /**
     * 整合事务
     *
     * @param dataSource
     * @return
     */
    @Bean
    public PlatformTransactionManager platformTransactionManager(@Autowired DataSource dataSource) {
        DataSourceTransactionManager dataSourceTransactionManager =
                new DataSourceTransactionManager();
        dataSourceTransactionManager.setDataSource(dataSource);
        return dataSourceTransactionManager;
    }
}

MybatisConfig

package com.mayikt.config;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;

import javax.sql.DataSource;


public class MybatisConfig {
    /**
     * mybatis相关配置
     *
     * @param dataSource
     * @return
     */
    @Bean
    public SqlSessionFactoryBean sqlSessionFactory(@Autowired DataSource dataSource) {
        SqlSessionFactoryBean sqlSessionFactoryBean =
                new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        // 实体层包
        sqlSessionFactoryBean.setTypeAliasesPackage("com.mayikt.entity");
        return sqlSessionFactoryBean;
    }

}

SpringConfig

package com.mayikt.config;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.EnableTransactionManagement;


@Configuration
@ComponentScan({"com.mayikt.service"})
//开启事务
@EnableTransactionManagement
@Import({MybatisConfig.class, JdbcConfig.class})
@MapperScan("com.mayikt.mapper")
public class SpringConfig {
}

SpringMVCConfig

package com.mayikt.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;


@EnableWebMvc
@Configuration
@ComponentScan("com.mayikt.controller")
public class SpringMVCConfig {
}

ServletConfig

package com.mayikt.config;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;


public class ServletConfig extends AbstractAnnotationConfigDispatcherServletInitializer {

    protected Class[] getRootConfigClasses() {
        return new Class[]{SpringConfig.class};
    }

    protected Class[] getServletConfigClasses() {
        return new Class[]{SpringMVCConfig.class};
    }

    protected String[] getServletMappings() {
        return new String[]{"/"};
    }
}

5.4、接口响应状态码

统一规范返回数据的格式,此处以json格式为例。返回数据应包含:返回状态码、返回状态信息、具体数据。

格式规范如下:

{
    "code":"200",
    "msg":"ok",
    "data": {
        //json格式的具体数据
    }
}

查询到数据

{
    "code":"200",
    "msg":"ok",
    "data": {
        "userName":"mayikt",
        "age":22
    }
}

前端 ajax技术

if(code==200){

        "data": {

        "userName":"mayikt",

        "age":22

        }

}

没有查询到数据

{
    "code":"500",
    "msg":"fail",
    "data": {
    
    }
}

新增数据

{
    "code":"500",
    "msg":"插入失败",
    "data": {
    
    }
}

前端:

if(code==200){

        alert(" "msg":"插入成功"")

}

Api Code状态码

1**

服务器收到请求,需要请求者继续执行操作

2**

操作被成功接收并处理

3**

重定向,需要进一步的操作以完成请求

4**

客户端错误,请求包含语法错误或无法完成请求

5**

服务器错误,服务器在处理请求的过程中发生了错误

如何封装接口响应状态码

package com.mayikt.controller;

import java.util.HashMap;


public class BaseController {
    /**
     * 提供处理请求响应成功的情况下
     *
     * @param data
     * @return
     */
    public HashMap setResultOk(Object data) {
        return setResult(200, "ok", data);
    }

    public HashMap setResultSuccess(String msg) {
        return setResult(200, msg, null);
    }


    /**
     * 提供处理请求失败情况下
     *
     * @param msg
     * @return
     */
    public HashMap setResultError(String msg) {
        return setResult(500, msg, null);
    }

    /**
     * @param code code 200 处理成功 500 处理失败
     * @param msg  响应错误内容
     * @param data 响应的数据
     * @return
     */
    public HashMap setResult(Integer code, String msg, Object data) {
        HashMap result = new HashMap<>();
        result.put("code", code);
        result.put("msg", msg);
        result.put("data", data);
        return result;
    }
}

5.5、整合全局捕获异常

当系统发生错误时,统一将系统错误日志 返回输出

package com.mayikt.controller;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@ControllerAdvice
public class GlobalExceptionHandler extends BaseController {
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public Map handleException(HttpServletRequest h, Exception e) {
        System.out.println("自定义异常:" + e);
        return setResultError("系统发生了错误!");
    }
}

你可能感兴趣的:(JavaWeb,Java,mybatis,spring,java,mvc,web)