Scope Object就是用來共享數據,想想你從前端接收使用者的數據,你希望再轉發給另一個Servlet協助處理;或是你希望記住使用者接下來一連串操作中會共用的訊息;或是你有著希望所有Servlet都知道的事,就讓我們來看看這三大域對象吧
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
註解請求轉發,先訪問SetAttributeServlet,再訪問GetAttributeServlet