我无法从请求中检索值。
Servlet:
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}, ...)
用来发出HTTPGET
请求时,您会将值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)
在某些情况下:如果参数数据是在请求正文中发送的(例如与HTTP POST请求一起发送),则直接通过读取该正文
getInputStream()
或getReader()
会干扰此方法的执行。
您的客户端代码有一个错误,您在其中定义Ajax调用完成时要运行的函数。该函数应events
作为参数,因为jQuery会自动解析JSON响应:
.done(function (events) {
// Do things with the events
});
(戴上学帽。)您的方法名称get_events_json
不遵循Java约定。考虑将其重命名getEventsJson
为该名称或类似的名称。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句