一、获取请求参数通用方式
1. String getParameter(String name):根据参数名称获取参数值 例:username=flypig&password=2343
2. String[] getParameterValues(String name):根据参数名称获取参数值的数组 例:hooby=xx&hobby=name
3. EnumerationgetParameterNames():获取所有请求的参数名称
4. MapgetParameterMap():获取所有参数的map集合
1 @WebServlet("/RequestDemo6") 2publicclass RequestDemo6extends HttpServlet { 3protectedvoid doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { 4//post 获取请求参数 5 6//根据参数名称获取参数值 7 String username = request.getParameter("username"); 8// System.out.println("post"); 9// System.out.println(username); 1011//根据参数名称获取参数值的数组12 String[] hobbies = request.getParameterValues("hobby"); 13// for (String hobby : hobbies) { 14// System.out.println(hobby); 15// } 1617//获取所有请求的参数名称1819 EnumerationparameterNames = request.getParameterNames(); 20// while(parameterNames.hasMoreElements()){ 21// String name = parameterNames.nextElement(); 22// System.out.print(name+":"); 23// String value = request.getParameter(name); 24// System.out.println(value); 25// } 2627//获取所有参数的map集合28 MapparameterMap = request.getParameterMap(); 29//遍历30 SetkeySet = parameterMap.keySet(); 31for (String name : keySet){ 3233//根据键获取值34 String[] values = parameterMap.get(name); 35 System.out.println(name); 36for (String value : values) { 37 System.out.println(value); 38 } 39 System.out.println("--------------"); 40 } 414243 } 4445protectedvoid doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { 46//get获取请求参数 4748//根据参数名称获取参数值 49// String username = request.getParameter("username"); 50// System.out.println("get"); 51// System.out.println(username);5253this.doPost(request,response); 54 } 55 }
二、解决乱码问题
解决请求参数中文乱码问题:
* get方式:tomcat 8已经将get方式乱码问题解决
* post方式:会乱码
*解决:在获取参数前,设置request的编码request.setCharacterEncoding("utf-8")
1 @WebServlet("/RequestDemo7") 2publicclass RequestDemo7extends HttpServlet { 3protectedvoid doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { 4 5//设置流的编码 6 request.setCharacterEncoding("utf-8"); 7 8//post 获取请求参数username 9 String username = request.getParameter("username"); 10 System.out.println(username); 1112 } 1314protectedvoid doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { 15//get获取请求参数 1617//根据参数名称获取参数值 18// String username = request.getParameter("username"); 19// System.out.println("get"); 20// System.out.println(username);2122this.doPost(request,response); 23 } 24 }