【Java Web】:“谈谈你对Servlet中三大域对象的认识,包括特性和常用方法”

407 阅读3分钟

一、前言

在JavaWeb开发中,Servlet中的三大域对象,即HttpServletRequestHttpSession,和ServletContext 用于存储和共享数据。这三个对象的使用方式受其作用域、生命周期的影响,本文将探讨它们的特性、用途以及使用方法。


二、内容

2.1 HttpServletRequest(请求对象)

(1)特性

  • 表示一个请求,每次发出请求都会创建一个新的HttpServletRequest对象。
  • 仅在当前请求中有效,用于不同页面之间的参数传递。
  • 常用于表单控件值传递和服务器间的同一请求不同页面之间的参数传递。

(2)常用方法

  • request.setAttribute(name, value):将数据存储在请求对象中。
  • request.getAttribute(name):获取存储在请求对象中的数据。
  • request.removeAttribute(name):删除请求对象中的属性。
  • request.getParameter(name):获取请求参数。

(3)具体示例

下面是一个简单的示例代码:

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class MyServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 设置属性
        request.setAttribute("message", "Hello, World!");

        // 获取属性
        String message = (String) request.getAttribute("message");

        // 删除属性
        request.removeAttribute("message");

        // 获取请求参数
        String paramName = request.getParameter("name");

        // 在这里可以处理参数或属性并生成响应
        response.getWriter().write("Message: " + message + "\n");
        response.getWriter().write("Parameter 'name' value: " + paramName + "\n");
    }
}

2.2 HttpSession(用户会话对象)

(1)特性

  • 服务器为每个会话创建一个新的HttpSession对象,数据可供当前会话中的所有Servlet共享。
  • 会话从浏览器打开开始,到关闭浏览器结束,期间只创建一个HttpSession对象。
  • 常用于登录验证,存储用户信息,以便后续访问权限判断。
  • HttpSession对象保存在服务器端,通过cookie返回sessionId给客户端以便下次验证。

(2)常用方法

  • request.getSession():获取当前会话的HttpSession对象。如果会话不存在,它将创建一个新的会话。

  • session.setAttribute(name, value):将数据存储在HttpSession中。

  • session.getAttribute(name):获取HttpSession中的数据。

  • session.removeAttribute(name):删除HttpSession中的数据。

(3)具体示例

下面是一个简单的示例代码:

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class SessionExampleServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取当前会话的 HttpSession 对象,如果不存在会话,则创建一个新的会话
        HttpSession session = request.getSession();

        // 存储数据在 HttpSession 中
        session.setAttribute("username", "john_doe");
        session.setAttribute("userRole", "admin");

        // 获取 HttpSession 中的数据
        String username = (String) session.getAttribute("username");
        String userRole = (String) session.getAttribute("userRole");

        // 删除 HttpSession 中的数据
        session.removeAttribute("userRole");

        // 在这里可以进行权限验证等操作
        response.getWriter().write("Username: " + username + "\n");
        response.getWriter().write("User Role: " + userRole + "\n");
    }
}

2.3 ServletContext(Web应用全局对象)

(1)特性

  • 针对同一个Web项目,所有Servlet共享一个ServletContext对象。
  • 用于获取根目录下的所有资源,类似一个Web全局对象。
  • 创建于服务器启动,销毁于服务器关闭,一个JavaWeb应用只能创建一个ServletContext对象。
  • 所有客户端在访问服务器时共享同一个ServletContext对象。

(2)常用方法

  • getServletContext():获取 ServletContext 对象,它代表整个Web应用程序。

  • servletContext.setAttribute(name, value):将数据存储在 ServletContext 中。

  • servletContext.getAttribute(name):获取 ServletContext 中的数据。

(3)具体示例

下面是一个简单的示例代码:

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ServletContextExample extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取ServletContext对象
        ServletContext servletContext = getServletContext();

        // 存储数据在ServletContext中
        servletContext.setAttribute("appTitle", "My Web Application");
        servletContext.setAttribute("version", "1.0");

        // 获取ServletContext中的数据
        String title = (String) servletContext.getAttribute("appTitle");
        String version = (String) servletContext.getAttribute("version");

        response.getWriter().write("Application Title: " + title + "\n");
        response.getWriter().write("Version: " + version + "\n");
    }
}

三、总结

总的来说,Servlet中的三大域对象(HttpServletRequestHttpSessionServletContext)是用来存放和共享数据的重要工具。需要注意的是,我们推荐使用尽量小的作用域,如果能使用request就使用它,如果无法满足需求,再考虑使用session。对于系统级别的数据,使用application作用域。

request常用于单次请求数据传递,session用于会话级别的数据共享,而application适用于项目全局信息的存储。理解并善用这三大域对象,有助于高效灵活地处理数据在JavaWeb应用中的传递和共享。