Servlet三种实现方式:实现Servlet接口,继承GenericServlet ,继承HttpServlet。
1、实现Servlet接口:
import javax.servlet.*; import java.io.*; public class Hello implements Servlet{ //执行条件:reload,关闭tomcat,关机 public void destroy() { // TODO Auto-generated method stub System.out.println("destroy it"); } @Override public ServletConfig getServletConfig() { // TODO Auto-generated method stub return null; } @Override public String getServletInfo() { // TODO Auto-generated method stub return null; } //初始化,用户第一次访问时调用 public void init(ServletConfig arg0) throws ServletException { // TODO Auto-generated method stub System.out.println("init it"); } //业务处理 public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { // TODO Auto-generated method stub System.out.println("service it"); res.getWriter().println("hell,world"); } }
2、继承GenericServlet :
import javax.servlet.*; import java.io.*; public class HelloGen extends GenericServlet{ @Override public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { // TODO Auto-generated method stub res.getWriter().println("Hello,gen"); } }
3、继承HttpServlet:
import javax.servlet.*; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; public class HellHttp extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res) { try { res.setContentType("text/html;charset=gbk"); res.getWriter().println("hello,HttpServlet");; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void doPost(HttpServletRequest req,HttpServletResponse res) { this.doGet(req, res); } }
使用Servlet需要对其在web.xml中进行配置,对于上面的三种方式要在web.xml中添加如下信息:
<!-- JSPC servlet mappings start--> <servlet> <servlet-name>hello</servlet-name> <servlet-class>Hello</servlet-class> </servlet> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> <!-- JSPC hellogen--> <servlet> <servlet-name>hellogen</servlet-name> <servlet-class>HelloGen</servlet-class> </servlet> <servlet-mapping> <servlet-name>hellogen</servlet-name> <url-pattern>/hellogen</url-pattern> </servlet-mapping> <!-- JSPC hellohttp--> <servlet> <servlet-name>hellohttp</servlet-name> <servlet-class>HellHttp</servlet-class> </servlet> <servlet-mapping> <servlet-name>hellohttp</servlet-name> <url-pattern>/hellohttp</url-pattern> </servlet-mapping> <!-- JSPC servlet mappings end-->
启动tomcat,输入正确地址,即可在浏览器中访问了。