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>
        

完事。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM