有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何从get请求中获取参数?

我无法从请求中检索值

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的情况下直接传递它,只使用文本


共 (2) 个答案

  1. # 1 楼答案

    Servlet Request Doc

    看看getAttribute(String name)getParameter(String name)

    编辑:getParameter(String)用于POST请求,但执行GET请求。改用getAttribute(String)

  2. # 2 楼答案

    使用$.get('EventServe', {location_id: location_id}, ...)发出HTTP GET请求时,将location_id的值作为查询字符串参数传递给指定的URL。基本上,您是在请求:EventServe?location_id=4,其中4将是location_id的值

    在服务器端,您可以通过^{}访问查询字符串参数:

    public void doGet(...) {
        String locationId = request.getParameter("location_id");
    }
    

    还有几点需要注意:

    • 你应该取消对request.getReader().readLine()的呼叫。(还有,readLine(byte[] b, int off, int len)不需要参数吗?)
    • 作为前一点的后续,通过BufferedReaderInputStream或任何类似的方式手动读取请求是一个坏习惯,因为在某些情况下,这样做可能会干扰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() or getReader() can interfere with the execution of this method.

    Source for the above quote.

    • 客户端代码有一个错误,您定义了Ajax调用完成时要运行的函数。函数应该以events作为参数,因为jQuery将自动解析JSON响应:

      .done(function (events) {
          // Do things with the events
      });
      
    • 戴上学究帽。)您的方法名get_events_json不遵循Java约定。考虑将其重命名为^ {CD14> }或类似的效果。