request请求获取参数的实现方法(post和get两种方式)
提交表单代码:
<!DOCTYPEhtml> <html> <head> <metacharset="UTF-8"> <title>Inserttitlehere</title> </head> <body> <h1>测试请求参数</h1> <!--注意href和action都是写的完整的名称:项目名和资源路径名--> <!--下面一句是get请求方式并在URL后面传值--> <ahref="/Web/AAServlet?xxx=王大炮&yyy=123456">点击这里</a> <hr/> <formaction="/Web/AAServlet"method="post"> 用户名:<inputtype="text"name="username"/><br/> 密码:<inputtype="password"name="password"/><br/> 性别:<inputtype="radio"name="sex"checked="checked"value="男">男 <inputtype="radio"name="sex"value="女">女<br/> 爱好:<inputtype="checkbox"name="hobby"value="吃饭"/>吃饭 <inputtype="checkbox"name="hobby"value="睡觉"/>睡觉 <inputtype="checkbox"name="hobby"value="打代码"/>打代码 <br/> <inputtype="submit"value="提交"/> </form> </body> </html>
Servlet代码:
packagerequest请求获取Post或者get参数;
importjava.io.IOException;
importjava.util.Arrays;
importjava.util.Enumeration;
importjava.util.Iterator;
importjava.util.Map;
importjavax.servlet.ServletException;
importjavax.servlet.annotation.WebServlet;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
/*
*演示request获取请求参数
*/
@WebServlet("/AAServlet")
publicclassAAServletextendsHttpServlet{
privatestaticfinallongserialVersionUID=1L;
protectedvoiddoGet(HttpServletRequestrequest,
HttpServletResponseresponse)throwsServletException,IOException{
System.out.println("get:"+request.getParameter("xxx"));
System.out.println("get:"+request.getParameter("yyy"));
}
protectedvoiddoPost(HttpServletRequestrequest,
HttpServletResponseresponse)throwsServletException,IOException{
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
Stringusername=request.getParameter("username");
Stringpassword=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(Stringname:map.keySet()){
String[]values=map.get(name);
System.out.println(name+"="+Arrays.toString(values));
}
}
}
以上就是小编为大家带来的request请求获取参数的实现方法(post和get两种方式)的全部内容了,希望对大家有所帮助,多多支持毛票票~