java遍历http请求request的所有参数

java遍历http请求request的所有参数  
博客分类: 工作
 
Java .


 通过程序遍历http请求的所有参数放到hashmap中,用的时候方便了。

如果参数值有中文,那么需要在程序中添加filter转码,或者在下面程序里,对paramValue转码

 

 



Java代码 复制代码 收藏代码
1.public void doGet(HttpServletRequest request, HttpServletResponse response)  
2.      throws ServletException, IOException {  




Java代码 复制代码 收藏代码
1.Map map = new HashMap();  
2.     Enumeration paramNames = request.getParameterNames();  
3.    while (paramNames.hasMoreElements()) {  
4.      String paramName = (String) paramNames.nextElement();  
5.  
6.      String[] paramValues = request.getParameterValues(paramName);  
7.      if (paramValues.length == 1) {  
8.        String paramValue = paramValues[0];  
9.        if (paramValue.length() != 0) {  
10.          System.out.println("参数:" + paramName + "=" + paramValue);  
11.          map.put(paramName, paramValue);  
12.        }  
13.      }  
14.    }  




Java代码 复制代码 收藏代码
1.}  

 

 

 

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
  <title> moresubmit.jsp </title>
  <meta charset="UTF-8">
  <meta name="Author" content="">
  <meta name="Keywords" content="">
  <meta name="Description" content="">
 </head>

 <body>


<form method="post" action="servlet/showParameters">
<input type="text" name="msg">
<br>
<input type="submit" id="submit_save" name="method:save" value="保存"/>
<br>
<input type="submit" id="submit_print" name="method:print" value="打印"/>
<br>    
</form>

 </body>
</html>

 

 

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
        out.println("<HTML>");
        out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
        out.println("  <BODY>");
        Map<String, String[]> paras = request.getParameterMap();
        //Map<Integer, Integer> map = new HashMap<Integer, Integer>();           
        for (Map.Entry<String, String[]> entry : paras.entrySet()) {           
            out.println("Key = " + entry.getKey() + ", Value = " ); 
            String[] values= entry.getValue();
            for(String val:values)
            {
                out.println(val + "," ); 
            }            
            out.println("<BR>");          
        }  

        
        out.println("  </BODY>");
        out.println("</HTML>");
        out.flush();
        out.close();
    }

 

Key = method:print, Value = 打印, 
Key = msg, Value = PPP, 

 

posted @ 2017-05-24 09:55  sky20080101  阅读(1280)  评论(0)    收藏  举报