转载:http://blog.csdn.net/yaerfeng/article/details/18942739
在servlet中GET请求可以通过HttpServletRequest的getRequestURL方法和getQueryString()得到完整的请求路径和请求所有参数列表,POST的需要getParameterMap()方法遍历得到,不论GET或POST都可以通过getRequestURL+getParameterMap()来得到请求完整路径
- 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);
- }
- }
PUT 请求获取不到参数,是因为 PUT 请求的参数不是存放在 HTTP Header 中的,而是在 HTTP Body 中,所以无法通过 request.getParameter() 方法来获取参数。
如果想要获取 PUT 请求的参数,可以参考如下这段代码:
1
2
3
4
5
6
|
String queryString = "" ;
BufferedReader reader = new BufferedReader( new InputStreamReader(request.getInputStream()));
String line; while ((line = reader.readLine()) != null ) {
queryString += line;
} |
拿到了 queryString,它是一个“a=1&b=2”格式的字符串,然后可以轻松的转换成一个 Map,最后通过 map.get() 方法获取指定的参数。