ServletContext瀵硅薄
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ServletContext瀵硅薄相关的知识,希望对你有一定的参考价值。
鏍囩锛?a href='http://www.mamicode.com/so/1/oid' title='oid'>oid name https 鏂囦欢 tde 鍔犺浇 bsp 鎺ュ彛 throw
姣忎竴涓猈eb宸ョ▼瀵瑰簲浜庝竴涓猄ervletContext瀵硅薄锛屾瀵硅薄浠h〃web搴旂敤锛岀敱鏈嶅姟鍣ㄥ垱寤恒€傚彲浠ヨВ鍐充笉鍚岀敤鎴风殑鏁版嵁鍏变韩闂銆?/p>
1銆佺敓鍛藉懆鏈燂細
鍒涘缓锛歸eb搴旂敤琚姞杞藉埌鏈嶅姟鍣ㄦ垨鏈嶅姟鍣ㄥ紑鍚€?/p>
閿€姣侊細web搴旂敤琚Щ闄ゆ垨鏈嶅姟鍣ㄥ叧闂€?/p>
2銆佸璞$殑鑾峰彇锛?/span>
锛?锛夊疄鐜癝ervlet鎺ュ彛鐨勭被鍐呴儴锛?/p>
public void init(ServletConfig servletConfig) throws ServletException
ServletContext servletContext= servletConfig.getServletContext();
锛?锛?/p>
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
ServletContext servletContext=getServletContext();
(3)閫氳繃Session鑾峰彇锛?/p>
ServletContext servletContext=request.getSession().getServletContext();
3銆丼ervletContext瀵硅薄鐨勫簲鐢細
锛?锛夎幏寰楀垵濮嬪寲鍙傛暟锛坵eb.xml鐨勫叏灞€鏁版嵁锛夛細
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>ServletDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/abc</url-pattern>
</servlet-mapping>
<context-param>//涓€缁勬爣绛惧彧鑳藉瓨鍌ㄤ竴缁勯敭鍊煎
<param-name>zhai</param-name>
<param-value>zhai1997</param-value>
</context-param>
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
ServletContext servletContext=getServletContext();
String paramvalue=servletContext.getInitParameter("zhai");//鐢遍敭鑾峰彇鍊?
System.out.println(paramvalue);
濡傛灉鏁版嵁涓嶅瓨鍦紝杩斿洖NULL銆?/p>
锛?锛夎幏寰楀伐绋嬪彂甯冨悗鐨勭粷瀵硅矾寰勶細
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
ServletContext servletContext=getServletContext();
String realpath=servletContext.getRealPath("/web.text");
System.out.println(realpath);
String realpath1=servletContext.getRealPath("/WEB-INF/wen-inf.text");
System.out.println(realpath1);
String realpath2=servletContext.getRealPath("../宸ョ▼.text");
System.out.println(realpath2);
getRealPath鐨勫弬鏁颁负鐩稿浜巜eb鐨勮矾寰勶紝鍥犱负鍙戝竷鍒版湇鍔″櫒鐨勬椂鍊欏彧鍙戝竷web鏂囦欢涓殑鍐呭锛屽洜姝わ細宸ョ▼.text鏂囦欢涓嶈兘琚闂埌銆?/p>
锛?锛夊煙瀵硅薄锛堜綔鐢ㄨ寖鍥翠负鏁翠釜web搴旂敤锛?/span>
Servlet1锛氬垱寤篠ervletContext瀵硅薄璁剧疆閿拰鍊硷紙鏁版嵁瀛樺偍锛夛細
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
ServletContext servletContext=getServletContext();
servletContext.setAttribute("name","zhai");
Servlet2锛氱敱閿幏鍙栧€硷細
String attribute=(String)this.getServletContext().getAttribute("name");
System.out.println(attribute);
闇€瑕佸厛璁块棶Servlet1璁剧疆閿拰鍊硷紝鍐嶅幓璁块棶Servlet2鑾峰彇鍊笺€傚鏋滀笉瀛樺湪杩斿洖NULL銆?/p>
以上是关于ServletContext瀵硅薄的主要内容,如果未能解决你的问题,请参考以下文章