写一个servlet项目
时间: 2024-05-11 17:17:55 浏览: 59
servlet项目
好的,下面是一个简单的servlet项目示例:
1. 首先创建一个名为`HelloWorldServlet`的Java类,继承自`javax.servlet.http.HttpServlet`。
```java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HelloWorldServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().write("Hello World!");
}
}
```
2. 在`web.xml`中配置servlet:
```xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" 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_3_0.xsd" version="3.0">
<display-name>HelloWorldServlet</display-name>
<servlet>
<servlet-name>HelloWorldServlet</servlet-name>
<servlet-class>HelloWorldServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorldServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
```
3. 构建并运行项目,访问`http://localhost:8080/HelloWorldServlet/hello`即可看到`Hello World!`的输出。
阅读全文