>  기사  >  Java  >  Java 서블릿의 ServletContext에 대한 자세한 소개

Java 서블릿의 ServletContext에 대한 자세한 소개

黄舟
黄舟원래의
2017-07-26 15:08:191568검색

이 글은 주로 서블릿의 ServletContext에 대한 소개입니다. 편집자는 이것이 꽤 좋다고 생각합니다. 이제 여러분과 공유하고 참고할 것입니다. 편집기를 따라가서 살펴보겠습니다.

웹에서는 대신 web.xml 파일과 같은 외부 세계를 통과하여 수정하기 쉽습니다. 46309ed845064fdb06e746051efff9e0 태그 아래에 380fae52cc7d04565d26dd4bbf4b5460 태그를 사용하고 380fae52cc7d04565d26dd4bbf4b5460 태그의 f226acac8cb0e4a9d59fcba58b57a899 여러 개의 380fae52cc7d04565d26dd4bbf4b5460 태그를 사용하여 여러 초기화 매개변수를 설정할 수 있습니다. Tomcat의 web.xml에서 기본 서블릿을 볼 수 있습니다.

이 기본 서블릿에는 두 가지 초기화가 있음을 알 수 있습니다. 매개변수는 각각 "debug=0" 및 "listings=false"입니다.


서블릿이 web.xml 파일에서 380fae52cc7d04565d26dd4bbf4b5460 태그를 구성하면 웹 컨테이너는 서블릿 인스턴스 객체를 생성할 때 이러한 초기화 매개변수를 ServletConfig 객체에 자동으로 캡슐화하고 서블릿의 초기화 init 메소드를 호출합니다. ServletConfig 객체를 Servlet에 전달합니다.


서블릿 인터페이스의 초기화 방법인 init(ServletConfig config)를 통해 서버가 서블릿 객체를 생성할 때 ServletConfig 객체를 전달하고 ServletConfig 객체에는 < init-param> 태그입니다.


처음 서블릿을 배우기 시작했을 때 서블릿 인터페이스의 비생명주기 메소드 중 하나가 ServletConfig 객체를 반환하는 getServletConfig() 메소드라고 이미 언급했습니다. 따라서 웹에서 일부 정보를 구성하면 이 Servlet에 액세스하기 위해 MyEclipse 콘솔에 인쇄되는 것을 볼 수 있습니다.


ServletConfig 클래스에서 getInitParameter(String name) 메소드는 특정 매개변수를 전달하는 것입니다. 해당 매개변수의 값을 가져오기 위한 이름, getInitParameterNames () 메소드는 모든 매개변수 이름을 Enumeration 객체에 로드하고 이를 반환합니다. 여러 매개변수 키-값 쌍이 있는 경우:


Traverse 및 서블릿 출력:

public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    ServletConfig config = this.getServletConfig();
    String initValue = config.getInitParameter("love");
    System.out.println(initValue);
  }


마지막으로 ServletConfig 객체의 역할은 일반적으로 인코딩 테이블 유형 획득, 데이터베이스 연결 정보 획득, 구성 파일(예: Struts의 web.xml 파일) 획득 등에 사용됩니다.

ServletConfig 객체에 대해 이야기한 후 이 객체의 메소드를 살펴보면 이 메소드에 getServletContext()라는 또 다른 메소드가 있다는 것을 알게 됩니다. 이 메소드는

ServletContext 객체를 반환하는데, 이는 매우 중요한 클래스입니다. 서블릿

. 물론 ServletContext 객체는 상위 클래스의 메소드에서 직접 얻을 수도 있습니다.


웹 컨테이너는 시작될 때 각 웹 애플리케이션에 대한 ServletContext 객체를 생성하며 이 ServletContext 객체는 현재 웹 애플리케이션을 나타냅니다. ServletContext 객체는 웹 애플리케이션을 나타내기 때문에 웹 애플리케이션의 모든 서블릿과 기타 리소스는 ServletContext 객체를 공유합니다. 이때 ServletContext 객체를 통해 Servlet 객체 간 통신이 가능합니다. ServletContext 객체는 Context 도메인 객체라고도 합니다.

먼저 ServletContext 객체를 얻는 두 가지 방법을 살펴보겠습니다.


public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    ServletConfig config = this.getServletConfig();
    Enumeration initParams = config.getInitParameterNames();
    while(initParams.hasMoreElements()) {
      String paramName = (String)initParams.nextElement();
      String paramValue = config.getInitParameter(paramName);
      System.out.println(paramName+" = "+paramValue );
    }
  }
먼저 ServletConfig 객체를 얻거나 상위 클래스 메소드를 통해 직접 얻을 수 있습니다. 이 두 가지 방법으로 얻는 것은 무엇입니까? 동일한 개체(동일한 주소)입니다.

ServletContext는 이 웹 애플리케이션을 나타내므로 이를 서블릿 간의 직접 통신에 사용할 수 있으며, 두 서블릿 간에 데이터를 전송하는 프로젝트를 생성하겠습니다. [myservlet] 웹 프로젝트 아래에 두 개의 서블릿을 만듭니다: ServletDemo1 및 ServletDemo2.

ServletDemo1은 ServletContext에 매개변수 키-값 쌍을 설정합니다. 코드는 다음과 같습니다.

public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    //两种获取ServletContext对象的方法:
    ServletContext context1 = this.getServletConfig().getServletContext();
    ServletContext context2 = this.getServletContext();
    
    //System.out.println(context1 == context2);  //ture
  }

ServletDemo2는 ServletContext에서 키-값 쌍을 가져옵니다. . 코드는 :


public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    ServletContext context = this.getServletContext();  
    System.out.println(context.getAttribute("lover"));
  }

在浏览器先访问ServletDemo1后(先执行ServletDemo1才能使ServletContext设置参数),再访问ServletDemo2后,MyEclipse的控制台就输出了ServletContext中设置的参数,这就达到了从一个Servlet传递数据给另一个Servlet。当然这只是ServletContext的一个小小应用。

在ServletContext类中还有getInitParameter(String name)方法或者getInitParameterNames()方法,这两个方法获取的是web应用所配置的参数(毕竟ServletContext代表web应用),就像ServletConfig中类似的方法获取的是某个Servlet中的380fae52cc7d04565d26dd4bbf4b5460标签配置的参数。

而对于配置web应用的参数是在web.xml文件中使用75d9475f58d50d678ef97bf7ae35ef75标签,正如在该文件中为Servlet配置参数而使用380fae52cc7d04565d26dd4bbf4b5460标签一样。这种配置75d9475f58d50d678ef97bf7ae35ef75标签的好处在于属于全局性的配置,而每个Servlet的配置参数仅局限于在Servlet的范围内,举个例子,对于整个web应用配置数据库连接,这样在web应用中的每个Servlet都可以使用,而无需再在每个Servlet中都单独设置一次,提高了效率。

例:在【myservlet】web工程下建立了名为ServletDemo3的Servlet,并在该web工程下的web.xml文件中添加75d9475f58d50d678ef97bf7ae35ef75标签作为该web应用的配置参数:

在ServletDemo3中的代码如下:


public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    ServletContext context = this.getServletContext();
    String username = context.getInitParameter("username");
    String password = context.getInitParameter("password");
    
    System.out.println(username +":"+ password);
}

在浏览器中访问该Servlet,如果MyEclipse的控制台能打印该信息,说明每个Servlet可以通过ServletContext对象来获取web应用的配置信息,也从侧面说明了ServletContext代表了这个web应用:

ServletContext类中的getMimeType(String  file)方法用于返回该文件的MIME类型:


public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    String filename = "1.html";
    ServletContext context = this.getServletContext();
    System.out.println(context.getMimeType(filename));  
  }

输出:text/html。

ServletContext中的转发方法(重要) 

在ServletContext对象中还有这么两个方法:getNameDispatcher(String name)(不常用)和getRequestDispatcher(String path),返回的是RequestDispatcher对象。转发有什么作用呢,举个例子,比如一个Servlet中的数据交个另一个Servlet来处理,或者Servlet将某个实时数据交给JSP来显示,虽然我们在浏览器中访问的是最开始的Servlet,但是进行转发后看到的其他web资源,而浏览器的地址栏不会改变。

注:在请求对象request对象中也有这么一个getRequestDispatcher(String path)方法,功能与ServletContext对象的这个方法一样,也可以实现转发,因此用哪个对象都行,没有区别。

例:在【myservlet】web工程下创建一个名为ServletDemo1的Servlet和一个show.jsp,

在ServletDemo1中将数据转发给show.jsp,代码为:


public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
  String data = "Ding love LRR";
  this.getServletContext().setAttribute("data", data); //将数据存至web应用的配置中
  ServletContext context = this.getServletContext();    
  RequestDispatcher dispathcer = context.getRequestDispatcher("/show.jsp"); //通过要转发的目的地来获取转发对象
  dispathcer.forward(request, response);   //通过forward方法将请求对象和响应对象转发给别人处理
  }

而在show.jsp中接收这个数据,并封装在HTML中:


<font size="100px" color="red">
    ${data }
</font>

接着我们去浏览器里访问ServletDemo1,就会看到:

虽然我们请求的ServletDemo1资源,但是由于在ServletDemo1中将请求进行了转发,所以其实服务器返回的是show.jsp的资源,但是我们浏览器地址依然会是ServletDemo1,这也是转发和重定向的区别之一。

위 내용은 Java 서블릿의 ServletContext에 대한 자세한 소개의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.