实现第一个Servlet程序(一)
程序员文章站
2022-06-03 09:59:37
...
(一)Servlet工作原理示意图
(二)在Eclipse中创建Servlet应用程序的结构
(三)在src目录下创建com.haha包,并在包下创建Demo类
package com.haha;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/Demo")
public class Demo extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().append("Served at: ").append(request.getContextPath());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
(四)使用xml文件配置Demo类
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>ServletDemo</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<!-- servlet-name名任意取 -->
<servlet-name>haha</servlet-name>
<!--servlet-class填写(包名.类名) -->
<servlet-class>com.haha.Demo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>haha</servlet-name>
<!-- Servlet资源路径名任意填写 -->
<url-pattern>/Demos</url-pattern>
</servlet-mapping>
</web-app>
(五)Servlet的多重映射
Servlet的多重映射指同一个Servlet可以被映射成多个虚拟路径,因此客户端可以通过多个路径对同一个Servlet进行访问。
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>ServletDemo</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<!-- servlet-name名任意取 -->
<servlet-name>haha</servlet-name>
<!--servlet-class填写(包名.类名) -->
<servlet-class>com.haha.Demo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>haha</servlet-name>
<!-- Servlet的多重映射 -->
<url-pattern>/Demos</url-pattern>
<url-pattern>/abc</url-pattern>
<url-pattern>/abcde</url-pattern>
</servlet-mapping>
</web-app>
(六)运行结果
上一篇: 为什么说PHP是个贫民区
下一篇: 简介Django中内置的一些中间件