1、前期配置
第一步:创建maven-web项目
会出现检测到Web框架,分组依据该怎么选?这里不要慌!默认就行,选择类型即可,确定。
第二步:修改配置文件web.xml为
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee
https://jakarta.ee/xml/ns/jakartaee/web-app_6_0.xsd"
version="6.0"
metadata-complete="false">
</web-app>
注意啦,因为我的tomcat版本是11.0.1 ,一开始我去找conf里的web.xml, 发现web-app的版本是6.1。
结果报错:不匹配
试了一下6.0才正确,所以一定要注意。
第三步:tomcat配置
选择热部署方式
第四步:配置 pom.xml
- 编译器版本为17
- 引入的依赖包括:mybatis,mysql驱动,junit,logback,servlet
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.10</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.30</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.11</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
第五步:添加java文件
main目录下添加
2、细节总结
细节1、使用MVC架构
要清晰的知道对象依赖关系,目前便于后续spring依赖倒置。
一般定义接口和接口的实现类,这样用接口对象new 接口的实现类,实现多态。
细节2、xml配置文件
webapp标签中要设置 metadata-complete=“false”,代表启用注解式开发,可以使用@WebServlet(“/transfer”)注解了,当然默认就是false。
细节3、pom.xml依赖配置
tomcat版本大于9,要用jakrata下的servlet,不然报错
<!-- https://mvnrepository.com/artifact/jakarta.servlet/jakarta.servlet-api -->
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<version>6.0.0</version>
<scope>provided</scope>
</dependency>