1、创建web工程:helloservlet
2、创建代码:
(1)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 { private String message; public void init() throws ServletException { // 执行必需的初始化 message = "Hello Servlet"; } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 设置响应内容类型 response.setContentType("text/html"); // 实际的逻辑是在这里 PrintWriter out = response.getWriter(); out.println("" + message + "
"); } public void destroy() { // 什么也不做 }}
(2)web.xml
index.jsp HelloWorld HelloWorld HelloWorld /HelloWorld
3、通过MyEclipse部署到Tomcat,然后再浏览器访问:
4、运行效果