如图创建web工程后,在Java Resources 的src 下面创建包和servlet文件。
test.java的代码如下
1 package com.weeklyReport.www; 2 3 import java.io.IOException; 4 import java.io.PrintWriter; 5 6 import javax.servlet.ServletException; 7 import javax.servlet.annotation.WebServlet; 8 import javax.servlet.http.HttpServlet; 9 import javax.servlet.http.HttpServletRequest; 10 import javax.servlet.http.HttpServletResponse; 11 12 /** 13 * Servlet implementation class test 14 */ 15 @WebServlet("/test") 16 public class test extends HttpServlet { 17 private static final long serialVersionUID = 1L; 18 public String message; 19 public void init() throws ServletException { 20 // 21 message = "Hello world!"; 22 } 23 /** 24 * @see HttpServlet#HttpServlet() 25 */ 26 public test() { 27 super(); 28 // TODO Auto-generated constructor stub 29 } 30 31 /** 32 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 33 */ 34 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 35 // TODO Auto-generated method stub 36 response.setContentType("text/html"); 37 PrintWriter out = response.getWriter(); 38 out.println("<h1>"+message+"</h1"); 39 } 40 41 /** 42 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 43 */ 44 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 45 // TODO Auto-generated method stub 46 doGet(request, response); 47 } 48 49 }
修改WebContent内的web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <display-name>WeeklyReport</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>test</servlet-name> <servlet-class>test</servlet-class> </servlet> <servlet-mapping> <servlet-name>test</servlet-name> <url-pattern>/test</url-pattern> </servlet-mapping> </web-app>
右键点击test,java,在tomcat上运行后结果如图