request请求获取参数的实现方法(post和get两种方式

编程学习 2021-07-04 20:00www.dzhlxh.cn编程入门
狼蚁网站SEO优化长沙网络推广就为大家带来一篇request请求获取参数的实现方法(post和get两种方式)。长沙网络推广觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随长沙网络推广过来看看吧

提交表单代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>测试请求参数</h1>
<!-- 注意href和action都是写的完整的名称:项目名和资源路径名 -->
<!-- 狼蚁网站SEO优化一句是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两种方式)的全部内容了,希望对大家有所帮助,多多支持狼蚁SEO~

Copyright © 2016-2025 www.dzhlxh.cn 金源码 版权所有 Power by

网站模板下载|网络推广|微博营销|seo优化|视频营销|网络营销|微信营销|网站建设|织梦模板|小程序模板