1.新建项目
菜单->File->New->Project->勾上 Web Application(3.1)->OK
2.项目目录
3.新建目录
右键WEB-INF->New->Directory 新建两个目录:
classes和lib目录
4.新建HelloServlet
选中src目录,然后右键鼠标->New->Servlet->输入HelloServlet
import java.io.IOException;
import java.util.Date;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HelloServlet extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse response){
try {
response.getWriter().println("<h1>Hello Servlet!</h1>");
response.getWriter().println(new Date().toLocaleString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
5.导入jar包
- 点击 project structure
- 点击 Libraries
- 点击加号,选中Java
- 指定E:\project\j2ee\web\WEB-INF\lib\servlet-api.jar
- 点击ok
这个行为做过之后服务端HelloServlet的编译错误就消失了
6.指定输出目录
- 打开project structure
- 设置 project complier output 为:
E:\project\j2ee\web\WEB-INF\classes
7.修改web.xml
在web.xml中添加/hello路径的映射
<?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_3_1.xsd"
version="3.1">
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>