1 实现Servlet
接口,然后实现接口中的五个方法,代码为:
public class Hello implements Servlet{ //该函数用于初始化servlet,类似于类的构造函数,该函数只会被调用一次 public void init(ServletConfig parm1) throws ServletException { System.out.println("init it!"); } public ServletConfig getServletConfig() { // TODO: Add your code here return null; } //这个函数用于处理业务逻辑 //当用户每访问servlet时,都会调用 //req:用于获得客户端(浏览器)信息 //res:用于向客户端(浏览器)返回信息 public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { //从res中得到PrintWriter System.out.println("Service it"); PrintWriter pw = res.getWriter(); pw.println("Hello world!"); } public String getServletInfo() { return ""; } //销毁,释放内存,三种方式会触发destroy //1. reload该servlet(webApps) 2. 关闭tomcat 3.关机 public void destroy() { System.out.println("destroy it!"); } }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
2 继承GenericServlet
,只需要实现一个方法:service
public class HelloGen extends GenericServlet{ //重写一个方法service即可 public void service(ServletRequest req, ServletResponse res){ //返回Hello world, generic try{ PrintWriter pw = res.getWriter(); pw.println("Hello generic"); } catch(Exception e){ e.printStackTrace(); } } }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
3 继承HttpServlet
,复写doGet
和doPost方法
public class HelloHttp extends HttpServlet{ //处理get请求 public void doGet(HttpServletRequest req, HttpServletResponse res){ //业务逻辑 try{ PrintWriter pw = res.getWriter(); pw.println("hello, Http"); } catch (Exception e){ e.printStackTrace(); } } public void doPost(HttpServletRequest req, HttpServletResponse res){ this.doGet(req,res); } }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
当然,每次写好代码之后,需要在web.xml
中注册新的servlet
web.xml
:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0" metadata-complete="true"> <display-name>Welcome to Tomcat</display-name> <description> Welcome to Tomcat </description> //第一种方式需要加入的部分 <servlet> <servlet-name>hello</servlet-name> <servlet-class>com.thorin.Hello</servlet-class> </servlet> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/thorin</url-pattern> </servlet-mapping> //第二种方式需要加入的部分 <servlet> <servlet-name>hellogen</servlet-name> <servlet-class>com.thorin.HelloGen</servlet-class> </servlet> <servlet-mapping> <servlet-name>hellogen</servlet-name> <url-pattern>/hellogen</url-pattern> </servlet-mapping> //第三种方式需要加入的部分 <servlet> <servlet-name>hellohttp</servlet-name> <servlet-class>com.thorin.HelloHttp</servlet-class> </servlet> <servlet-mapping> <servlet-name>hellohttp</servlet-name> <url-pattern>/hellohttp</url-pattern> </servlet-mapping> </web-app>
文章来源: Java Servlet实现的三种方式