我无法从请求中检索值。
小服务程序:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String location_id = request.getReader().readLine(); // <---- null
location_id = request.getParameter("location_id"); // <--- null
PrintWriter out = response.getWriter();
out.write(this.get_events_json(location_id));
}
在客户端:
$.get("EventServe", {location_id : location_id}).done(function() {
var events = JSON.parse(responseText);
outer_this.events = events.map(function(event){
var event = new Event(event.address, event.name, event.event_start, event.event_end)
return event;
});
outer_this.events.map(function(event){outer_this.insert_event(event)});
});
我也试过在不使用 jQuery 的情况下直接传递它,只使用文字。
最佳答案
当您使用 $.get('EventServe', {location_id: location_id}, ...)
发出 HTTP GET
请求时,您传递的是值location_id
作为指定 URL 的查询字符串参数。本质上,您请求的是:EventServe?location_id=4
,其中 4 是 location_id
的值。
在服务器端,您可以通过getParameter(String name)
访问查询字符串参数。 :
public void doGet(...) {
String locationId = request.getParameter("location_id");
}
一些额外的注意事项:
- 您应该删除对
request.getReader().readLine()
的调用。 (此外,readLine(byte[] b, int off, int len)
不需要参数吗?) - 作为上一点的后续,通过
BufferedReader
、InputStream
或任何类似的方式手动读取请求是一个不好的(随意使用)习惯,因为在某些情况下这样做可能会干扰getParameter(String name)
:
If the parameter data was sent in the request body, such as occurs with an HTTP POST request, then reading the body directly via
getInputStream()
orgetReader()
can interfere with the execution of this method.
您的客户端代码在定义 Ajax 调用完成时运行的函数时出现错误。该函数应将
events
作为参数,因为 jQuery 会自动解析 JSON 响应:.done(function (events) { // Do things with the events });
(戴上 Nerd 的帽子。)您的方法名称
get_events_json
不遵循 Java 约定。考虑将其重命名为getEventsJson
或类似的名称。
关于java - 如何从 GET 请求中获取参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22584504/