Java 如何从 HttpServletRequest (Tomcat 9.0) 获取查询参数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39509892/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 21:12:46  来源:igfitidea点击:

How to get query parameters from HttpServletRequest (Tomcat 9.0)?

javatomcatservlets

提问by Katrikken

The server recieves requests from two clients - Raspberry Pi and Android app, both send requests using HttpURLConnection. I need to pass parameters with theese requests, e.g:

服务器接收来自两个客户端的请求 - Raspberry Pi 和 Android 应用程序,两者都使用 HttpURLConnection 发送请求。我需要通过这些请求传递参数,例如:

http://192.168.0.10:8080/MyProject/MyServer/rpi/checktask?rpi="rpi"

doing it as:

这样做:

String requestUrl = "http://192.168.0.10:8080/MyProject/MyServer/rpi";
String query = String.format("/checktask?rpi=%s",
                        URLEncoder.encode("rpi", "UTF-8"));
URL url = new URL(requestUrl + query);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setRequestProperty("Accept-Charset", "UTF-8");
conn.connect();

The Servlet has annotation:

Servlet 有注释:

@WebServlet(name = "MyServer", urlPatterns = { "/MyServer/rpi/*", "/MyServer/app/*"})

But when Servlet gets request as above following happens:

但是当 Servlet 收到上述请求时,会发生以下情况:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

String path = request.getRequestURI();     // /MyProject/MyServer/rpi/*
String query = request.getQueryString();   // null
String context = request.getContextPath(); // /MyProject
String servlet = request.getServletPath(); // /MyServer/rpi
String info = request.getPathInfo();       // /*
}

Although according to those answers: How to use @WebServlet to accept arguments (in a RESTFul way)?and How come request.getPathInfo() in service method returns null?

虽然根据这些答案: How to use @WebServlet to accept arguments (in a RESTFul way)? 如何在服务方法返回null来request.getPathInfo()?

it should look like this:

它应该是这样的:

String path = request.getRequestURI();     // /MyProject/MyServer/rpi//checktask?rpi="rpi"
String query = request.getQueryString();   // rpi="rpi"
String context = request.getContextPath(); // /MyProject
String servlet = request.getServletPath(); // /MyServer/rpi
String info = request.getPathInfo();       // /checktask?rpi="rpi"

What am I doing wrong?

我究竟做错了什么?

回答by Rohit Gaikwad

Your URL string is

您的网址字符串是

http://192.168.0.10:8080/MyProject/MyServer/rpi/checktask?rpi="rpi" 

The name of the parameter in the above String is "rpi".

上述字符串中的参数名称为“ rpi”。

The below code will give you the required value of the parameter "rpi".

以下代码将为您提供参数“rpi”所需的值。

String rpi = request.getParameter("rpi");