在servlet中GET请求能够经过HttpServletRequest的getRequestURL方法和getQueryString()获得完整的请求路径和请求全部参数列表,POST的须要getPa

转自:http://www.zuidaima.com/share/1550463555308544.htmjava

**在servlet中GET请求能够经过HttpServletRequest的getRequestURL方法和getQueryString()获得完整的请求路径和请求全部参数列表,POST的须要getParameterMap()方法遍历获得,不论GET或POST均可以经过getRequestURL+getParameterMap()来获得请求完整路径

** [java] view plain copy print?在CODE上查看代码片派生到个人代码片ui

package com.zuidaima                          
import java.io.IOException;  
import java.io.PrintWriter;  
import java.util.Map;  
  
import javax.servlet.ServletException;  
import javax.servlet.http.HttpServlet;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
  
public class GetParams extends HttpServlet {  
    private static final long serialVersionUID = 1L;  
  
    public GetParams() {  
        super();  
    }  
  
    protected void doGet(HttpServletRequest request,  
            HttpServletResponse response) throws ServletException, IOException {  
        PrintWriter writer = response.getWriter();  
        writer.println("GET " + request.getRequestURL() + " "  
                + request.getQueryString());  
  
        Map<String, String[]> params = request.getParameterMap();  
        String queryString = "";  
        for (String key : params.keySet()) {  
            String[] values = params.get(key);  
            for (int i = 0; i < values.length; i++) {  
                String value = values[i];  
                queryString += key + "=" + value + "&";  
            }  
        }  
        // 去掉最后一个空格  
        queryString = queryString.substring(0, queryString.length() - 1);  
        writer.println("GET " + request.getRequestURL() + " " + queryString);  
    }  
  
    protected void doPost(HttpServletRequest request,  
            HttpServletResponse response) throws ServletException, IOException {  
        PrintWriter writer = response.getWriter();  
        Map<String, String[]> params = request.getParameterMap();  
        String queryString = "";  
        for (String key : params.keySet()) {  
            String[] values = params.get(key);  
            for (int i = 0; i < values.length; i++) {  
                String value = values[i];  
                queryString += key + "=" + value + "&";  
            }  
        }  
        // 去掉最后一个空格  
        queryString = queryString.substring(0, queryString.length() - 1);  
        writer.println("POST " + request.getRequestURL() + " " + queryString);  
    }  
}
相关文章
相关标签/搜索