共计 2309 个字符,预计需要花费 6 分钟才能阅读完成。
- 创建普通
Maven
项目,并输入项目信息,这里指定项目名称为hello-servlet
- 向
pom.xml
中添加以下内容
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
....
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<webResources>
<resource>
<directory>${project.basedir}/src/main/resources/</directory>
</resource>
</webResources>
<warName>${project.artifactId}</warName>
</configuration>
</plugin>
</plugins>
</build>
</project
packaging 指定打包方式为 war 包,servlet-api 是开发 servlet 程序的基础依赖包,scope 必须声明为 provided,表示运行时依赖由运行环境提供,打包需要借助 maven-war-plugin 工具进行打包。
- 在
resources
目录下创建WEB-INF
目录,并在WEB-INF
目录下创建web.xml
文件,名称不能改。
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5" xmlns="http://java.sun.com/xml/ns/javaee">
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>com.demo.service.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
- 新建 Servlet 类
package com.demo.service;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @Description:
* @author: jianfeng.zheng
* @since: 2020/7/7 21:31 PM
* @history: 1.2020/7/7 created by jianfeng.zheng
*/
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {String name=req.getParameter("username");
String content="hello"+name;
resp.getOutputStream().write(content.getBytes("utf-8"));
resp.getOutputStream().flush();
}
}
此时的目录结构如下:
.
├── hello-servlet.iml
├── pom.xml
└── src
└── main
├── java
│ └── com
│ └── demo
│ └── service
│ └── HelloServlet.java
└── resources
└── WEB-INF
└── web.xml
- 在控制台执行 maven 打包命令
mvn clean package
- 将
target
目录下 war 包复制到 tomcat webapps 目录下。
参考
- IntelliJ IEDA 开发 servlet
正文完