request请求获取参数(post和get两种方式)

提交表单代码:





Insert title here


测试请求参数

点击这里
用户名:
密 码:
性 别:
爱 好:吃饭 睡觉 打代码

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 names = (Iterator) request.getParameterNames();
//		while(names.hasNext()){
//			System.out.println(names.next());
//		}
		
		/*
		 * 获取所有请求参数,封装到Map中
		 */
			Map map = (Map)request.getParameterMap();
			for(String name:map.keySet()){
				String[] values = map.get(name);
				System.out.println(name+"="+Arrays.toString(values));
			}
		}

}


你可能感兴趣的:(Servlet和Jsp)