DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> 關於JavaScript >> request請求獲取參數的實現方法(post和get兩種方式)
request請求獲取參數的實現方法(post和get兩種方式)
編輯:關於JavaScript     

提交表單代碼:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>測試請求參數</h1>
<!-- 注意href和action都是寫的完整的名稱:項目名和資源路徑名 -->
<!-- 下面一句是get請求方式並在URL後面傳值 -->
<a href="/Web/AAServlet?xxx=王大炮&yyy=123456">點擊這裡</a>
<hr />

<form action="/Web/AAServlet" method="post">
	用戶名:<input type="text" name="username" /><br />
	密  碼:<input type="password" name="password" /><br />
	性  別:<input type="radio" name="sex" checked="checked" value="男">男
		 <input type="radio" name="sex" value="女">女<br />
	愛  好:<input type="checkbox" name="hobby" value="吃飯" />吃飯
		 <input type="checkbox" name="hobby" value="睡覺" />睡覺
		 <input type="checkbox" name="hobby" value="打代碼" />打代碼
	<br/>
	<input type="submit" value="提交" />
	</form>
</body>
</html>

Servlet代碼:

package request請求獲取Post或者get參數;

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

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

/*
 * 演示request獲取請求參數
 */
@WebServlet("/AAServlet")
public class AAServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		System.out.println("get:"+request.getParameter("xxx"));
		System.out.println("get:"+request.getParameter("yyy"));
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String[] hobby = request.getParameterValues("hobby");
		
		System.out.println(username+","+password+","+Arrays.toString(hobby));
		
		/*
		 * 測試獲取所有請求參數的名稱
		 */
		Enumeration<?> names2 = request.getParameterNames();
		while(names2.hasMoreElements()){
			System.out.println(names2.nextElement());
		}
//		Iterator<String> names = (Iterator<String>) request.getParameterNames();
//		while(names.hasNext()){
//			System.out.println(names.next());
//		}
		
		/*
		 * 獲取所有請求參數,封裝到Map中
		 */
			Map<String,String[]> map = (Map<String,String[]>)request.getParameterMap();
			for(String name:map.keySet()){
				String[] values = map.get(name);
				System.out.println(name+"="+Arrays.toString(values));
			}
		}

}

以上就是小編為大家帶來的request請求獲取參數的實現方法(post和get兩種方式)的全部內容了,希望對大家有所幫助,多多支持~

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved