[1.Servlet基础.pptVIP

  • 4
  • 0
  • 约6.18千字
  • 约 23页
  • 2017-01-07 发布于北京
  • 举报
[1.Servlet基础

Servlet基础 主讲:许松伟 议程 Servlet的功能 使用ECLIPSE开发Servlet步骤 Servlet的API结构,详解 servlet的生命周期 Tomcat安装与结构 Servlet的功能 功能 读取客户程序发送来的显式数据(表单数据) 读取客户程序发送来的隐式数据(请求报头) 生成相应的结果 发送显式的数据给客户程序(HTML) 发送隐式的数据给客户程序(状态代码和响应报头 使用Eclipse开发Servlet步骤 Servlet生命周期 1、客户发出请求—Web 服务器转发到Web容器Tomcat; 2、Tomcat主线程对转发来用户的请求做出响应创建两个对象:HttpServletRequest和HttpServletResponse; 3、从请求中的URL中找到正确Servlet,Tomcat为其创建或者分配一个线程,同时把2创建的两个对象传递给该线程; 4、Tomcat调用Servlet的servic()方法,根据请求参数的不同调用doGet()或者doPost()方法; 5、假设是HTTP GET请求,doGet()方法生成静态页面,并组合到响应对象里; 6、Servlet线程结束,Tomcat将响应对象转换为HTTP响应发回给客户,同时删除请求和响应对象。 Servlet的生命周期:Servlet类加载(对应3步);Servlet实例化(对应3步);调用init方法,且只调用一次(对应3步);调用service()方法(对应4、5步);;若服务器关闭或者重启则调用destroy()方法。 Servlet API GenericServlet GenericServlet类定义了一个普通的、协议无关的Servlet,实现了Servlet和ServletConfig等接口。 GenericServlet类简化了Servlet的开发,并提供了生命周期方法的简单版本。开发一个普通的Servlet必须重载service()方法。 HttpServlet HttpServlet 是从GenericServlet 继承而来,因此它具有GenericServlet 类似的方法和对象,是我们使用Servlet编程经常用到的包,它支持HTTP 的post 和 get 等方法。 ServletRequest getAttribute getContentType getInputStream getParameter getParameterNames getParameterValues getRemoteAddr getRemoteHost getRemotePort setAttribute HttpServletRequest getCookies getHeader getRequestURI getQueryString getMethod ServletContext ServletContext Web应用的服务器端组件的共享内存,可以存放共享数据 通过该接口可以存储和检索属性,获得Servlet容器和运行时上下文,把事件记录到应用程序的日志文件等. ServletCotext ctx = this.getServletContext(); ctx.setAttribute(“username”,”XuSongwei”); String name = (String)ctx.getAttribute(“username”); ctx.removeAttribute(“username”); 方法: setAttribute getAttribute removeAttribute getAttributeNames 发送请求到其它资源 转发(forwarding) 使用RequestDispatcher接口 直接服务器端操作,客户端浏览器地址栏没有改变. 例子: ///通过ServletContext转发 if(!user.isRegistered) { ServletContext ctx = this.getServletContext(); RequestDispatcher dispatcher = ctx.getRequestDispatcher(“/mainServlet”);//必须以“/”开始 dispatcher.forward(request, response); } //通过request转发 if(!user.isRegistered) { RequestDispatcher dispatcher = request.getRequestDispatcher(“/mainServlet”);//不一定以“/”开始 dispatcher

文档评论(0)

1亿VIP精品文档

相关文档