标签:inf 释放 get请求 http int eric 关机 writer webapps
1.实现Servlet接口的方式
import javax.servlet.*;
public class Hello implements Servlet{
//初始化Servlet
//该函数只会被调用一次(当用户第一次访问该Servlet时被调用)
public void init(ServletConfig parm1) throws ServletException {
System.out.println("init it");
}
public ServletConfig getServletConfig() {
return null;
}
//这个函数用于处理业务逻辑
//程序员应当把业务逻辑代码写在这里
//当用户每访问一次该servlet时候都会调用
//reg:用于获得客户端(浏览器)的信息
//res:用于向客户端(浏览器)返回信息
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
System.out.println("service it");
//从res中得到printwriter
PrintWriter pw = res.getWriter();
pw.println("hello,world!");
}
public String getServletInfo() {
return "";
}
//销毁servlet实例(释放内存)
//1.reload该servlet(webApps)2.关闭tomcat3.关机 (这三种操作都会销毁Servlet)
public void destroy() {
System.out.println("destroy!");
}
}
-------------------------------------------------------------------------------------------------------------------------------------------
2.通过继承GenericServlet
import javax.servlet.GenericServlet;
import javax.servlet.*;
public class HelloGeneric extends GenericServlet{
//重写service方法即可
public void service(ServletRequest req,ServletResponse res){
//返回hello,world!generic
try{
PrintWriter pw = res.getWriter();
pw.println("hello,world!generic");
}catch(Exception ex){
ex.printStackTrace();
}
}
}
--------------------------------------------------------------------------------------------------------------------------------------------
3.通过继承HttpServlet
import javax.servlet.http.*;
public class HelloHttp extends HttpServlet{
//处理get请求
//req:用于获得客户端(浏览器)的信息
//res:用于向客户端(浏览器)返回信息
public void doGet(HttpServletRequest req,HttpServletResponse res){
//业务逻辑
try{
PrintWriter pw = res.getWriter();
pw.println("hello,world!HttpServlet");
}catch(Exception ex){
ex.printStackTrace();
}
}
//处理post请求
//req:用于获得客户端(浏览器)的信息
//res:用于向客户端(浏览器)返回信息
public void doPost(HttpServletRequest req,HttpServletResponse res){
this.doGet(req,res);
}
}
标签:inf 释放 get请求 http int eric 关机 writer webapps
原文地址:https://www.cnblogs.com/daemon94011/p/9298043.html