1 package myservlet; 2 3 import java.io.IOException; 4 import javax.servlet.ServletException; 5 import javax.servlet.annotation.WebServlet; 6 import javax.servlet.http.HttpServlet; 7 import javax.servlet.http.HttpServletRequest; 8 import javax.servlet.http.HttpServletResponse; 9 10 /** 11 * Servlet implementation class Dispatcher 12 */ 13 @WebServlet("/Dispatcher") 14 public class Dispatcher extends HttpServlet { 15 private static final long serialVersionUID = 1L; 16 17 /** 18 * @see HttpServlet#HttpServlet() 19 */ 20 public Dispatcher() { 21 super(); 22 // TODO Auto-generated constructor stub 23 } 24 25 /** 26 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 27 */ 28 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 29 // TODO Auto-generated method stub 30 response.getWriter().append("Served at: ").append(request.getContextPath()); 31 } 32 33 /** 34 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 35 */ 36 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 37 // TODO Auto-generated method stub 38 doGet(request, response); 39 } 40 41 }View Code
2.將創建好的Servlet配置到web.xml
1 <servlet> 2 <servlet-name>dispatcher</servlet-name> 3 <servlet-class>myservlet.DispatcherServlet</servlet-class> 4 </servlet> 5 6 <servlet-mapping> 7 <servlet-name>dispatcher</servlet-name> 8 <url-pattern>/</url-pattern> 9 </servlet-mapping>View Code
3.將項目部署到tomcat下即可。
總結說明:
1.創建Servlet需繼承Tomcat下servlet-api.jar下的類庫
2.web.xml是項目的配置文件,需要將Servlet配置到該配置文件下
3.Servlet是項目入口
(初學者記錄學習中的總結,希望各位大牛進行點評指正,謝謝大家!)