内嵌式Tomcat整合SSM框架

前言

笔者在学习的时候发现,为什么每次都要手动去配置Tomcat,我能不能不配啊?所以笔者参考了SpringBoot框架的开发思想,想到了使用内嵌式Tomcat,经过笔者查询大量的资料,最终实现了,那么我们接下来就一起看看怎么实现!

技术栈

JDK17

Apache-tomcat-10.1.6

Spring-6.0.0

SpringMVC-6.0.0

MyBatis-3.5.6

MySQL Driver-8.0.27

本项目源码:https://gitee.com/mumangguo/embed-tomcat-ssm,有需要的自取!

具体实现

  1. 创建普通Maven工程,不需要创建Maven的Web工程

内嵌式Tomcat整合SSM框架_第1张图片
  1. 引入相关依赖,并在properties标签中指定公共版本号

     
        6.0.0
        10.1.6
    

    
        
        
            org.apache.tomcat.embed
            tomcat-embed-core
            ${embed.tomcat.version}
        

        
            org.apache.tomcat.embed
            tomcat-embed-jasper
            ${embed.tomcat.version}
        

        
        
            junit
            junit
            3.8.1
            test
        

        
        
            org.springframework
            spring-core
            ${spring.version}
        
        
            org.springframework
            spring-beans
            ${spring.version}
        
        
            org.springframework
            spring-aop
            ${spring.version}
        
        
            org.springframework
            spring-context
            ${spring.version}
        
        
            org.springframework
            spring-context-support
            ${spring.version}
        
        
            org.springframework
            spring-jdbc
            ${spring.version}
        
        
            org.springframework
            spring-web
            ${spring.version}
        

        
        
            org.springframework
            spring-webmvc
            ${spring.version}
        

        
        
            com.alibaba
            druid
            1.1.12
        

        
        
            mysql
            mysql-connector-java
            8.0.27
        
        
        
            org.mybatis
            mybatis
            3.5.6
        
        
            org.mybatis
            mybatis-spring
            3.0.1
        

        
        
            com.fasterxml.jackson.core
            jackson-databind
            2.9.3
        

        
        
            org.aspectj
            aspectjweaver
            1.9.5
        
        
            org.aspectj
            aspectjrt
            1.9.5
        
    
  1. 在resources目录下新建一个名为WEB-INF的目录,在此目录下创建一个web.xml文件,并写入以下内容

目录结构:

内嵌式Tomcat整合SSM框架_第2张图片




    Archetype Created Web Application
    
    
        contextConfigLocation
        classpath:config/spring.xml
    

    
    
        org.springframework.web.context.ContextLoaderListener
    

    
    
        springmvc
        org.springframework.web.servlet.DispatcherServlet
        
            contextConfigLocation
            classpath:config/springmvc.xml
        
    
    
        springmvc
        /
    
  1. 在resouces目录下新建一个config目录用来管理spring相关配置文件,具体内容如下

目录结构:

内嵌式Tomcat整合SSM框架_第3张图片

jdbc.properties

jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm
jdbc.username=root
jdbc.password=admin

MyBatis-Config.xml




    
    
        
    

spring.xml




    
    

    
    

    
    
        
        
        
        
    

    
    
        
        
        
        
        
        
        
        
    

    
    
        
        
    

    
    
        
    
    
    

springmvc.xml




    
    
    
    
    
    
        
        
    
  1. 编写Tomcat启动类

package com.mmg;

import org.apache.catalina.Context;
import org.apache.catalina.WebResourceRoot;
import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.webresources.DirResourceSet;
import org.apache.catalina.webresources.StandardRoot;

import java.io.File;

/**
 * 通过TomcatStarter启动该项目即可
 * @author mmg
 */
public class TomcatStarter {
    public static void main(String[] args) throws Exception {
        // 启动 tomcat
        Tomcat tomcat = new Tomcat();
        tomcat.setPort(Integer.getInteger("port", 8080));
        tomcat.getConnector();
        // 创建 WebApp
        Context context = tomcat.addWebapp("", new File("src/main/resources").getAbsolutePath());
        WebResourceRoot resources = new StandardRoot(context);
        resources.addPreResources(
                new DirResourceSet(resources, "/WEB-INF/classes",
                        new File("target/classes").getAbsolutePath(), "/"));
        context.setResources(resources);

        tomcat.start();
        tomcat.getServer().await();
    }
}
  1. 编写实体类,包名为com.mmg.entity,文件名为Users

package com.mmg.entity;

/**
 * 实体类
 */
public class Users {

    private Integer id;
    private String username;
    private String birthday;
    private Integer sex;
    private String address;

    public Users() {
    }

    public Users(String username, String birthday, Integer sex, String address) {
        this.username = username;
        this.birthday = birthday;
        this.sex = sex;
        this.address = address;
    }

    public Users(Integer id, String username, String birthday, Integer sex, String address) {
        this.id = id;
        this.username = username;
        this.birthday = birthday;
        this.sex = sex;
        this.address = address;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

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

    public String getBirthday() {
        return birthday;
    }

    public void setBirthday(String birthday) {
        this.birthday = birthday;
    }

    public Integer getSex() {
        return sex;
    }

    public void setSex(Integer sex) {
        this.sex = sex;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "Users{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", birthday='" + birthday + '\'' +
                ", sex=" + sex +
                ", address='" + address + '\'' +
                '}';
    }
}
  1. 编写dao层,包名为com.mmg.dao,文件名为UsersDao

package com.mmg.dao;

import com.mmg.entity.Users;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface UsersDao {

    /**
     * 分页查询
     */
    List selectByPage(@Param("page") Integer page, @Param("pageSize") Integer pageSize);

    /**
     * 根据id查询
     */
    Users selectById(Integer id);

    /**
     * 查询所有用户
     */
    List selectAll();

    /**
     * 新增
     */
    int insert(Users users);

    /**
     * 删除
     */
    int delete(Integer id);

    /**
     * 更新
     */
    int update(Users user);
}
  1. 编写mapper映射文件,在resources目录下新建mapper目录,用来存放mapper映射

目录结构:

内嵌式Tomcat整合SSM框架_第4张图片
 



    
        insert into users values (null,#{username},#{birthday},#{sex},#{address})
    

    
        update t_user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} where id=#{id}
    

    
        delete from users where id=#{id}
    

    

    

    
  1. 编写service层和service实现层,包名为com.mmg.service和com.mmg.service.impl

UsersService.java

package com.mmg.service;

import com.mmg.entity.Users;

import java.util.List;

public interface UsersService {
    /**
     * 分页查询
     */
    List selectByPage(Integer page, Integer pageSize);

    /**
     * 根据id查询
     */
    Users selectById(Integer id);

    /**
     * 查询所有用户
     */
    List selectAll();

    /**
     * 新增
     */
    int insert(Users users);

    /**
     * 删除
     */
    int delete(Integer id);

    /**
     * 更新
     */
    int update(Users users);
}

UsersServiceImpl.java

package com.mmg.service.impl;

import com.mmg.dao.UsersDao;
import com.mmg.entity.Users;
import com.mmg.service.UsersService;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Transactional //开启事务
@Service //将UsersServiceImpl交给Spring管理,默认类名首字母小写
public class UsersServiceImpl implements UsersService {

    private UsersDao usersDao;

    //使用构造注入
    @Autowired
    public UsersServiceImpl(UsersDao usersDao) {
        this.usersDao = usersDao;
    }


    @Override
    public List selectByPage(Integer page, Integer pageSize) {
        page = (page - 1) * pageSize;
        return usersDao.selectByPage(page, pageSize);
    }

    @Override
    public Users selectById(Integer id) {
        return usersDao.selectById(id);
    }

    public List selectAll() {
        return usersDao.selectAll();
    }

    public int insert(Users users) {
        return usersDao.insert(users);
    }

    @Override
    public int delete(Integer id) {
        return usersDao.delete(id);
    }

    @Override
    public int update(Users users) {
        return usersDao.update(users);
    }
}
  1. 编写Controller层,包名为com.mmg.controller

package com.mmg.controller;

import com.mmg.entity.Users;
import com.mmg.service.UsersService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController //代表类中返回值转换为json响应到浏览器
@RequestMapping("/users") //代表访问路径,通过/users访问
public class UsersController {

    @Resource
    private UsersService usersService;

    /**
     *  API=http://localhost:8080/users/{page}/{pageSize}
     */
    @GetMapping("/{page}/{pageSize}")
    public List getUsersByPage(@PathVariable("page") Integer page, @PathVariable("pageSize") Integer pageSize) {
        return usersService.selectByPage(page, pageSize);
    }

    /**
     * API=http://localhost:8080/users/{id}
     */
    @GetMapping("/{id}")
    public Users getUsersById(@PathVariable("id") Integer id) {
        return usersService.selectById(id);
    }

    /**
     * API=http://localhost:8080/users
     * 参数:无
     */
    @GetMapping("") //get请求的访问路径
    public List getAllUsers() {
        return usersService.selectAll();
    }

    /**
     * API=http://localhost:8080/users/add
     * 参数:
     * {
     * "username": "木芒果",
     * "birthday": "2003-12-22",
     * "sex": 2,
     * "address": "湖南"
     * }
     */
    @PostMapping("/add") //post请求的访问路径
    public String addUsers(@RequestBody Users users) {
        int count = usersService.insert(users);
        if (count == 1) {
            return "success";
        }
        return "fail";
    }

    /**
     * API=http://localhost:8080/users/{id}
     */
    @DeleteMapping("/{id}") //delete请求的访问路径
    public String deleteUsers(@PathVariable("id") Integer id) {
        int count = usersService.delete(id);
        if (count == 1) {
            return "success";
        }
        return "fail";
    }

    /**
     * API=http://localhost:8080/users
     * 参数:
     * {
     * "username": "木芒果",
     * "birthday": "2003-12-22",
     * "sex": 2,
     * "address": "湖南"
     */
    @PutMapping("") //put请求的访问路径
    public String updateUsers(@RequestBody Users users) {
        int count = usersService.update(users);
        if (count == 1) {
            return "success";
        }
        return "fail";
    }
}
  1. 在resources目录下新建一个index.jsp供显示

目录结构:

内嵌式Tomcat整合SSM框架_第5张图片
<%@ page contentType="text/html;charset=UTF-8" language="java" %>




  1. 到此代码全部写完,我们通过启动TomcatStarter类完成项目的启动!

总结

  1. 总体来说还是比较简单的,主要用到了Tomcat底层相关知识

  1. 如果你有更好的想法可以评论在下方哦!笔者水平有限...

  1. 如果不想看长篇的教程,可以直接拉取本项目自行查询

你可能感兴趣的:(tomcat,spring,java)