使用Java类实现Servlet接口,完成FirstServlet的编写(需在web.xml中配置映射路径)
时间: 2023-05-18 11:05:36 浏览: 114
JavaWeb开发技术-实现Servlet虚拟路径的映射.pptx
以下是一个简单的FirstServlet示例:
```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 FirstServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
response.getWriter().println("<html><body><h2>Hello World!</h2></body></html>");
}
}
```
在web.xml中配置映射路径:
```xml
<servlet>
<servlet-name>FirstServlet</servlet-name>
<servlet-class>com.example.FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FirstServlet</servlet-name>
<url-pattern>/first</url-pattern>
</servlet-mapping>
```
这将把FirstServlet映射到/first路径。当用户访问/first时,将调用doGet方法并输出“Hello World!”消息。
阅读全文