JavaWeb-HTTPServletReauest和HTTPServletResponse

HttpServletRequest 和 HttpServletResponse

Servlet配置方式

  • 1. 全路徑匹配

以 / 開始 /a /aa/bbcss

localhost:8080/項目名稱/aa/bbhtml

  • 2. 路徑匹配 , 前半段匹配

以 / 開始 , 可是以 * 結束 /a/* /*java

  • 實際上是一個通配符,匹配任意文字

localhost:8080/項目名稱/aa/bbweb

  • 3. 以擴展名匹配

寫法: 沒有/ 以 * 開始 *.擴展名 *.aa *.bb數據庫

ServletContext

Servlet 上下文apache

每一個web工程都只有一個ServletContext對象。 說白了也就是無論在哪一個servlet裏面,獲取到的這個類的對象都是同一個。數組

如何獲得對象

//1. 獲取對象
    ServletContext context = getServletContext();

有什麼做用

  1. 獲取全局配置參數
  2. 獲取web工程中的資源
  3. 存取數據,servlet間共享數據 域對象

.能夠獲取全局配置參數

獲取全局參數瀏覽器

. 能夠獲取Web應用中的資源

1. 獲取資源在tomcat裏面的絕對路徑

    先獲得路徑,而後本身new InpuStream

        context.getRealPath("") //這裏獲得的是項目在tomcat裏面的根目錄。

        D:\tomcat\apache-tomcat-7.0.52\apache-tomcat-7.0.52\wtpwebapps\Demo03\

        String path = context.getRealPath("file/config.properties");

        D:\tomcat\apache-tomcat-7.0.52\apache-tomcat-7.0.52\wtpwebapps\Demo03\file\config.properties


2. getResourceAsStream 獲取資源 流對象

    直接給相對的路徑,而後獲取流對象。

經過classloader去獲取web工程下的資源

使用ServletContext存取數據。

  1. 定義一個登錄的html頁面, 定義一個form表單

  1. 定義一個Servlet,名爲LoginServlet

  1. 針對成功或者失敗,進行判斷,而後跳轉到不同的網頁

所有代碼

package com.wby.servlet.context;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
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 LoginServlet extends HttpServlet{
	PrintWriter pw;
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//獲取參數
		String nameString=req.getParameter("username");
		String passwordString=req.getParameter("password");
		System.out.println(nameString);
		System.out.println(passwordString);

	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//獲取參數
		String nameString=req.getParameter("username");
		String passwordString=req.getParameter("password");
		System.out.println("post"+nameString);
		System.out.println("post"+passwordString);
		
		PrintWriter pWriter=resp.getWriter();
		
		
		if ("wby".equals(nameString)&&"123".equals(passwordString)) {
			
			try {
				Object obj =getServletContext().getAttribute("count") ; 
				int totalCount=0;
				if (obj!=null) {
					totalCount=(int) obj;
				}
				System.out.println("一直登陸成功次數:"+totalCount);
				getServletContext().setAttribute("count", totalCount+1);
			} catch (NullPointerException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			resp.setStatus(302);
			resp.setHeader("Location", "sucess.html");
			//pWriter.write("sucess");
		}else {
			pWriter.write("faile");
		}
		
	}
}
package com.wby.servlet.context;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
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 SuccessServlet extends HttpServlet{
	PrintWriter pw;
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		try {
			int count=(int) getServletContext().getAttribute("count");
			resp.getWriter().write("denglu次數:"+count);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		int count=(int) getServletContext().getAttribute("count");
		resp.getWriter().write("denglu次數:"+count);
		
	}
}
<!DOCTYPE html>
<html>
  <head>
    <title>login.html</title>
	
    <meta name="keywords" content="keyword1,keyword2,keyword3">
    <meta name="description" content="this is my page">
    <meta name="content-type" content="text/html; charset=UTF-8">
    
    <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->

  </head>
  
  <body>
    <form action="log" method="post">
    	帳號:<input type="text" name="username"></br>
    	密碼:<input type="text" name="password"></br>
    	提交:<input type="submit" value="登陸"></br>
    </form>
  </body>
</html>
<!DOCTYPE html>
<html>
  <head>
    <title>login.html</title>
	
    <meta name="keywords" content="keyword1,keyword2,keyword3">
    <meta name="description" content="this is my page">
    <meta name="content-type" content="text/html; charset=UTF-8">
    
    <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->

  </head>
  
  <body>
    <a href="count">獲取登陸總數</a>
  </body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
  <display-name>Servlet</display-name>
  <welcome-file-list>
    <welcome-file>login.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
  <!-- servletContext:全局參數 -->
 
  <servlet>
  	<servlet-name>login</servlet-name>
  	<servlet-class>com.wby.servlet.context.LoginServlet</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>login</servlet-name>
  	<url-pattern>/log</url-pattern>
  </servlet-mapping>
  
  <servlet>
  	<servlet-name>count</servlet-name>
  	<servlet-class>com.wby.servlet.context.SuccessServlet</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>count</servlet-name>
  	<url-pattern>/count</url-pattern>
  </servlet-mapping>
</web-app>

ServletContext存取值分析

細節:

<!--    
    A路徑: Servlet的路徑
        http://localhost:8080/Demo4/login

    B路徑: 當前這個html的路徑:
        http://localhost:8080/Demo4/login.html -->


    <form action="login" method="get">
        帳號:<input type="text" name="username"/><br>
        密碼:<input type="text" name="password"/><br>
        <input type="submit" value="登陸"/>
    </form>

ServletContext 什麼時候建立, 什麼時候銷燬?

服務器啓動的時候,會爲託管的每個web應用程序,建立一個ServletContext對象tomcat

從服務器移除託管,或者是關閉服務器。服務器

  • ServletContext 的做用範圍

只要在這個項目裏面,均可以取。 只要同一個項目。 A項目 存, 在B項目取,是取不到的? ServletContext對象不一樣。

HttpServletRequest

這個對象封裝了客戶端提交過來的一切數據。

  1. 能夠獲取客戶端請求頭信息

    //獲得一個枚舉集合  
    Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String name = (String) headerNames.nextElement();
        String value = request.getHeader(name);
        System.out.println(name+"="+value);
    
    }
  2. 獲取客戶端提交過來的數據

    String name = request.getParameter("name");
    String address = request.getParameter("address");
    System.out.println("name="+name);
    System.out.println("address="+address);
    
    -------------------------------------------------
    
    //name=zhangsan&name=lisi&name=wangwu 一個key能夠對應多個值。
    
    Map<String, String[]> map = request.getParameterMap();
    
    Set<String> keySet = map.keySet();
    Iterator<String> iterator = keySet.iterator();
    while (iterator.hasNext()) {
        String key = (String) iterator.next();
        System.out.println("key="+key + "--的值總數有:"+map.get(key).length);
        String value = map.get(key)[0];
        String value1 = map.get(key)[1];
        String value2 = map.get(key)[2];
    
        System.out.println(key+" ======= "+ value + "=" + value1 + "="+ value2);
    }
  3. 獲取中文數據

客戶端提交數據給服務器端,若是數據中帶有中文的話,有可能會出現亂碼狀況,那麼能夠參照如下方法解決。

  • 若是是GET方式

    1. 代碼轉碼 String username = request.getParameter("username"); String password = request.getParameter("password");

      System.out.println("userName="+username+"==password="+password);
      
      //get請求過來的數據,在url地址欄上就已經通過編碼了,因此咱們取到的就是亂碼,
      //tomcat收到了這批數據,getParameter 默認使用ISO-8859-1去解碼
      
      //先讓文字回到ISO-8859-1對應的字節數組 , 而後再按utf-8組拼字符串
      username = new String(username.getBytes("ISO-8859-1") , "UTF-8");
      System.out.println("userName="+username+"==password="+password);
      
      直接在tomcat裏面作配置,之後get請求過來的數據永遠都是用UTF-8編碼。
    2. 能夠在tomcat裏面作設置處理 conf/server.xml 加上URIEncoding="utf-8"

       

  • 若是是POST方式

    這個說的是設置請求體裏面的文字編碼。  get方式,用這行,有用嗎? ---> 沒用
    request.setCharacterEncoding("UTF-8");
    
    這行設置必定要寫在getParameter以前。

HttpServletResponse

負責返回數據給客戶端。

  • 輸出數據到頁面上

    //以字符流的方式寫數據    
    //response.getWriter().write("<h1>hello response...</h1>");
    
    //以字節流的方式寫數據 
    response.getOutputStream().write("hello response2222...".getBytes());

響應的數據中有中文,那麼有可能出現中文亂碼

  • 以字符流輸出

response.getWriter()

//1. 指定輸出到客戶端的時候,這些文字使用UTF-8編碼
    response.setCharacterEncoding("UTF-8");

    //2. 直接規定瀏覽器看這份數據的時候,使用什麼編碼來看。
    response.setHeader("Content-Type", "text/html; charset=UTF-8");

    response.getWriter().write("我愛黑馬訓練營...");
  • 以字節流輸出

response.getOutputStream()

//1. 指定瀏覽器看這份數據使用的碼錶
    response.setHeader("Content-Type", "text/html;charset=UTF-8");

    //2. 指定輸出的中文用的碼錶
    response.getOutputStream().write("我愛深圳黑馬訓練營..".getBytes("UTF-8"));


    --------------------------------------------

不論是字節流仍是字符流,直接使用一行代碼就能夠了。

response.setContentType("text/html;charset=UTF-8");

而後在寫數據便可。

演練下載資源。

  1. 直接以超連接的方式下載,不寫任何代碼。 也可以下載東西下來。

    讓tomcat的默認servlet去提供下載:
    aa.jpg
    bb.txt
    cc.rar

緣由是tomcat裏面有一個默認的Servlet -- DefaultServlet 。這個DefaultServlet 專門用於處理放在tomcat服務器上的靜態資源。

總結

  1. Servlet註冊方式

  2. ServletContext【重點】

    做用:
    
        1. 獲取全局參數
    
        2. 獲取工程裏面的資源。
    
        3. 資源共享。  ServletContext 域對象
    
    有幾個 一個 
    
    何時建立 ? 何時銷燬
    
    服務器啓動的時候給每個應用都建立一個ServletContext對象, 服務器關閉的時候銷燬

    簡單登陸

  3. HttpServletRequest【重點】

    1. 獲取請求頭
    
    2. 獲取提交過來的數據
  4. HttpServletResponse【重點】

    負責輸出數據到客戶端,其實就是對以前的請求做出響應
  5. 中文亂碼問題。【重點】

  6. 下載

練習:

1. 完成註冊 

2. 完成登陸

V1.1 最好配合上數據庫,完成註冊和登陸的功能。

代碼演示

    demo

package com.itheima.servlet;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
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;

/**
 * Servlet implementation class Demo03
 */
public class Demo03 extends HttpServlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		/*test01();*/
		//test02();
		test03();
		

	}

	/**
	 * 根據classloader去獲取工程下的資源    類加載器(JDBC)
	 */
	private void test03() {
		try {
			// 1. 建立屬性對象
			Properties properties = new Properties();
			
			//獲取該java文件的class ,而後獲取到加載這個class到虛擬機中的那個類加載器對象。
			
			/*
			 * ServletContext
			 * a路徑--工程在tomcat裏面的目錄
			 * 			D:\tomcat\apache-tomcat-7.0.52\apache-tomcat-7.0.52\wtpwebapps\Demo03
			 * 
			 * ClassLoader 
			 * 
			 * a路徑: D:\tomcat\apache-tomcat-7.0.52\apache-tomcat-7.0.52\wtpwebapps\Demo03\WEB-INF\classes
			 * 
			 * 默認的lcassloader 的路徑是上面這個路徑,咱們必須得回到Demo03這個目錄下,才能進入file目錄。如何回到上一級目錄呢?
			 *  ../../  ---  D:\tomcat\apache-tomcat-7.0.52\apache-tomcat-7.0.52\wtpwebapps\Demo03
			 * ../../file/config.properties  --- D:\tomcat\apache-tomcat-7.0.52\apache-tomcat-7.0.52\wtpwebapps\Demo03\file\config.properties

			 * b路徑: D:\tomcat\apache-tomcat-7.0.52\apache-tomcat-7.0.52\wtpwebapps\Demo03\file\config.properties
			 */
//			System.out.println(getClass().getClassLoader());
			InputStream is = this.getClass().getClassLoader().getResourceAsStream("../../file/config.properties");
			properties.load(is);
			// 3. 獲取name屬性的值
			String name = properties.getProperty("name");
			System.out.println("name333333=" + name);
			is.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 根據相對路徑,直接獲取流對象
	 */
	private void test02() {
		try {
			// 獲取ServletContext對象
			ServletContext context = getServletContext();
			
			// 1. 建立屬性對象
			Properties properties = new Properties();
			
			//獲取web工程下的資源,轉化成流對象。  前面隱藏當前工程的根目錄。 
			/*
			 * 相對路徑 (有參照物) 相對誰?
			 * 
			 * 		工程在tomcat裏面的根目錄。
			 * 
			 * 	a路徑--工程在tomcat裏面的目錄
			 * 			D:\tomcat\apache-tomcat-7.0.52\apache-tomcat-7.0.52\wtpwebapps\Demo03
			 * 	b路徑---			
			 * 			file\config.properties
			 * 
			 * 			D:\tomcat\apache-tomcat-7.0.52\apache-tomcat-7.0.52\wtpwebapps\Demo03\file\config.properties
			 * 	
			 * 
			 * 絕對路徑 (沒有參照物)
			 * 
			 * 		D:\tomcat\apache-tomcat-7.0.52\apache-tomcat-7.0.52\wtpwebapps\Demo03\file\config.properties
			 * 
			 */
			InputStream is = context.getResourceAsStream("file/config.properties");
			properties.load(is);
			// 3. 獲取name屬性的值
			String name = properties.getProperty("name");
			System.out.println("name22=" + name);
			is.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 先獲取路徑,在獲取流對象
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	private void test01() throws FileNotFoundException, IOException {
		// 獲取ServletContext對象
		ServletContext context = getServletContext();
		//獲取給定的文件在服務器上面的絕對路徑。
		String path = context.getRealPath("file/config.properties");
		System.out.println("path="+path);
		
		// 1. 建立屬性對象
		Properties properties = new Properties();
		InputStream is = new FileInputStream(path);
		properties.load(is);

		// 3. 獲取name屬性的值
		String name = properties.getProperty("name");

		System.out.println("name=" + name);
	}

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

}

    demo2

        LoginServlet

package com.itheima.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

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

public class LoginServlet extends HttpServlet {
	
	

	/**
	 * request : 包含請求的信息
	 * 
	 * response : 響應數據給瀏覽器, 就靠這個對象
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	
		
		//1. 獲取數據
		String userName = request.getParameter("username");
		String password = request.getParameter("password");
		
		System.out.println("userName="+userName+"==password="+password);
		//2. 校驗數據
		
		//向客戶端輸出內容
		PrintWriter pw = response.getWriter();
		
		if("admin".equals(userName) && "123".equals(password)){
			//System.out.println("登陸成功");
//			pw.write("login success..");
			//成功就跳轉到login_success.html
			
			//1. 成功的次數累加
			
			//獲取之前存的值 , 而後在舊的值基礎上  + 1 
			Object obj = getServletContext().getAttribute("count") ; 
			
			//默認就是0次
			int totalCount = 0 ;
			if(obj != null){
				totalCount = (int) obj;
			}
			
			System.out.println("已知登陸成功的次數是:"+totalCount);
			
			//給這個count賦新的值
			getServletContext().setAttribute("count", totalCount+1);
			
			
			//2. 跳轉到成功的界面 
			//設置狀態碼? 從新定位 狀態碼
			response.setStatus(302);
			//定位跳轉的位置是哪個頁面。
			response.setHeader("Location", "login_success.html");
		}else{
			pw.write("login failed..");
		}
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

            CountSrevlet

package com.itheima.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 CountSrevlet
 */
public class CountSrevlet extends HttpServlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		//1. 取值
		int count = (int) getServletContext().getAttribute("count");
		
		//2. 輸出到界面
		
		response.getWriter().write("login success count ===:"+count);
	
	}

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

}

    DownLoadDemo

package com.itheima.servlet;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

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

/**
 * Servlet implementation class Demo01
 */
public class Demo01 extends HttpServlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		//1. 獲取要下載的文件名字 aa.jpg  --- inputStream
		String fileName = request.getParameter("filename");
		
		//2. 獲取這個文件在tomcat裏面的絕對路徑地址
		String path = getServletContext().getRealPath("download/"+fileName);
		
		//讓瀏覽器收到這份資源的時候, 如下載的方式提醒用戶,而不是直接展現。 
		response.setHeader("Content-Disposition", "attachment; filename="+fileName);
		
//		response.setStatus(302);
//		response.setHeader(Location, "login_success.html");
		
		//
		response.sendRedirect("login_success.html");
		
		//3. 轉化成輸入流
		InputStream is = new FileInputStream(path);
		OutputStream os = response.getOutputStream();
		
		int len = 0 ;
		byte[]buffer = new byte[1024];
		while( (len = is.read(buffer)) != -1){
			os.write(buffer, 0, len);
		}
		
		os.close();
		is.close();
	
	}

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

}

    RequestDemo01

package com.itheima.servlet;

import java.io.IOException;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

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

public class Demo01 extends HttpServlet {
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	
		//1. 取出請求裏面的全部頭信息  ---- 獲得一個枚舉集合  
		Enumeration<String> headerNames = request.getHeaderNames();
		while (headerNames.hasMoreElements()) {
			String name = (String) headerNames.nextElement();
			String value = request.getHeader(name);
			System.out.println(name+"="+value);
			
		}
		
		System.out.println("-----------------------");
		
		//2. 獲取到的是客戶端提交上來的數據
		String name = request.getParameter("name");
		String address = request.getParameter("address");
		System.out.println("name="+name);
		System.out.println("address="+address);
		
		System.out.println("-----------------------");
		
//		獲取全部的參數,獲得一個枚舉集合
//		Enumeration<String> parameterNames = request.getParameterNames();
		
//		name=zhangsan&address=beijing
		
		//name=zhangsan&name=lisi&name=wangwu
		
		Map<String, String[]> map = request.getParameterMap();
		
		Set<String> keySet = map.keySet();
		Iterator<String> iterator = keySet.iterator();
		while (iterator.hasNext()) {
			String key = (String) iterator.next();
			System.out.println("key="+key + "--的值總數有:"+map.get(key).length);
			String value = map.get(key)[0];
			String value1 = map.get(key)[1];
			String value2 = map.get(key)[2];
			
			System.out.println(key+" ======= "+ value + "=" + value1 + "="+ value2);
		}
		
	}

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

}

    RequestDemo02

package com.itheima.servlet;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

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

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		//這個說的是設置請求體裏面的文字編碼。  get方式,用這行,有用嗎? ---> get
		request.setCharacterEncoding("UTF-8");
		
		
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		//test01(username, password);
		//post過來的數據亂碼處理: 
		System.out.println("post : userName="+username+"==password="+password);
		
	}

	
	/**
	 * 處理get請求過來的數據亂碼
	 * @param username
	 * @param password
	 * @throws UnsupportedEncodingException
	 */
	private void test01(String username, String password) throws UnsupportedEncodingException {
		System.out.println("userName="+username+"==password="+password);
		
		//get請求過來的數據,在url地址欄上就已經通過編碼了,因此咱們取到的就是亂碼,
		//tomcat收到了這批數據,getParameter 默認使用ISO-8859-1去解碼
		
		//先讓文字回到ISO-8859-1對應的字節數組 , 而後再按utf-8組拼字符串
		username = new String(username.getBytes("ISO-8859-1") , "UTF-8");
		System.out.println("userName="+username+"==password="+password);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("來了一個post請求...");
		doGet(request, response);
	}

}

    ResponseDemo01

package com.itheima.servlet;

import java.io.IOException;
import java.nio.charset.Charset;

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


public class Demo01 extends HttpServlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	
//		test01(response);
		
//		test03(response);
		
		//以字節流輸出
		
		/*
		 * 若是想讓服務器端出去的中文,在客戶端可以正常顯示。只要確保一點。
		 * 
		 * 出去的時候用的編碼 , 和 客戶端看這份數據用的編碼 是同樣的。 
		 * 
		 * 默認狀況下getOutputStream 輸出使用的是UTF-8的碼錶 。 若是想指定具體的編碼,能夠在獲取byte數組的時候,指定。 
		 * 
		 * 
		 * 
		 */
		
		//設置響應的數據類型是html文本,而且告知瀏覽器,使用UTF-8 來編碼。 
		response.setContentType("text/html;charset=UTF-8");
		
		
		//String這個類裏面, getBytes()方法使用的碼錶,是UTF-8,  跟tomcat的默認碼錶不要緊。 tomcat iso-8859-1
		 String csn = Charset.defaultCharset().name();
		 
		 System.out.println("默認的String裏面的getBytes方法使用的碼錶是: "+ csn);
		
		//1. 指定瀏覽器看這份數據使用的碼錶
//		response.setHeader("Content-Type", "text/html;charset=UTF-8");
		
		//2. 指定輸出的中文用的碼錶
		response.getOutputStream().write("我愛深圳黑馬訓練營..".getBytes("UTF-8"));
		
	}
	
	void test03(HttpServletResponse response){
		//響應的數據中包含中文---> 亂碼。 以字符流輸出
		
				try {
					//這裏寫出去的文字,默認使用的是ISO-8859-1 ,咱們能夠指定寫出去的時候,使用什麼編碼寫
					//1. 指定輸出到客戶端的時候,這些文字使用UTF-8編碼
					response.setCharacterEncoding("UTF-8");
					//2. 直接規定瀏覽器看這份數據的時候,使用什麼編碼來看。
					response.setHeader("Content-Type", "text/html; charset=UTF-8");
					response.getWriter().write("我愛黑馬訓練營...");
				} catch (Exception e) {
				}
	}
	
	void test01(HttpServletResponse response){
		//以字符流的方式寫數據	
				//response.getWriter().write("<h1>hello response...</h1>");
				
				try {
					//以字節流的方式寫數據 
					response.getOutputStream().write("hello response2222...".getBytes());
				} catch (Exception e) {
					// TODO: handle exception
				}
				
				
				//設置當前這個請求的處理狀態碼
				//response.setStatus("");
				
				//設置一個頭
				//response.setHeader(name, value);
				
				//設置響應的內容類型,以及編碼。
				//response.setContentType(type);
	}
	
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}

    SerlvetContextDemo

package com.itheima.servlet;

import java.io.IOException;

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

/**
 * Servlet implementation class ServletContext01
 */
public class ServletContext01 extends HttpServlet {
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		//1. 獲取對象
	/*	ServletContext context = getServletContext();
		String address = context.getInitParameter("address");
		System.out.println("這是01獲取的數據::address="+address);*/
		
		test();
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//		doGet(request, response);
		
		//1. 獲取對象
			/*	ServletContext context = getServletContext();
				String address = context.getInitParameter("address");
				System.out.println("這是01獲取的數據::address="+address);*/
		
		test();
	}
	
	void test(){
		ServletContext context = getServletContext();
		String address = context.getInitParameter("address");
		System.out.println("這是01獲取的數據::address="+address);
	}

}
package com.itheima.servlet;

import java.io.IOException;

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

/**
 * Servlet implementation class ServletContext02
 */
public class ServletContext02 extends HttpServlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	
		//1. 獲取對象
		ServletContext context = getServletContext();
		String address = context.getInitParameter("address");
		System.out.println("這是02獲取的數據:::address="+address);
	}

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

}

    ServletContextDemo02

package com.itheima.servlet;

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

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

/**
 * Servlet implementation class Demo02
 */
public class Demo02 extends HttpServlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	
		//1. 建立屬性對象
		Properties properties = new Properties();
		
		//2. 指定載入的數據源
		/*
		 * 此處,若是想獲取web工程下的資源,用普通的FileInputStream 寫法是不OK 的。
		 * 由於路徑不對了。  這裏相對的路徑,實際上是根據jre來肯定的。 可是咱們這是一個web工程,
		 * jre 後面會由tomcat管理,因此這裏真正相對的路徑是 tomcat裏面的bin目錄
		 */
		InputStream is = new FileInputStream("classes/config.properties");
		properties.load(is);
		
		//3. 獲取name屬性的值
		String name = properties.getProperty("name");
	
		System.out.println("name="+name);
	}

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

}

    TestRegister

package com.itheima.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 ServletRegister
 */
public class ServletRegister extends HttpServlet {
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//response.getWriter().append("Served at: ").append(request.getContextPath());
		
		aa();
	}
	
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//aa();
		
		doGet(request, response);
		
	}
	
	void aa(){
		System.out.println("來了一個請求..");
		System.out.println("來了一個請求..");
		System.out.println("來了一個請求..");
		System.out.println("來了一個請求..");
		System.out.println("來了一個請求..");
		System.out.println("來了一個請求..");
		System.out.println("來了一個請求..");
		System.out.println("來了一個請求..");
		System.out.println("來了一個請求..");
		System.out.println("來了一個請求..");
		System.out.println("來了一個請求..");
	}

}
相關文章
相關標籤/搜索