Java Web之Servlet的三大作用域对象

 

  Servlet的作用域是干嘛的?答案就是共享数据而存在的,如图: 

 

  下面通过代码演示来具体讲解一下三大作用域

我们新建两个类

package main.com.vae.scope;

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;

@WebServlet("/scope")
public class ScopeServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //Servlet的三大作用域讲解
        //1.request
        Integer numInRequest=(Integer)req.getAttribute("NUM_IN_REQUEST") ;
        if (numInRequest == null) {
            req.setAttribute("NUM_IN_REQUEST",1);
        }
        else {
            req.setAttribute("NUM_IN_REQUEST",numInRequest+1);
        }
        //2.Session
        Integer numInSession=(Integer)req.getSession().getAttribute("NUM_IN_SESSION") ;
        if (numInSession == null) {
            req.getSession().setAttribute("NUM_IN_SESSION",1);
        }
        else {
            req.getSession().setAttribute("NUM_IN_SESSION",numInSession+1);
        }
        //3.application

        Integer numInApplication=(Integer) req.getServletContext().getAttribute("NUM_IN_APPLICATION");
        if (numInApplication == null) {
            req.getServletContext().setAttribute("NUM_IN_APPLICATION",1);
        }
        else {
            req.getServletContext().setAttribute("NUM_IN_APPLICATION",numInApplication+1);
        }

        req.getRequestDispatcher("/result").forward(req,resp);

    }
}
package main.com.vae.scope;

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.io.PrintWriter;

@WebServlet("/result")
public class ResultServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out=resp.getWriter();

        Integer numInRequest=(Integer) req.getAttribute("NUM_IN_REQUEST");
        Integer numInSession=(Integer) req.getSession().getAttribute("NUM_IN_SESSION");
        Integer numInApplication=(Integer) req.getServletContext().getAttribute("NUM_IN_APPLICATION");

        out.println("Request="+numInRequest);
        out.println("Session="+numInSession);
        out.println("Application="+numInApplication);
    }
}

运行,输入/scope。这个例子很好的讲解了三大作用域的本质

第一次访问,三大作用域都是1,按F5刷新几下

可以看到,Session和Application作用域在一直增加,我换一个火狐浏览器再访问这个Servlet试试

换个火狐浏览器访问了几次,Session从0开始计算了,而Application还是接着加的,我再返回Google浏览器试试

Google里面的session自己又加1了,Application是右边增加的基础上又加的。这就表达了一个本质

Request是一次请求

Session是一个会话

Application是多次会话(Tomcat开启到关闭)

 

 

ServletContext对象的获取以及常用的方法

 

代码如下:

package main.com.vae.scope;

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("/scd")
public class ServletContextDemo extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取ServletContext(就是Application)对象的3种方式
        //1.
        ServletContext app1=super.getServletContext();
        //2.
        ServletContext app2=req.getServletContext();
        //3.
        ServletContext app3=req.getSession().getServletContext();

        //以上三种方式获取的ServletContext对象是相等的,是同一个

        //ServletContext常用的方法
        //1.根据相对路径获取绝对路径。在做资源下载的时候有用
        String Path=super.getServletContext().getRealPath("/WEB-INF/web.html");
        System.out.println(Path);
        //2.返回响应的上下文路径,Tomcat7以上你不填path就是空的,Tomcat6你不填是一个 /
        System.out.println(req.getContextPath());
        System.out.println(super.getServletContext().getContextPath());

        //3.获取全局参数
        System.out.println(super.getServletContext().getInitParameter("name"));
        Enumeration<String> enums=super.getServletContext().getInitParameterNames();
        while (enums.hasMoreElements()) {
            System.out.println("--->" + enums.nextElement());
        }

    }
}

浏览器访问之后,输出栏结果如下:

这里需要说一下,第一个方法没啥讲的,获取绝对路径。

第二个方法是这样的,获取当前项目的上下文路径,就是我们Tomcat的Server.xml里面配置的,如图:

这个path我们填的空,那就没显示。

第三个方法,配置全局参数,因为Servlet自己在Tomcat的web.xml里面配置的参数只能自己用,其他Servlet如果也使用了通用的参数还得自己写。

所以写一个全局参数比较好,全局参数在项目的WEB-INF文件夹下的web.xml里面写,这样写

<?xml version="1.0" encoding="UTF-8"?>

<web-app version="2.4"
         xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">


    <!--全局的初始化参数-->
    <context-param>
        <param-name>name</param-name>
        <param-value>许嵩</param-value>
    </context-param>
    <context-param>
        <param-name>password</param-name>
        <param-value>514</param-value>
    </context-param>

</web-app>
        

完事。

 

posted @ 2019-01-06 23:12  蜀云泉  阅读(3289)  评论(1编辑  收藏  举报