servlet代码结构
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class testServlet extends HttpServlet{
public void init() throws ServletException{
}
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException{
}
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException{
}
public void doPut(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException{
}
public void Delete(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException{
}
public void destroy(){
super.destroy();
}
}
一个简单的servlet程序
在编写servlet时不必重写所有方法,只需要重写所需代码即可。
例如:处理HTTP Get请求,只需重写doGet方法
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletREsponse;
public class SimpleServlet extends HttpServlet{
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException{
response.setContentTpe("text/html");
PrintWriter out = response.getWriter();
out.println("this is a servlet.");
}
}