JAVAWEB four domain object summary

The methods contained in the four domain objects

1,pubic void setAttribute(String name,*Object value*):向域中存储数据,指定名称
2,public *Object* getAttribute(String name):获取域对象中指定name的值
3,public void removeAttribute(String name):删除域对象中指定name的值

Servletcontext domain object

生命周期:
  • Create: When the server starts, the server will create a ServletContext domain object for each web project on the server
  • Destruction: When the server is shut down or when the item is removed from the server
  • Scope: It can be used as long as the project is running. It is the largest domain object and can be accessed by all servlets.

The role of servletContext:

  1. Application scope domain objects:
    create three servlets separately to store, obtain, delete data, test that the servletcontext domain object is valid for all current servlets.
    Code display:
    step1:
    create link:
<body>
  <a href="${pageContext.request.contextPath}/ContextServlet">存储数据</a>
  <a href="${pageContext.request.contextPath}/Context1Servlet">获取数据</a>
  <a href="${pageContext.request.contextPath}/Context2Servlet">删除数据</a>
  </body>
step2:
	创建ContextServlet:
@WebServlet("/ContextServlet")
public class ContextServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //告诉浏览器响应的数据类型
        response.setContentType("text/html;charset=utf-8");
        //获取servletContext域对象,方法是从父类中继承过来的
        ServletContext sc = getServletContext();
        //存放数据到域对象中
        sc.setAttribute("wp","666");
        response.getWriter().write("存储成功!");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
step3:
	创建Context1Servlet:
@WebServlet("/Context1Servlet")
public class Context1Servlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //告诉浏览器响应的数据类型
        response.setContentType("text/html;charset=utf-8");
        //获取servletContext域对象,方法是从父类中继承过来的
        ServletContext sc = getServletContext();
        //获取servletContext域对象中的数据
        String wp = (String) sc.getAttribute("wp");
        response.getWriter().write("获取到的数据是:"+wp);
    }

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

step4:
	创建Context2Servlet:
@WebServlet("/Context2Servlet")
public class Context2Servlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //告诉浏览器响应的数据类型
        response.setContentType("text/html;charset=utf-8");
        //获取servletContext域对象,方法是从父类中继承过来的
        ServletContext sc = getServletContext();
        //删除域对象中name为“wp”的数据
        sc.removeAttribute("wp");
        response.getWriter().write("删除成功!");
    }

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

Result: When you click Store Data, the data is stored in the servletContext domain object. At this time, click Get Data to display data 666. When you click Delete Data, click Get Data to display null.


  1. Common methods for obtaining application-level parameter configuration (global configuration parameters, only xml) :
    1, public String getInitParamter (String name): get the configuration parameter information of the specified name
    2, public Enumeration <String> getInitParamterNames (): get all applications Level parameters
    Code display:
    step1:
    Configure application level parameters in web.xml:
<context-param>
        <param-name>wp</param-name>
        <param-value>66</param-value>
    </context-param>
    <context-param>
        <param-name>wpp</param-name>
        <param-value>666</param-value>
    </context-param>
step2:
	创建Deno1Servlet:
@WebServlet("/Demo1Servlet")
public class Demo1Servlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取servletContext域对象
        ServletContext sc = getServletContext();
        //获取wp的取值
        String wp = sc.getInitParameter("wp");
        System.out.println(wp);
        //获取所有的配置参数
        Enumeration<String> ipn = sc.getInitParameterNames();
        //遍历
        while (ipn.hasMoreElements()){
            String s = ipn.nextElement();
            System.out.println(sc.getInitParameter(s));
        }
    }

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

Output:
66
666
66

  • Get the real path of web resources
    Common methods:
    1, public string getRealPath ("/ path"): get the real path (must / before servlet3.0)
    2. public inputstream getresourceAsStream ("/ path"): get the input to this Stream object
    code display:
@WebServlet("/Demo2Servlet")
public class Demo2Servlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取servletContext域对象
        ServletContext sc = getServletContext();
        //获取真实路径
        String realPath = sc.getRealPath("/images/5.jsp");
        System.out.println("真实路径:"+realPath);
        //输出结果:真实路径:E:\idea工作区间\javaweb129\out\artifacts\MyTest_war_exploded\images\5.jpg
        //getrealpath()方法不管路径存不存在,都可以获取到真实路径
        //需要注意的是,此图片的路径在web下的images文件夹下
        InputStream is = sc.getResourceAsStream("/images/5.jpg");
        ServletOutputStream os = response.getOutputStream();
        int len;
        byte[] b=new byte[1024];
        while ((len=is.read(b))!=-1){
            os.write(b,0,len);
        }
    }

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

HttpSession domain object

The life cycle:

  • Create: In java, it is created by the server when getSession () is called for the first time in a session; in jsp, it is created when you access any jsp interface for the first time in a session
  • Destruction: When
    calling the invalidate () method When the
    server times out: The web server specifies the default timeout, tomcat is 30 minutes
//此代码在tomcat的conf目录的web.xml中
<session-config>
        <session-timeout>30</session-timeout>
    </session-config>
服务器关闭时:服务器关闭时,我们可以通过钝化(将session数据保存到硬盘中)和活化(将session数据回复到session中)
  • Scope of action: In a session, both the servlet and jsp involved can be used

HttpServletRequest domain object

The life cycle:

  • Create: Created by the server when requested by the browser
  • Destruction: destroyed by the server when the response is generated
  • Scope: Only in one request
  • note! The data in the request domain object can be shared in two servlets when forwarding, but it cannot be in the redirection.
    Code demonstration:
    step1:
    Create a Demo3Servlet to store data in the domain object
@WebServlet("/Demo3Servlet")
public class Demo3Servlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //向httpservletrequest域对象中存储数据
        request.setAttribute("data","一对数据");
        //转发到Demo4Servlet
        request.getRequestDispatcher("Demo4Servlet").forward(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
step2:
	在此域对象中获取到了转发来的数据
@WebServlet("/Demo4Servlet")
public class Demo4Servlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取域中的数据
        String data = (String) request.getAttribute("data");
        //输出:一对数据
        System.out.println(data);
    }

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

PageContext domain object

The life cycle:

  • Create: Create when the request to jsp starts

  • Destroy: destroy when the response is over

  • Scope: The entire page (the smallest scope of the four domain objects)
    functions:

  • Get the other eight built-in objects
    getException () returns Exception.
    getPage () returns Page.
    getRequest () returns the request.
    getResponse () returns the response.
    getServletConfig () returns config.
    getServletContext () returns application.
    getSession () returns session.
    getOut () returns out

  • As a domain object

  • In the current interface, you can operate the other three domain objects
    setAttribute (which field of String key, String value, int):
    getAttribute (which field of String key, int)
    removeAttribute ( which field of String key, int)
    fi ndAttribute (String key): in turn from jsp Find the specified key one by one in the four fields from small to large (the range of the field). If it is found, return directly and terminate the search.

Published an original article · Likes0 · Visits1

Guess you like

Origin blog.csdn.net/SUPER__W/article/details/105440298