package Excise;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//继承类HttpServlet
public class HelloWorld extends HttpServlet {
// 处理客户端的Get请求
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 设置HTTP响应头的Content-Type字段值
response.setContentType("text/html");
// 获得用于输出消息的PrintWriter对象
PrintWriter out = response.getWriter();
out.println("<b>Hello World!</b>"); // 向客户端发送消息
}
}
运行结果:
相应的web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
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">
<display-name></display-name>
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>Excise.HelloWorld</servlet-class>
</servlet>
<!-- 定义Servlet映射信息 -->
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<!-- 指定在浏览器中访问的Servlet的URL -->
<url-pattern>/servlet/HelloWorld</url-pattern>
</servlet-mapping>
<!-- 配置欢迎页 -->
<welcome-file-list>
<!-- 指定index.jsp页面为系统默认的访问页面 -->
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>