Jsp的pageContext,request,session,application4个域对象的属性作用范围

Attr_1:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>




Insert title here


 
 <%
  //setAttribute:设置属性
  //geyAttribute: 获取指定的属性
  
  //4个域对象设置属性
  //pageContext 的作用范围仅限于当前页面
  pageContext.setAttribute("pageCotext_Attr", "pageCotext_Val");
  
     //request 的作用范围仅限于同一个请求
  request.setAttribute("request_Attr", "request_Val");
  
  //session 的作用范围仅限于一次会话, 浏览器打开直到关闭, 称之为一次会话
  session.setAttribute("session_Attr", "session_Val");
  
  //application 的作用范围仅限于当前WEB 应用,是范围最大的属性作用范围, 只要在一处设置,在其他的jsp 和servlet 都可以获取到
  application.setAttribute("application_Attr", "application_Val");
  
  //重开浏览器比对seesion 和application 的作用范围
 %>
 
 

This is Attr_1


 
 pageContext:<%= pageContext.getAttribute("pageCotext_Attr") %>
 


 request:<%= request.getAttribute("request_Attr") %>
 


 session:<%= session.getAttribute("session_Attr") %>
 


 application:<%= application.getAttribute("application_Attr") %>
 


 Attr_2
 


 Text_Attr
 



Attr_2:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>




Insert title here


 

This is Attr_2


 pageContext:<%= pageContext.getAttribute("pageCotext_Attr") %>
 


 request:<%= request.getAttribute("request_Attr") %>
 


 session:<%= session.getAttribute("session_Attr") %>
 


 application:<%= application.getAttribute("application_Attr") %>
 


Text_Attr:

package src;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebServlet("/text_attr")
public class Text_attr extends HttpServlet {
 private static final long serialVersionUID = 1L;
      

 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
 {
  
  PrintWriter out  = response.getWriter();
  
  //pageContext 在servlet 获取不到
  
  //request 的获取
  out.print("request_Attr: "+request.getAttribute("request_Attr"));
  out.print("
");
  
  //session 的获取
  out.print("session_Attr: "+request.getSession().getAttribute("session_Attr"));
  out.print("
");
  
  //application 的获取
  out.print("application_Attr: "+getServletContext().getAttribute("application_Attr"));
  out.print("
");
 }


}

你可能感兴趣的:(java)