Java_Web------ServletRequest實現

    

Java_Web------ServletRequest實現

  • public interface ServletRequest

    Defines an object to provide client request information to a servlet. The servlet container creates a ServletRequest object and passes it as an argument to the servlet's service method.

    A ServletRequest object provides data including parameter name and values, attributes, and an input stream. Interfaces that extend ServletRequest can provide additional protocol-specific data (for example, HTTP data is provided by HttpServletRequest.


    ServletRequest是一個Java EE 接口,其中HttpServletRequest是其子接口。這兩個接口封裝了許多處理web請求的相關方法,如獲取參數名稱Name、Names,通過參數名稱獲取參數值、獲取請求協議、request請求URI、URL等,功能非常強大!下面僅列舉自己練習的幾個方法,更多方法可以參考Java EE API。

    最後總結:今天我發現查看英文文檔其實並沒有想象中的那麼難,只是每看一行需要花額外多一點點的時間而已!這時間很短,但我感覺對於學習階段的我來說,看英文文檔是很有幫助的,個人感覺很爽!不懂可以下載個有道詞典嘛!

    在一個Servlet中重寫一個service()方法
@Override
	public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
		
		System.out.println("servie......");
		//通過request對象獲取參數值
		String user = request.getParameter("user");
		
		String password = request.getParameter("password");
		
		System.out.println(user+":  "+password);
		
		//獲取當前請求的所有參數名稱
		Enumeration<String>  names = request.getParameterNames();
		
		while(names.hasMoreElements()){
			
			String name = names.nextElement();
			
			System.out.println(name);
		}
		
		//獲取指定參數名的所有value
		String [] values = request.getParameterValues("0");
		
		for(String value : values){
		
			System.out.println(value);
		
		}
		//遍歷Map集合中的鍵值對(key-value)
		Map<String,String[]> map = request.getParameterMap();
		
		for (Map.Entry<String, String[]> entry : map.entrySet()) {
			System.out.println("^^"+entry.getKey() + ": "+ Arrays.asList(entry.getValue()));
		}
		
		System.out.println("==================");
		System.out.println("協議名稱和版本爲:"+request.getProtocol());
		System.out.println("服務器名"+request.getServerName()+" ,服務器端口號: "+request.getServerPort());
		System.out.println("該請求是否是安全的(即https://)"+request.isSecure());
		
		//HttpServletRequest是ServletRequest的一個子接口
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		
		String httpRequestURL =new String(httpServletRequest.getRequestURL());
		System.out.println("Request的URL爲:"+httpRequestURL);
		
		String method = httpServletRequest.getMethod();
		System.out.println("Request請求的方式爲: "+ method);


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