通过继承GenericServlet抽象类。只需要重写service()方法即可。(这个知识点了解即可)
1 package cn.servlet; 2 3 import java.io.IOException; 4 import java.io.PrintWriter; 5 6 import javax.servlet.GenericServlet; 7 import javax.servlet.ServletException; 8 import javax.servlet.ServletRequest; 9 import javax.servlet.ServletResponse; 10 11 public class MyGenericServlet extends GenericServlet{ 12 13 @Override 14 public void service(ServletRequest req, ServletResponse resp) 15 throws ServletException, IOException { 16 resp.setCharacterEncoding("GBK"); 17 resp.getWriter().println("中文!"); 18 resp.getWriter().print("hello,我继承了GenericServlet"); 19 20 } 21 }
XML部署:
<servlet> <servlet-name>mygenericservlet</servlet-name> <servlet-class>cn.servlet.MyGenericServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>mygenericservlet</servlet-name> <url-pattern>/servlet/MyGenericServlet</url-pattern> </servlet-mapping>