(JavaWeb)ServletContext对象
生活随笔
收集整理的這篇文章主要介紹了
(JavaWeb)ServletContext对象
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- ServletContext
- 1.共享數據
- 2.獲取初始化參數
- 3.請求轉發
- 4.讀取資源文件
ServletContext
- web容器在啟動的時候,它會為每個web程序都創建一個對應的ServletContext對象,它代表了當前的web應用;
1.共享數據
Servlet1可以將數據存放在ServletContext中,Servlet2和Servlet3可以在ServletContext中取得Servlet1在ServletContext中存放的數據。
在HelloServlet中存放String數據 伊澤瑞爾。
在GetNameServlet中取得數據并顯示在網站上
public class GetNameServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//獲取ServletContext對象ServletContext servletContext = this.getServletContext();//獲取HelloServlet中在獲取ServletContext對象中存放的數據String name = (String) servletContext.getAttribute("name");//設置響應信息為中文resp.setContentType("text/html");resp.setCharacterEncoding("utf-8");resp.getWriter().write(name);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req, resp);} }先訪問HelloServlet頁面將數據存放在ServletContext中,再訪問GetNameServlet拿出數據并顯示在網頁。
2.獲取初始化參數
<!--配置一些web應用初始化參數--><context-param><param-name>url</param-name><param-value>jdbc:mysql://localhost:3306/mybatis</param-value></context-param> protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {ServletContext context = this.getServletContext();String url = context.getInitParameter("url");resp.getWriter().print(url); }3.請求轉發
public class ServletDemo01 extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//創建servletContext對象ServletContext servletContext = this.getServletContext();//請求轉發servletContext.getRequestDispatcher("/getName").forward(req,resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req, resp);} }運行,顯示的是GetNameServlet的頁面,這里null是由于沒有訪問hello的緣故。
顯示的是GetNameServlet的頁面,但是路徑卻還是自己的。
如圖,A向B請求資源,B向C請求資源,B將C返回的資源再返回給A,A自始至終沒有接觸C,所以顯示的還是B的路徑。
4.讀取資源文件
Properties
- 在resources目錄下新建db.properties文件
總結
以上是生活随笔為你收集整理的(JavaWeb)ServletContext对象的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: HTTP Status 405 – Me
- 下一篇: (JavaWeb)HttpServlet