1. 左上角点击 File -> New -> Project -> 新建一个 Web Application 项目
2. 设置项目名称:FirstServlet
3. 新建一个servlet文件:HelloWorld
4. 添加依赖的 Tomcat 下的 Servlet 库
5. 编写 HelloWorld.java 代码
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorld extends HttpServlet {
private String message;
public void init() throws ServletException
{
// 初始化
message = "Hello, First Servlet!";
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 设置:响应内容类型
response.setContentType("text/html");
// 输出文本
PrintWriter out = response.getWriter();
out.write("<h1> " + message + " </h1>");
}
}
6. 编写web.xml配置文件
<?xmlversion="1.0"encoding="UTF-8"?>
<web-appxmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaeehttp://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/demo</url-pattern>
</servlet-mapping>
</web-app>
7. 部署 Tomcat ,并调试运行
8. 成功运行(http://localhost:8080/demo)