Servlet笔记

  Java Servlet 是运行在 Web 服务器或应用服务器上的程序,它是作为来自 Web 浏览器或其他 HTTP 客户端的请求和 HTTP 服务器上的数据库或应用程序之间的中间层。

  使用 Servlet,您可以收集来自网页表单的用户输入,呈现来自数据库或者其他源的记录,还可以动态创建网页。

Servlet架构:

  • Servlet对象是由服务器创建(反射)

  • request与response对象也是由tomcat服务器创建

  • service()方法也是服务器调用的

serrvlet生命周期方法:

  • init(ServletConfig config) (第一次请求时,会初始化调用)
  • service(ServletRequest req, ServletResponse res)(任何请求都会调用)
  • destroy()(服务器关闭,进行销毁)

ServletContext:域对象

ServletContext: 是一个全局对象, 上下文对象.

  • 作为域对象存取数据,让Servlet共享(掌握)
  • 获得文件MIME类型(文件下载)(了解)
  • 获得全局初始化参数(了解)
  • 获取web资源路径 ,可以将Web资源转换成字节输入流(掌握)
存: 
String name = "周杰"; //1. 获取ServletContext对象 ServletContext servletContext = getServletContext(); //2. 往容器ServletContext中存值 servletContext.setAttribute("name",name);
-------------------------------------------------------------------
取:

//1. 获取那个容器ServletContext
ServletContext servletContext = getServletContext();
//2. 从容器ServletContext中获取数据
String name = (String) servletContext.getAttribute("name");

System.out.println("在ServletDemo02中获取的name是:" + name);

获得文件mime-type:

String file01 = "a.mp3";
String mimeType01 = getServletContext().getMimeType(file01);

获取web资源路径:

 ServletContext servletContext = gestSServletContext();域对象
//getRealPath(String file); 获得文件的绝对路径
InputStream is = servletContext.getResourceAsStream("mm.jpg");

原文地址:https://www.cnblogs.com/YwhsR0129/p/13814475.html