写一个Servlet需要的步骤
//1.写servlet
//2.web.xml 部署servlet
//3.启动tomcat 访问servlet
//Servlet第一种写法
public class ServletLife implements Servlet{
//销毁Servlet实例 释放内存
//reload 该servlet 2 关闭tomcat 3关机
@Override
public void destroy() {
// TODO Auto-generated method stub
System.out.println("destroy");
}
@Override
public ServletConfig getServletConfig() {
// TODO Auto-generated method stub
return null;
}
@Override
public String getServletInfo() {
return "";
}
//初始化servlet 只会被调用一次 当用户第一次访问该servlet被调用
@Override
public void init(ServletConfig arg0) throws ServletException {
// TODO Auto-generated method stub
System.out.println("init");
}
//该函数处理业务逻辑 业务逻辑代码放在这个方法中 用户每一次访问该servlet就会调用一次service方法
//req获取客户端的信息
// rsp用于向客户端返回信息
@Override
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("service");
//从res中得到printWriter
PrintWriter pw = res.getWriter();
pw.print("Hello World");
}
}
部署Servlet web.xml
<servlet>
<servlet-name>hello</servlet-name>
<!-- servlet路径 包名加上类名 -->
<servlet-class>com.gac.test.ServletLife</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<!-- 浏览器中的输入的访问该servlet url -->
<url-pattern>/gac</url-pattern>
</servlet-mapping>
Servlet第二种写法
//第二种servlet 开发 继承 GenericServlet
public class GenericServletDemo extends GenericServlet{
//只需要重写service 方法即可
@Override
public void service(ServletRequest req, ServletResponse rep)
throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter pw = rep.getWriter();
pw.println("Hello world generic");
}
}
Servlet第三种写法
/第三种Servlet开发方法 继承httpServlet
//需要重写doGet doPost 方法
//表单提交数据get post请求区别
//get提交数据会在地址栏中 显示安全性低
//get提交数据内容大小小于post 理论上 get 小于2k post 不受限制 建议不要大于64k
//响应速度快 get 服务器立即处理 post 形成一个队列请求
public class HttpServletDemo extends HttpServlet{
//处理get请求
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
//业务逻辑
PrintWriter pw = resp.getWriter();
pw.println("Http Servlet");
}
//处理post请求
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
this.doGet(req, resp);
}
}