ServletContext的常見使用方式

ServletContext的使用:

每個web工程都只有一個ServletContext對象,所以在哪裏獲得的ServletContext對象都是同一個.

作用:
1.可以獲取全局配置參數
2.可以獲取web應用中的資源
    1)獲取資源在tomcat裏面的絕對路徑,使用getRealPath()方法,先獲取路徑再獲取流對象.
    2)使用getResourceAsStream(),根據相對路徑直接獲取流對象
    3)通過classloader(類加載器JDBC)去獲取web工程下的資源
3.存取數據,在多個servlet間共享數據
    樣例:定義一個登陸的頁面;定義一個servlet;針對成功或者失敗跳轉到不同頁面;

ServletContext在服務器啓動時,會爲託管的每一個web應用程序,創建一個ServletContext對象;從服務器移除託管或者關閉服務器時銷燬.
作用範圍:在同一個項目裏面都可以取.

獲取全局配置參數與獲取web應用中的資源的實現案例

package cw.Servlet;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Servlet06 extends HttpServlet{
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		//1.獲取全局配置參數
		ServletContext context=getServletContext();	//創建對象
		String rrrr=context.getInitParameter("rrrr");
		System.out.println("rrrr"+"..."+rrrr);
		
		//2.獲取web應用中的資源
		/*
		 * 這裏如果想獲取web工程下的資源,用普通的FileInputStream寫法是不對的
		 * 因爲路徑不正確,這裏的相對路徑是根據jre來確定的,但是這裏是一個web工程
		 * jre後面由tomcat管理,所以這裏真正的相對路徑是tomcat裏的bin目錄
		 */
		/*
		Properties pro=new Properties();	//創建屬性對象
		InputStream is=new FileInputStream("src/config.properties");
		pro.load(is);
		String name=pro.getProperty("address");
		System.out.println(name);
		*/
		//應該使用ServletContext
		//1)第一種方式,使用getRealPath()方法,先獲取路徑再獲取流對象
		ServletContext sc2=getServletContext();	//獲取ServletContext對象
		String path=sc2.getRealPath("file/config.properties");		//獲取給定的文件在服務器上面的絕對路徑
		
		Properties pro=new Properties();		//創建屬性對象
		InputStream is=new FileInputStream("path");
		pro.load(is);
		
		String name=pro.getProperty("address");	//獲取address屬性的值
		System.out.println(name);
		is.close();
		
		//2)第二種方式,使用getResourceAsStream(),根據相對路徑直接獲取流對象
		ServletContext sc3=getServletContext();	
		Properties pro2=new Properties();
		//獲取web工程下的資源轉換成流對象,前面隱藏當前工程的根目錄
		InputStream is2=sc3.getResourceAsStream("file/config.properties");
		pro2.load(is2);
		String name2=pro2.getProperty("address");
		System.out.println(name2);
		is2.close();
		
		//3).通過classloader(類加載器JDBC)去獲取web工程下的資源
		Properties pro3=new Properties();
			//獲取該java文件的class,然後獲取到加載這個class到虛擬機中的那個類加載器對象
		
		//默認的classloader的路徑是下面這個路徑,我們必須得回到JavaWeb_1這個目錄下,才能進入file目錄
		//E:\tomcat\apache-tomcat-7.0.57\wtpwebapps\JavaWeb_1\WEB-INF\classes
		InputStream is3=this.getClass().getClassLoader().getResourceAsStream("../../file/config.properties");
		pro3.load(is3);
		String name3=pro3.getProperty("address");
		System.out.println(name3);
		is3.close();
		
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		System.out.println("bb");
	}
}

實現存取數據,在多個servlet間共享數據的樣例

此功能實現了實現登陸功能,並且記錄登陸的次數返回到網頁.

login.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h2>請輸入登陸信息</h2>
	<form action="LoginServlet" method="get">
		賬號:<input type="text" name="username" />
		密碼:<input type="text" name="password" />
		<input type="submit" name="登陸" />
	</form>	
</body>
</html>

LoginServlet.java

package cw.Servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
/*
	request:包含請求信息

	response:響應數據給瀏覽器
	
*/
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//1.獲取數據
		String name=request.getParameter("username");
		String password=request.getParameter("password");
		System.out.println("username="+name+"..."+"password="+password);
		//2.校驗數據
		//向客戶端輸出內容
		PrintWriter pw=response.getWriter();
		if("admin".equals(name)&&"123".equals(password)){
			System.out.println("登陸成功");
			pw.write("login success...");
			
			//成功的次數累加
			Object obj=getServletContext().getAttribute("count");//獲取以前存取的count值
			
			Integer count=0;
			if(obj!=null){
				count=(Integer)obj;
			}
			System.out.println("已登陸成功的次數是:"+count);
			getServletContext().setAttribute("count", count+1);
			
			response.setStatus(302);	//設置狀態碼,重新定位目標位置
			//定位跳轉的位置是哪一個頁面
			response.setHeader("Location", "login_success.html");	//成功就跳轉到login_success.html
		}
		else{
			System.out.println("登陸失敗");
			pw.write("login failed...");
		}
			
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}

login_success.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h2>登陸成功!</h2>
	<a href="CountServlet">獲取網站登陸成功總數</a>
</body>
</html>

CountServlet.java

package cw.Servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class CountServlet
 */
public class CountServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//1.取出相應的值
		Integer count=(Integer)getServletContext().getAttribute("count");
		//2.輸出到界面
		response.getWriter().write("login success times:"+count);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章