1. 程式人生 > >Java學習路程(javaEE)之ServletConfig物件、ServletContext物件、response 響應和request 請求

Java學習路程(javaEE)之ServletConfig物件、ServletContext物件、response 響應和request 請求

一.ServletConfig物件

1.配置資訊需要在web.xml進行配置,是以鍵值對形式配置 key-value,並且在Servlet初始化配置 2.獲取ServletConfig物件 方法一:宣告成員變數儲存ServletConfig

public class Demo01 extends HttpServlet{
	//宣告變數
	private ServletConfig config;
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		//接收引數中的配置物件
		this.config = config;
	}
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//遍歷獲取ServletConfig的值
		Enumeration<String> values = this.config.getInitParameterNames();
		while (values.hasMoreElements()) {
			String name = values.nextElement();
			System.out.println(name +"="+ this.config.getInitParameter(name));
			方法二:通過父類中的方法直接獲取ServletConfig物件
			ServletConfig servletConfig = this.getServletConfig();
			String value = servletConfig.getInitParameter("lisi");
		}
	}
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}
}

Servlet初始化配置

<servlet>
  	<servlet-name>demo02</servlet-name>
  	<servlet-class>com.lanou3g.Demo02</servlet-class>
  	<!-- 新增配置資訊 -->
  	<init-param>
  	<!-- 設定鍵值對資訊 -->
  		<param-name>lisi</param-name>
  		<param-value>hello</param-value>
  	</init-param>
  	
  	<init-param>
  		<param-name>zhangsan</param-name>
  		<param-value>world</param-value>
  	</init-param>
  	<init-param>
  		<param-name>zhang</param-name>
  		<param-value>123</param-value>
  	</init-param>
  </servlet>
  <servlet-mapping>
  	<servlet-name>demo02</servlet-name>
  	<url-pattern>/demo02</url-pattern>
  </servlet-mapping>

二.ServletContext(application域)

1.域物件: 在一定範圍內有效的物件 2.作用範圍: 當前工程都有效並且整個工程有且只有一個ServletContext物件 3.域物件共有的方法: 1).setAttribute 2).getAttribute 3).removeAttribute 4.域物件的作用: 1).存值取值 2).進行單例傳值 3).可以獲取全域性配置資訊 4).可以獲取專案中所有資源在伺服器上的絕對路徑 5).可以進行請求轉發

public class Demo03 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		  獲取context域方式一: 通過ServletContext物件獲取
		ServletContext application = this.getServletConfig().getServletContext();
		//存值
		application.setAttribute("name", "lisi");
		 獲取全域性配置資訊
		String value = application.getInitParameter("zhangfei");
		System.out.println(value);
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}

Servlet配置

 <servlet>
  	<servlet-name>demo03</servlet-name>
  	<servlet-class>com.lanou3g.Demo03</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>demo03</servlet-name>
  	<url-pattern>/demo03</url-pattern>
  </servlet-mapping>

使用域物件取值

public class Demo04 extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ServletContext application = this.getServletConfig().getServletContext();
		//取值
		Object value = application.getAttribute("name");
		System.out.println(value);
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}

Servlet設定

 <servlet>
  	<servlet-name>demo04</servlet-name>
  	<servlet-class>com.lanou3g.Demo04</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>demo04</servlet-name>
  	<url-pattern>/demo04</url-pattern>
  </servlet-mapping>

獲取專案中所有資源在伺服器上的絕對路徑

public class Demo05 extends HttpServlet{
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		獲取context域
		ServletContext application = this.getServletContext();
		獲取伺服器上的真實路徑
		String path1 = application.getRealPath("/WEB-INF/classes/a.properties");
		讀取檔案
		Properties properties = new Properties();
		FileInputStream fis = new FileInputStream(path1);
		讀取
		properties.load(fis);
		System.out.println(properties.getProperty("key"));
		關閉資源
	    fis.close();
	}
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}
}

Servlet配置

<servlet>
  	<servlet-name>demo05</servlet-name>
  	<servlet-class>com.lanou3g.Demo05</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>demo05</servlet-name>
  	<url-pattern>/demo05</url-pattern>
  </servlet-mapping>

Context域進行請求轉發

public class Demo06 extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("急缺錢");
		System.out.println("找別人借");
		ServletContext application = this.getServletContext();
		//獲取請求轉發器
		//注意請求轉發只能轉發站內的路徑並且傳入的地址相對於工程的
		RequestDispatcher dispatcher = application.getRequestDispatcher("/demo07");
		//傳送轉發請求
		dispatcher.forward(request, response);
		System.out.println("借錢完畢");
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}

public class Demo07 extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("借你一個億");
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	doGet(request, response);
	}
}

列印結果:

急缺錢
找別人借
借你一個億
借錢完畢

注意: 1.使用者只發送了一次請求,網址沒有發生變化 2.只能轉發站內

三.response 響應

1.響應包含的內容 響應行 響應狀態碼 200(成功) 302(重定向) 響應頭 告知瀏覽器資訊 響應體 響應的內容

public class Demo08 extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	    修改編碼格式並設定響應頭以什麼編碼格式解析響應
		response.setContentType("text/html;charset=UTF-8");
		利用response獲取字元流和位元組流
		PrintWriter writer = response.getWriter();
		writer.write("李四");
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}

下載圖片

public class Demo09 extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		ServletContext application = this.getServletContext();
		//獲取圖片在伺服器上的真實路徑
		String path = application.getRealPath("/WEB-INF/classes/哈哈.png");
		//通過file類獲取檔名
		File file1 = new File(path);
		String name = file1.getName();
		//設定圖片名的編碼格式 iso-8859-1
		name = new String(name.getBytes(), "iso-8859-1");
		//通過設定響應頭 告訴瀏覽器 要下載   content-disposition attachment;filename=圖片名(下載頭)
		response.setHeader("content-disposition", "attachment;filename=" + name);
		//設定下載內容的格式(web.xml裡查詢資源字尾的格式)
		response.setHeader("Content-type", "image/png");
		File file = new File(path);
		//使用位元組流讀取圖片
		FileInputStream fis = new FileInputStream(file);
		//使用響應中的位元組流,將圖片響應回瀏覽器
		ServletOutputStream sos = response.getOutputStream();
		byte[] b = new byte[1024];
		int len = 0;
		while ((len = fis.read(b)) != -1) {
			 sos.write(b, 0, len);
		}	
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}

2.請求重定向和重新整理頭

public class Demo10 extends HttpServlet{
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("借錢");
		//可以進行站內重定向也可以進行站外重定向  相對於8080 後的斜槓(需要帶上工程名)
		response.setHeader("location", "/sh-web-02/demo11");//站內
		// 新增重定向的狀態碼
		response.setStatus(302);
		 System.out.println("借錢完畢");
		 
		// 重新整理頭  3秒後重新整理頁面
		response.setHeader("refresh", "3;url=/sh-web-02/demo11");// 站內
		
		// 每隔一秒重新整理介面
		response.setIntHeader("refresh", 1);
	}
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}
}

public class Demo11 extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("錢借到了");
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}

重定向結果 1.重定向傳送了兩次請求(網址改變) 2.選執行完第一次請求的方法在進行第二次請求

借錢
借錢完畢
錢借到了

四.request 請求

public class Demo01 extends HttpServlet{
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 獲取請求的方式
		String method = request.getMethod();
		System.out.println(method);
		// 獲取使用者請求的URL(統一資源定位符)
		StringBuffer requestURL = request.getRequestURL();
		System.out.println(requestURL);//  http://localhost:8080/sh-web-02/demo12
		// 獲取使用者URI(統一資源識別符號)
		String requestURI = request.getRequestURI();
		System.out.println(requestURI);//  /sh-web-02/demo12
		
		// 獲取相對路徑
		String contextPath = request.getContextPath();
		System.out.println(contextPath);//  /sh-web-02
		// 獲取使用者請求的引數
		請求地址:
		http://localhost:8080/sh-web-02/demo12?username=lisi&password=123
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		System.out.println(username);
		System.out.println(password);
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}
}