web development (five) ServletContext objects, functions, annotations development

1.1 What is ServletContext

ServletContext: context object of Servlet . Servlet ServletContext object to the content before and after the know. There is a web project there is a ServletContext object (web project object). Create a separate ServletContext object for each item in the web server start.
ServletContext itself is an interface, the interface is implemented by the class object Tomcat engine
Obtaining:

	方法1.先获取ServletConfig对象,在通过ServletConfig对象中的方法getServletContext获取
		ServletConfig config = getServletConfig();
		ServletContext context1 = config.getServletContext();
	方法2.在父类中GenericServlet中直接封装好了获取ServletContext对象的方式,我们可以直接使用
		ServletContext getServletContext()
		ServletContext context2 = getServletContext()

extends HttpServlet, HttpServlet extends GenericServlet, in a method of packaging in GenericServlet getServletContext (). In fact, the above two methods are essentially the same.
Here Insert Picture Description

Action 1.2 ServletContext object

1.2.1 used to obtain information web project

Because a web project is only a ServletContext object, the object of the relevant contents of the entire project is to understand.

method return value description
getMimeType(String file) String Gets the MIME type of file
getContextPath() String Project name acquisition request web project
getInitParameter(String name) String Get initialization parameters web project
getInitParameterNames () Enumeration Get initialization parameters web project (the return type is enum)
for example:
package com.ccc.demo01ServletContext;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

@WebServlet(urlPatterns = "/Context1")
public class Demo01ServletContext extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

	    //在父类中GenericServlet中直接封装好了获取ServletContext对象的方式,我们可以直接使用
        ServletContext context = getServletContext();
        
        //String getMimeType(String file) 获取文件的MIME类型
        String aMimeType = context.getMimeType("a.txt");
        System.out.println(aMimeType);	//text/plain

        //String getContextPath() 获取web项目请求工程名
        String contextPath = context.getContextPath();
        System.out.println(contextPath);//    /day12_web

        //String getInitParameter(String name) 获取web项目的初始化参数值
        String a = context.getInitParameter("a");
        System.out.println(a);	//123

        //Enumeration<E> getInitParameterNames() 获取web项目的所有初始化参数的名称
        Enumeration<String> en = context.getInitParameterNames();
        while (en.hasMoreElements()){
            String name = en.nextElement();
            String value = context.getInitParameter(name);
            System.out.println(name+"\t"+value);
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}

1.2.2 obtain any resources under WEB application absolute path

  • Method: String getRealPath ( "resources relative path"), returns the resources of the absolute path (path in Tomcat server, including the drive letter)
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      //context对象,方法getRealPath获取任意资源的绝对路径
      //获取web目录下的a.txt绝对路径
      String aPath = context.getRealPath("a.txt");
      System.out.println(aPath);
  
      //获取web目下WEB-INF目录下的b.txt绝对路径
      String bPath = context.getRealPath("WEB-INF/b.txt");
      System.out.println(bPath);
  
      //获取src目录下的c.txt绝对路径
      String cPath = context.getRealPath("WEB-INF/classes/c.txt");
      System.out.println(cPath);
  
      //获取WEB03 module下的d.txt绝对路径,获取不到,因为只有发布在Tomcat中的文件,才能获取到。
      //此时文件存在根目录下,不会发布到Tomcat中(即是在src文件夹之下),所以也就获取不到。
}

Note that this method does not itself determine the authenticity of the document. Only use string concatenation (path + project directory), and the file exists or not, and this path is correct, it does not judge.
The web project is to be published in Tomcat, it refers to the relative path is relative to the Tomcat, Java and Java project is relative to the root directory.

1.2.3 domain object

ServletContext object is a container that can store data
objects have scope problem, the entire scope ServletContext WEB application
Here Insert Picture Description

  • Storing data to domain object: setAttribute (String key, Object value)
  • Remove the data domain objects: Object getAttribute (String key)
  • Remove the domain object data: removeAttribute (String key)

The above three methods (storage, extraction, removal) is equally applicable to other domain objects

note:

ServletContext object scope is the entire web project, the web project where all can access the Servlet

:( Here is a scope of expansion in descending rank)

  1. The ServletContext : when the entire web project scope; that is, the web project where all Servlet can access.
  2. The Session : As long as it does not close the browser effectively. Even different virtual addresses can also be accessed. But only retained for 30 minutes.
  3. Request:只要是地址栏不变,不刷新,就有效,即只能请求一次。转发也有效。但是重定向就无效了。因为转发的地址栏不变,重定向的地址栏发生变化了。
  4. PageContext:只在jsp本页面有效。
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      /*
       * 域对象的存储和取出
       */
      ServletContext context = getServletContext();
      //域对象存储数据,键值对(在该项目的任意一个servlet中都能获取到该键值对)
      context.setAttribute("heima","java");
      //取出域对象存储的键值对
      Object value = context.getAttribute("heima");
      System.out.println(value);
      //移除域对象数据:  void removeAttribute(String key)
      context.removeAttribute("heima");
}

1.2.4 init方法只会在创建Servlet对象的时候执行一次

利用这个特点,我们可以先将init方法重写,然后把一些需要只执行一次的代码放到init方法里面。但是切记:一定要重写空参数的init方法,因为tomcat在调用完带参init方法之后,会默认调用空参数的(在源码中)。
以下是源码:
Here Insert Picture Description
源码tomcat在调用完带参init方法之后,会调用空参数init方法。

@WebServlet(urlPatterns = "/context5")
public class Demo05ServletContext extends HttpServlet {
    //重写父类GenericServlet中init方法
    /*
        以后我们重写init方法,不要重写带ServletConfig的init方法
        重写空参数的init方法-->tomcat在调用完带参init方法之后,会调用空参数的
     */
    @Override
    public void init() throws ServletException {
        System.out.println("init方法只会在创建Servlet对象的时候执行一次");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取ServletContext域对象
        ServletContext context = getServletContext();
        System.out.println(context);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}

引发问题:ServletContext对象的空指针异常

Here Insert Picture Description

产生原因:

重写父类GenericServlet中的init的带参方法后。在程序运行的时,它就会优先调用重写后的这个init方法。

解决方案:

以后我们重写init方法时,不要重写带参数(ServletConfig config)的方法。要重写空参数的init方法。因为Tomcat(源代码)在调用完有参数的init方法之后,就会默认调用其空参的方法。所有我们传递一个空参数的init方法(重写)之后,就相当于传递给了底层的有参方法。

1.3 注解开发取代web.xml(修改注解方式Servlet的模版)

Here Insert Picture Description
WebServlet in parentheses after, urlPatterns assignment is client access virtual path . At this point you do not have to configure the web.xml.
When ready to use notes and use web.xml file, it will conflict (virtual paths the same situation). If the virtual path to change is not the same, you can use two ways to access. This feature is only Java6 and later versions is supported.
Remember After modifying the template, the new servlet dialog box, plus front Name "/" check box to the bottom left corner ✔.

Guess you like

Origin blog.csdn.net/qq_45083975/article/details/92251200