该Servlet实现如下功能:当用户通过浏览器访问该Servlet时,该Servlet向客户端浏览器返回一个HTML页面。在Edit-Plus里输入以下内容,并编译,得到ShowHtml.class.
ShowHtml.java
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;
public class HelloWorld extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Hello World</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Hello World!</h1>");
out.println("</body>");
out.println("</html>");
}
}
在web.xml文件中添加:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems,Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<servlet>
<servlet-name>HtmlServlet</servlet-name>
<servlet-class>com.JavaBean.ShowHtml</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HtmlServlet</servlet-name>
<url-pattern>/htmlservlet</url-pattern>
</servlet-mapping>
</web-app>
打开浏览器,输入:
http://localhost:8080/htmlservlet