前言
笔者在学习的时候发现,为什么每次都要手动去配置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,有需要的自取!
具体实现
创建普通Maven工程,不需要创建Maven的Web工程
![](https://i-blog.csdnimg.cn/blog_migrate/c5448100beeb887a92895ce201758d35.png)
引入相关依赖,并在properties标签中指定公共版本号
<properties>
<spring.version>6.0.0</spring.version>
<embed.tomcat.version>10.1.6</embed.tomcat.version>
</properties>
<dependencies>
<!-- tomcat相关依赖 -->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
<version>${embed.tomcat.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<version>${embed.tomcat.version}</version>
</dependency>
<!-- junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- spring相关依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- spring web mvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.12</version>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.27</version>
</dependency>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>3.0.1</version>
</dependency>
<!-- jackson -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.3</version>
</dependency>
<!-- aspectj -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.5</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.9.5</version>
</dependency>
</dependencies>
在resources目录下新建一个名为WEB-INF的目录,在此目录下创建一个web.xml文件,并写入以下内容
目录结构:
![](https://i-blog.csdnimg.cn/blog_migrate/c95a42ed7ee2d0b01c33eeb2a2e57fd2.png)
<!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 Application</display-name>
<!-- 加载spring.xml -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:config/spring.xml</param-value>
</context-param>
<!-- 配置spring工厂启动 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 配置springmvc -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:config/springmvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
在resouces目录下新建一个config目录用来管理spring相关配置文件,具体内容如下
目录结构:
![](https://i-blog.csdnimg.cn/blog_migrate/c658a3c8219f9c33f2e81f560a67a7e2.png)
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
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 开启MyBatis的STD标准日志 -->
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
</configuration>
spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<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:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 开启注解扫描 -->
<context:component-scan base-package="com.mmg.service"/>
<!--引入外部properties配置文件-->
<context:property-placeholder location="classpath:/config/jdbc.properties"/>
<!-- 创建数据源 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!-- 创建SqlSessionFactoryBean -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 配置数据源-->
<property name="dataSource" ref="dataSource"/>
<!-- 配置mapper文件的位置 -->
<property name="mapperLocations" value="classpath:mapper/*.xml"/>
<!-- 配置mybatis的别名 -->
<property name="typeAliasesPackage" value="com.mmg.entity"/>
<!-- 指定MyBatis核心配置文件的位置 -->
<property name="configLocation" value="classpath:/config/MyBatis-Config.xml"/>
</bean>
<!-- 配置Mapper扫描器 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.mmg.dao"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
<!-- 创建事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 开启事务注解生效 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
springmvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<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/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 开启注解扫描 -->
<context:component-scan base-package="com.mmg.controller"/>
<!-- 开启mvc注解驱动 -->
<mvc:annotation-driven/>
<!-- 配置试图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
编写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();
}
}
编写实体类,包名为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 + '\'' +
'}';
}
}
编写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<Users> selectByPage(@Param("page") Integer page, @Param("pageSize") Integer pageSize);
/**
* 根据id查询
*/
Users selectById(Integer id);
/**
* 查询所有用户
*/
List<Users> selectAll();
/**
* 新增
*/
int insert(Users users);
/**
* 删除
*/
int delete(Integer id);
/**
* 更新
*/
int update(Users user);
}
编写mapper映射文件,在resources目录下新建mapper目录,用来存放mapper映射
目录结构:
![](https://i-blog.csdnimg.cn/blog_migrate/1283e64c63210e5b7964c7410c6efef5.png)
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC
"-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mmg.dao.UsersDao">
<insert id="insert">
insert into users values (null,#{username},#{birthday},#{sex},#{address})
</insert>
<update id="update">
update t_user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} where id=#{id}
</update>
<delete id="delete">
delete from users where id=#{id}
</delete>
<select id="selectAll" resultType="users">
select * from users
</select>
<select id="selectByPage" resultType="users">
select * from users limit #{page},#{pageSize}
</select>
<select id="selectById" resultType="users">
select * from users where id=#{id}
</select>
</mapper>
编写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<Users> selectByPage(Integer page, Integer pageSize);
/**
* 根据id查询
*/
Users selectById(Integer id);
/**
* 查询所有用户
*/
List<Users> 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<Users> 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<Users> 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);
}
}
编写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<Users> 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<Users> 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";
}
}
在resources目录下新建一个index.jsp供显示
目录结构:
![](https://i-blog.csdnimg.cn/blog_migrate/2cbdfb4cdcc69ea70aa37be912ccba94.png)
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<div align="center">
<h1>Hello World!</h1>
<a href="users">查看所有用户</a>
<a href="users/1">查看用户1</a>
<a href="users/1/3">分页查看</a>
</div>
</body>
</html>
到此代码全部写完,我们通过启动TomcatStarter类完成项目的启动!
总结
总体来说还是比较简单的,主要用到了Tomcat底层相关知识
如果你有更好的想法可以评论在下方哦!笔者水平有限...
如果不想看长篇的教程,可以直接拉取本项目自行查询