Servlet有三种实现方式:
* 实现Servlet接口
* 继承GenericServlet类
* 继承HttpServlet类
1.实现servlet类
package com.vc.servlet;
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;
public class HelloWorldServlet implements Servlet{
//释放内存
//1. reload
//2. 关闭TomCat
//3. 关机
public void destroy() {
// TODO Auto-generated method stub
System.out.println("destroy it");
}
public ServletConfig getServletConfig() {
// TODO Auto-generated method stub
return null;
}
public String getServletInfo() {
// TODO Auto-generated method stub
return null;
}
//该 函数用于初始化,只会被调用一次(当用户第一次访问Servlet时,被调用)
public void init(ServletConfig arg0) throws ServletException {
// TODO Auto-generated method stub
System.out.println("init it");
}
//用于处理业务逻辑,应该把业务逻辑代码写在该方法中
//会被多次调用,当用户每访问一次时就会被调用一次
//request用于获取客户端的信息
//response用户向客户端返回信息
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("service it");
PrintWriter printWriter=response.getWriter();
printWriter.println("<h1>"+"hello,world"+"</h1>");
}
}
2.继承 genericservlet
package com.vc.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
@SuppressWarnings("serial")
public class HelloWorldGenericServlet extends GenericServlet {
@Override
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
try{
PrintWriter printWriter=response.getWriter();
printWriter.println("<h1>hello,generic world.!!!</h1>");
}catch(Exception e){
e.printStackTrace();
}
}
}
3.继承httpServlet
package com.vc.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@SuppressWarnings("serial")
public class HelloWorldHttpServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter printWriter=resp.getWriter();
printWriter.println("<h1>Hello World!</h1>");
}
}