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

时间:2016-09-15 11:24:37

标签: java tomcat servlets

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

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

这样做:

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();

Servlet有注释:

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

但是,当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();       // /*
}

虽然根据这些答案: How to use @WebServlet to accept arguments (in a RESTFul way)?How come request.getPathInfo() in service method returns null?

它应该是这样的:

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"

我做错了什么?

1 个答案:

答案 0 :(得分:10)

您的网址字符串是

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

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

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

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