1

I am having some problem when trying to execute different method in servlet doGet(). So when my button on click, it will pass along the eventID:

viewDtlEventBtn.setOnClickListener(new OnClickListener(){
        public void onClick(View v){
            Intent eventDtlIntent = new Intent(context, EventDetail.class);
            eventDtlIntent.putExtra("eventID", eventIDTV.getText());
            startActivity(eventDtlIntent);
        }
    });

Then in my EventDetail class, I am executing the method in AsyncTask class:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.event_detail);
    context = this; 
    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        eventID = extras.getString("eventID");
    }       
    eventModel.setEventID(eventID);
    new GetEventDetailAsyncTask(context).execute(eventModel);
}

And in my AsyncTask class, I am calling the method in my controller which retrieving the JSON returned from servlet:

@Override
protected Double doInBackground(Event... params) {
    try {
        eventCtrl.getEventDetailByID(params[0]);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return null;
}

And in my controller class:

public Event getEventDetailByID(Event event) throws JSONException {
    Event eventModel = new Event();
    String page;
    JSONArray jsonArray;
    String eventID = event.getEventID();

    try {
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(ENeighbourhoodActivity.URL
                + "?getEventDetailByID&eventID=" + eventID +"");
        HttpResponse response = client.execute(request);
        HttpEntity entity = response.getEntity();
        String responseString = EntityUtils.toString(entity, "UTF-8");
        page = "{\'EventDetail\':" + responseString + "}";
        try {
            JSONObject jsonObject = new JSONObject(page);
            jsonArray = jsonObject.getJSONArray("EventDetail");
            int length = jsonArray.length();
            for (int i = 0; i < length; i++) {
                JSONObject attribute = jsonArray.getJSONObject(i);
                String eventName = attribute.getString("eventName");
                eventModel.setEventName(eventName);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return event;
}

And basically from here, I am accessing the servlet. And in my doGet() in serlvet class:

protected void doGet(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    JSONArray jsonArray = new JSONArray();
    PrintWriter out = response.getWriter();

    if (request.getParameter("getAllEvent") != null) {  
    }

    catch (JSONException je) {
        System.out.println(je.getMessage());
    } catch (Exception exc) {
        System.out.println(exc.getMessage());
    }
    out.println(jsonArray.toString());
    }
}

I already have one if statement for some other methods. I wonder how should I pass the getEventDetailByID and the eventID parameter into servlet so that it knows which method to runs.

Thanks in advance.

  • If you append them to the request, you can get them by getParameter method – Alaychem goes to Codidact Nov 12 '14 at 11:17
  • @Alaychem So do you mean that I need to set a NameValuePair to pass in the eventID as parameter. Then inside doGet(), I get the parameter? –  Nov 12 '14 at 11:21
  • Don't use parameters to decide inside a servlet what to do. Better use the path and mapping to let it route to different servlets: http://stackoverflow.com/questions/10000008/restful-servlet-urls-servlet-mapping-in-web-xml – zapl Nov 12 '14 at 11:30
  • @zapl Would you mind to provide me some example which could fit into my situation? Because I not really understand the thread you provided :( –  Nov 12 '14 at 11:33
  • Why NameValuePair? isn't eventID is a String? just add `?eventID=foo&getEventDetailByID=fee` to get request, and yes, get the parameter on the doGet. (Or use diffrent servlets as zapl suggested) – Alaychem goes to Codidact Nov 12 '14 at 11:37
  • It looks like your webservice is supposed to do and return completely different things depending on url parameters like `?getEventDetailByID` or `?getAllEvent`. Instead of doing so, make those into two different servlets. Then use whatever servlet mapping technique you're using to route requests to the right servlet method. Via xml based on different paths for example: http://stackoverflow.com/a/8198327/995891 . That saves you from doing if/else, the server does it automatically now. More path vs param: http://stackoverflow.com/questions/4024271/rest-api-best-practices-where-to-put-parameters – zapl Nov 12 '14 at 11:40
  • @Alaychem Okay so let's make it this way. Let's say I wanted another if statement in my servlet, so: if (request.getParameter("getEventDetailByID&eventID=" + eventID + "") != null) { } So I typed this out but where should I get the value for eventID in servlet class? I can just initialize it as null? –  Nov 12 '14 at 11:44
  • @zapl So can I assumed that I need to create a web.xml in servlet. and for each of the if statement that I am going to use, I create different classes for them and each have doGet() and doPost() inside? –  Nov 12 '14 at 11:46
  • Something already routes the request to that particular `doGet` method. I assume there is an existing `web.xml` with 1 entry for your servlet. Using different servlets for different tasks is just simpler, you can do it all in one if you really like to but the idea of automatic request to servlet mapping is that you don't have to. – zapl Nov 12 '14 at 11:52
  • @zapl Different servlet for different tasks. But in that case, let's say I got 3 different tasks, instead of doing them in a servlet class with if else statement, I have to create 3 different servlet class for each tasks? –  Nov 12 '14 at 11:58
  • Yes exactly. A single `Servlet` can have only 1 `doGet` method so you have to create 3 and add 3 mappings in the xml. But if you don't like that, take a look at the alternatives like http://www.vogella.com/tutorials/REST/article.html#restjersey - that's an abstraction on top of servlets that routes different requests to different annotated methods. – zapl Nov 12 '14 at 12:08
  • When appending two parameters the way I showed , two getParameter calls should be done. `String getEventDetailByID = requset.getParameter("getEventDetailByID"); String eventID = requset.getParameter("eventID"); ` – Alaychem goes to Codidact Nov 12 '14 at 12:12
  • @zapl You mentioned mappings in the xml. So bascially I have to create a web.xml and what should I do with it? –  Nov 12 '14 at 12:26
  • The file should exist already, search in your project, maybe it's `/war/WEB-INF/web.xml`. In there should be an existing mapping to the servlet you have. – zapl Nov 12 '14 at 12:37
  • @zapl Nope I did not see it. But do I have to do anything with it? or I can just simply create servlet class and change the servlet URL in my controller? –  Nov 12 '14 at 12:38
  • If you can add servlets and urls without that xml file, do that instead. I don't know how that works in your project :) I was just assuming that you have that file because it's a standard defined by the servlet specification, see http://wiki.metawerx.net/wiki/Web.xml or https://cloud.google.com/appengine/docs/java/config/webxml for example. – zapl Nov 12 '14 at 12:51

1 Answers1

1

Here is a example of how you can get the eventID value.

        //gets value from getEventDetailByID parameter.
        String detail = request.getParameter("getEventDetailByID");
        if (detail != null && !detail.equals("")) {
            int eventId = Integer.parseInt(request.getParameter("eventID"));
            //get event detail by id with id 
            //e.g resultObject = myMethod(detail, eventId);
        }

Update 1: A better way of doing what is required:

        String action = request.getParameter("action");
        if (action.equalsIgnoreCase("GetById")) {
            int eventId = Integer.parseInt(request.getParameter("eventID"));
            //get event detail by id with id 
            //e.g resultObject = getById(eventId);
        } else if (action.equalsIgnoreCase("GetAllEvents")) {
            //Get all events
            //e.g resultObject = GetAllEvents();
        } else {
        }

The URL usage:

to get event by id:

http://localhost:8080/WebService/EventDetailServlet?action=GetById&eventID=46

to get all event details

http://localhost:8080/WebService/EventDetailServlet?action=GetAllEvents
Asiriel
  • 118
  • 1
  • 13
  • !detail.equalsIgnoreCase("") - I didn't knew that "" can be case sensetive! – Alaychem goes to Codidact Nov 12 '14 at 12:21
  • fixed, caused by ctrl + space in netbeans :) Should not make a difference anyway. – Asiriel Nov 12 '14 at 12:25
  • @Asiriel So inside my controller class, the HTTPGet still remain the same as this: HttpGet request = new HttpGet(ENeighbourhoodActivity.URL + "?getEventDetailByID&eventID=" + eventID +"");? –  Nov 12 '14 at 12:28
  • in the example I gave if you use ?getEventDetailByID&eventID= the if (detail != null && !detail.equals("")) will evaluate to false. – Asiriel Nov 12 '14 at 12:39
  • @Asiriel Okay sure, give me a minute to test it out :) –  Nov 12 '14 at 12:42
  • I tested this in my servlet: http://localhost:8080/WebService/EventDetailServlet?getEventDetailByID&eventID=46 and it returns null. Do you have any ideas? –  Nov 12 '14 at 13:13
  • As I mentioned in my previous comment the if statement will evaluate to false, meaning getEventDetailByID has no value and equals null. adding a value to the parameter should resolve the problem. example: http://localhost:8080/WebService/EventDetailServlet?getEventDetailByID=yes&eventID=46 you can also try something like having a parameter called action, and if action equals getEventDetailsById then call a certain method using the eventId. I'm not sure as to what exactly you want to do. – Asiriel Nov 12 '14 at 13:16
  • @Asiriel So in my controller class, how should I format this: HTTPGet still remain the same as this: HttpGet request = new HttpGet(ENeighbourhoodActivity.URL + "?getEventDetailByID&eventID=" + eventID +"");? –  Nov 12 '14 at 13:23
  • Updated answer, please read and see if it helps with what you require. – Asiriel Nov 12 '14 at 13:39