Jenia Be Nice Please
Jenia Be Nice Please

Reputation: 2693

How to get parameters from GET request?

I can't retrieve the values from a request.

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

On the client-side:

$.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)});
});

I've also tried to pass it in directly without jQuery, using only literals.

Upvotes: 3

Views: 7401

Answers (2)

Whymarrh
Whymarrh

Reputation: 13565

When you use $.get('EventServe', {location_id: location_id}, ...) to make a HTTP GET request, you are passing the value of location_id as a query string parameter to the specified URL. Essentially you are requesting: EventServe?location_id=4, where 4 would be the value of location_id.

On the server side, you can access the query string parameters via getParameter(String name):

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

A few extra notes:

  • You should remove your call to request.getReader().readLine(). (Also, doesn't readLine(byte[] b, int off, int len) require arguments?)
  • As a followup to the previous point, manually reading from the request via a BufferedReader, InputStream, or anything similar is a bad (used loosely) habit to get into, as doing so may interfere with getParameter(String name) in some cases:

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.

  • Your client side code has a error where you define the function to run when the Ajax call is completed. The function should take events as an argument, as jQuery will automagically parse a JSON response:

    .done(function (events) {
        // Do things with the events
    });
    
  • (Puts on pedant hat.) Your method name get_events_json does not follow Java conventions. Consider renaming it to getEventsJson or something to that effect.

Upvotes: 2

Ennosigaeon
Ennosigaeon

Reputation: 442

Servlet Request Doc

Just look at getAttribute(String name) or getParameter(String name).

Edit: getParameter(String) is for POST request, but you perform a GET request. Use getAttribute(String) instead

Upvotes: -1

Related Questions