|
| 1 | +package com.baeldung.context; |
| 2 | + |
| 3 | +import jakarta.servlet.ServletConfig; |
| 4 | +import jakarta.servlet.ServletContext; |
| 5 | +import jakarta.servlet.ServletException; |
| 6 | +import jakarta.servlet.annotation.WebServlet; |
| 7 | +import jakarta.servlet.http.HttpServlet; |
| 8 | +import jakarta.servlet.http.HttpServletRequest; |
| 9 | +import jakarta.servlet.http.HttpServletResponse; |
| 10 | + |
| 11 | +import java.io.IOException; |
| 12 | + |
| 13 | +@WebServlet("/context") |
| 14 | +public class ContextServlet extends HttpServlet { |
| 15 | + |
| 16 | + @Override |
| 17 | + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { |
| 18 | + |
| 19 | + resp.setContentType("text/plain"); |
| 20 | + |
| 21 | + // 1. Direct Access From the Servlet |
| 22 | + ServletContext contextFromServlet = this.getServletContext(); |
| 23 | + resp.getWriter() |
| 24 | + .println("1) From HttpServlet: " + contextFromServlet); |
| 25 | + |
| 26 | + resp.getWriter() |
| 27 | + .println(); |
| 28 | + |
| 29 | + // 2. Accessing Through the ServletConfig |
| 30 | + ServletConfig config = this.getServletConfig(); |
| 31 | + ServletContext contextFromConfig = config.getServletContext(); |
| 32 | + resp.getWriter() |
| 33 | + .println("2) From ServletConfig: " + contextFromConfig); |
| 34 | + |
| 35 | + resp.getWriter() |
| 36 | + .println(); |
| 37 | + |
| 38 | + // 3. Getting the Context From the HttpServletRequest (Servlet 3.0+) |
| 39 | + ServletContext contextFromRequest = req.getServletContext(); |
| 40 | + resp.getWriter() |
| 41 | + .println("3) From HttpServletRequest: " + contextFromRequest); |
| 42 | + |
| 43 | + resp.getWriter() |
| 44 | + .println(); |
| 45 | + |
| 46 | + // 4. Retrieving Through the Session Object |
| 47 | + ServletContext contextFromSession = req.getSession() |
| 48 | + .getServletContext(); |
| 49 | + resp.getWriter() |
| 50 | + .println("4) From HttpSession: " + contextFromSession); |
| 51 | + } |
| 52 | +} |
0 commit comments