GeeCON Prague 2014*
The moose likes Servlets and the fly likes parameter problems Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Servlets
Bookmark "parameter problems" Watch "parameter problems" New topic
Author

parameter problems

Jenn Person
Ranch Hand

Joined: Jan 16, 2005
Posts: 89
I have a controller servlet that will accept one of two different parameters depending on which hyperlink summons it.

Ex. <A HREF="Genre?genreID=3">Rock</A>
<A HREF="Genre?ID=4">AC/DC</A>

Here, Genre is the servlet and genreID and ID are the two different parameters. Every time a link is used, only one parameter is sent. They are both integer parameters.

My problem is right now I start my Genre servlet by reading in both of those parameters as such:
int genreID = Integer.parseInt(request.getParameter("genreID"));
int ID = Integer.parseInt(request.getParameter("ID"));

However just using this in my servlet causes an error during runtime. I suppose I cannot read in a value if it has not been assigned a value?? How can I solve this problem??

Basically because this is a controller servlet I want it to be able to handle multiple similar requests. In this example, if it receives a genreID, then it retrieves a whole category of music. If an ID is received, it retrieves just one cd.

Thanks to all who reply!!
Ben Souther
Sheriff

Joined: Dec 11, 2004
Posts: 13410



Is one approach but can get a bit expensive if you have a lot of parameters.

Another is to always pass an action parameter that you read first to determine the mode. Once you know what mode you're in, you can read only the parameters that are expected for that action.


[ April 12, 2005: Message edited by: Ben Souther ]

Java API J2EE API Servlet Spec JSP Spec How to ask a question... Simple Servlet Examples jsonf
Ben Souther
Sheriff

Joined: Dec 11, 2004
Posts: 13410

The second approach can also be achieved by creating multiple mappings to the same servlet and then reading the URI to determine the mode

Jason Kwok
Ranch Hand

Joined: Mar 31, 2005
Posts: 126
I don't know if this is the best way, but I had a situation like that and I fixed it quite easily by putting both parameters in each link and make the one you know won't have a value of 0.

for example:
<A HREF="Genre?genreID=3&ID=0">Rock</A>
<A HREF="Genre?ID=4&genreID=0">AC/DC</A>

This way your servlet can read in both values regardless of which link is summoning your servlet. To test which you need to use you could do something like...

if(ID == 0) {
//do something with genreID
}
if(genreID == 0) {
//do something with ID
}

I really hope that helps. It may not be very elegant, but it works!!
Chit Ming Chong
Ranch Hand

Joined: Sep 09, 2004
Posts: 49
or check them whether they have a null value before assigning them e.g.

 
GeeCON Prague 2014
 
subject: parameter problems