使用 IntelliJ IDEA创建Servlet 项目
使用 IntelliJ IDEA 创建 Servlet 项目
0x1、新建一个 Web Application 项目
0x2 设置项目名称:ServletPro
0x3 新建一个servlet文件:HelloWorld
0x4 添加依赖的 Tomcat 下的 Servlet 库
选择Tomcat下的servlet-api包。
0x5 编写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>");
}
}
0x6 编写web.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<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>
0x7 部署 Tomcat ,并调试运行
详见Mac IDEA开发JavaWeb一文中为项目配置Tomcat