iT邦幫忙

2024 iThome 鐵人賽

DAY 16
0
Software Development

從Servlet到Spring MVC系列 第 16

Day15 Servlet - Scope Object

  • 分享至 

  • xImage
  •  

0、創建module

請參考Day05創建module

一、Scope Object

Scope Object就是用來共享數據,想想你從前端接收使用者的數據,你希望再轉發給另一個Servlet協助處理;或是你希望記住使用者接下來一連串操作中會共用的訊息;或是你有著希望所有Servlet都知道的事,就讓我們來看看這三大域對象吧

  • ServletRequest:一次的請求範圍內及請求轉發
  • HttpSession:一次會話內,可以跨多個請求
  • ServletContext:作用範圍在此WebApp內,可以跨多個會話,因作用範圍是全域有時也會稱Application Context
    https://ithelp.ithome.com.tw/upload/images/20240930/20128084fr4ThCEpNi.png

二、Scope Object API

  • void setAttribute(String name,String value)設值
  • Object getAttribute(String name)取值
  • removeAttribute(String name)移除

Demo

SetAttributeServlet

@WebServlet("/SetAttributeServlet")
public class SetAttributeServlet extends HttpServlet {
    public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        req.setAttribute("request","request-information");
        req.getSession().setAttribute("session","session-information");
        req.getServletContext().setAttribute("application","servlet-information");
        //case1 請求轉發
        req.getRequestDispatcher("GetAttributeServlet").forward(req,res);
    }
}

GetAttributeServlet

@WebServlet("/GetAttributeServlet")
public class GetAttributeServlet extends HttpServlet {
    public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
        PrintWriter writer = res.getWriter();
        //case1
        writer.println("request data:"+req.getAttribute("request"));
        writer.println("session data:"+req.getSession().getAttribute("request"));
        writer.println("application data"+req.getServletContext().getAttribute("application"));
    }
}

訪問SetAttributeServlet
https://ithelp.ithome.com.tw/upload/images/20240930/20128084wsxu49S8km.png
註解請求轉發,先訪問SetAttributeServlet,再訪問GetAttributeServlet
https://ithelp.ithome.com.tw/upload/images/20240930/20128084fNLvTQbDyC.png

Reference


上一篇
Day14 Servlet - Cookie and Session
下一篇
Day16 Servlet - Filter
系列文
從Servlet到Spring MVC36
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言