方法一:实现Servlet接口:全部都要重写方法
package com.company.project;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
/**
* 这是我的第一个Servlet程序
*/
public class Test01 implements Servlet {
@Override
public void destroy() {
System.out.println("调用了销毁内存.");
}
@Override
public ServletConfig getServletConfig() {
return null;
}
@Override
public String getServletInfo() {
return null;
}
@Override
public void init(ServletConfig arg0) throws ServletException {
System.out.println("调用了servlet的初始化方法");
}
int i = 0;
@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
i++;
System.out.println("第" + i + "调用了servlet的service方法");
PrintWriter pw = res.getWriter();
pw.print("Hello Lee.");
}
}
方法二:继承GenericServlet:重写servlet方法
package com.company.project;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class Test01 extends GenericServlet {
private static final long serialVersionUID = 6306669133189570823L;
@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
try {
res.setContentType("text/html; charset=GBK");
PrintWriter pw = res.getWriter();
pw.println("这是用GenericServlet父类的方法实现servlet.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
方法三:继承HttpServlet
package com.company.project;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Test01 extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest req, HttpServletResponse res) {
res.setContentType("text/html; charset=GBK");
try {
PrintWriter pw = res.getWriter();
pw.print("这是第三种方法开发servlet.");
} catch (IOException e) {
e.printStackTrace();
}
}
public void doPost(HttpServletRequest req, HttpServletResponse res) {
this.doGet(req, res);
}
}