Resumen de cuatro objetos de dominio JAVAWEB

Los métodos contenidos en los cuatro objetos de dominio.

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

Objeto de dominio Servletcontext

生命周期:
  • Crear: cuando se inicia el servidor, el servidor creará un objeto de dominio ServletContext para cada proyecto web en el servidor
  • Destrucción: cuando el servidor se apaga o cuando el elemento se elimina del servidor
  • Alcance: Se puede usar mientras el proyecto se esté ejecutando. Es el objeto de dominio más grande y todos los servlets pueden acceder a él.

El papel de servletContext:

  1. Objetos de dominio de ámbito de aplicación:
    cree tres servlets por separado para almacenar, obtener, eliminar datos, probar que el objeto de dominio servletcontext es válido para todos los servlets actuales.
    Visualización de código:
    paso1:
    crear enlace:
<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);
    }
}

Resultado: cuando hace clic en Almacenar datos, los datos se almacenan en el objeto de dominio servletContext. En este momento, haga clic en Obtener datos para mostrar los datos 666. Cuando haga clic en Eliminar datos, haga clic en Obtener datos para mostrar nulo.


  1. Métodos comunes para obtener la configuración de parámetros a nivel de aplicación (parámetros de configuración global, solo xml) :
    1, public String getInitParamter (String name): obtiene la información del parámetro de configuración del nombre especificado
    2, Public Enumeration <String> getInitParamterNames (): obtiene todas las aplicaciones Parámetros de nivel
    Visualización de código:
    paso1:
    Configure los parámetros de nivel de aplicación en 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);
    }
}

Salida:
66
666
66

  • Obtenga la ruta real de los recursos web
    Métodos comunes:
    1, cadena pública getRealPath ("/ ruta"): obtenga la ruta real (debe / antes del servlet3.0)
    2. flujo de entrada público getresourceAsStream ("/ ruta"): obtenga la entrada para esto
    Visualización del código de objeto de flujo :
@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);
    }
}

Objeto de dominio HttpSession

Ciclo de vida:

  • Crear: en Java, el servidor lo crea cuando se llama a getSession () por primera vez en una sesión; en jsp, se crea cuando accede a cualquier interfaz jsp por primera vez en una sesión
  • Destrucción: cuando se
    llama al método invalidate () Cuando el
    servidor agota el tiempo de espera: el servidor web especifica el tiempo de espera predeterminado, tomcat es de 30 minutos
//此代码在tomcat的conf目录的web.xml中
<session-config>
        <session-timeout>30</session-timeout>
    </session-config>
服务器关闭时:服务器关闭时,我们可以通过钝化(将session数据保存到硬盘中)和活化(将session数据回复到session中)
  • Alcance de la acción: en una sesión, se pueden usar tanto el servlet como el jsp involucrados

Objeto de dominio HttpServletRequest

Ciclo de vida:

  • Crear: creado por el servidor cuando lo solicita el navegador
  • Destrucción: destruida por el servidor cuando se genera la respuesta
  • Alcance: solo en una solicitud
  • Atencion Los datos en el objeto de dominio de solicitud pueden compartirse en dos servlets cuando se reenvían, pero no pueden estar en la redirección.
    Demostración de código:
    paso1:
    Cree un Demo3Servlet para almacenar datos en el objeto de dominio
@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);
    }
}

Objeto de dominio PageContext

Ciclo de vida:

  • Crear: crea cuando comienza la solicitud de jsp

  • Destruir: destruir cuando termine la respuesta

  • Alcance: toda la página (el alcance más pequeño de los cuatro objetos de dominio)
    funciona:

  • Obtener los otros ocho objetos
    integrados getException () devuelve Exception.
    getPage () devuelve la página.
    getRequest () devuelve la solicitud.
    getResponse () devuelve la respuesta.
    getServletConfig () devuelve config.
    getServletContext () devuelve la aplicación.
    getSession () devuelve sesión.
    getOut () regresa

  • Como objeto de dominio

  • En la interfaz actual, puede operar los otros tres objetos de dominio
    setAttribute (qué campo es String key, String value, int):
    getAttribute (qué campo de String key, int)
    removeAttribute ( qué campo de String key, int) encuentra
    ndAttribute (String key): a su vez desde jsp Busque la clave especificada una por una en los cuatro campos de pequeño a grande (el rango del campo). Si se encuentra, regrese directamente y finalice la búsqueda.

Publicado un artículo original · Me gusta0 · Visitas1

Supongo que te gusta

Origin blog.csdn.net/SUPER__W/article/details/105440298
Recomendado
Clasificación