(JavaWeb)ServletContext对象
生活随笔
收集整理的這篇文章主要介紹了
(JavaWeb)ServletContext对象
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
文章目錄
- ServletContext
- 1.共享數(shù)據(jù)
- 2.獲取初始化參數(shù)
- 3.請求轉(zhuǎn)發(fā)
- 4.讀取資源文件
ServletContext
- web容器在啟動的時候,它會為每個web程序都創(chuàng)建一個對應(yīng)的ServletContext對象,它代表了當(dāng)前的web應(yīng)用;
1.共享數(shù)據(jù)
Servlet1可以將數(shù)據(jù)存放在ServletContext中,Servlet2和Servlet3可以在ServletContext中取得Servlet1在ServletContext中存放的數(shù)據(jù)。
在HelloServlet中存放String數(shù)據(jù) 伊澤瑞爾。
在GetNameServlet中取得數(shù)據(jù)并顯示在網(wǎng)站上
public class GetNameServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//獲取ServletContext對象ServletContext servletContext = this.getServletContext();//獲取HelloServlet中在獲取ServletContext對象中存放的數(shù)據(jù)String name = (String) servletContext.getAttribute("name");//設(shè)置響應(yīng)信息為中文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頁面將數(shù)據(jù)存放在ServletContext中,再訪問GetNameServlet拿出數(shù)據(jù)并顯示在網(wǎng)頁。
2.獲取初始化參數(shù)
<!--配置一些web應(yīng)用初始化參數(shù)--><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.請求轉(zhuǎn)發(fā)
public class ServletDemo01 extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//創(chuàng)建servletContext對象ServletContext servletContext = this.getServletContext();//請求轉(zhuǎn)發(fā)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文件
總結(jié)
以上是生活随笔為你收集整理的(JavaWeb)ServletContext对象的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: HTTP Status 405 – Me
- 下一篇: (JavaWeb)HttpServlet