1.在eclipse中配置tomcat,参考上一边文章,建立的web项目tomcatWeb目录结构
2.添加Servlet处理类
3. 实现doGet()与doPost()方法:
<span style="font-size:18px;">public class HttpServletDemo extends HttpServlet { /** * */ private static final long serialVersionUID = 4230239235404655360L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("text/html;charset=GB2312"); PrintWriter printWriter = response.getWriter(); // printWriter.print("hello, china"); String title = "HelloServlet"; String heading1 = "HelloServlet的doGet方法的输出:"; printWriter = response.getWriter(); printWriter.print("<HTML><HEAD><TITLE>" + title + "</TITLE>"); printWriter.print("</HEAD><BODY>"); printWriter.print(heading1); printWriter.println("<h1><p>:您好</h1>"); printWriter.print("</body></HTML>"); printWriter.write(""); printWriter.flush(); printWriter.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { doGet(request, response); } }</span>4. 在web.xml中配置servlet
<span style="font-size:18px;"> <servlet> <servlet-name>TomcatWeb</servlet-name> <servlet-class>tomcat.servlet.HttpServletDemo</servlet-class> </servlet> <servlet-mapping> <servlet-name>TomcatWeb</servlet-name> <url-pattern>/servlet/HttpServletDemo</url-pattern> </servlet-mapping></span>
方式1:右击项目--run as - run on server - 选择配置好的tomcat容器
方式2:右击运行
6. 在浏览器上输入:http://localhost:8080/TomcatWeb/servlet/HttpServletDemo,即可看到