• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Initialize int variable in servlets

 
muntago Richard
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
how do i set int variable in servlets request .

int id = Integer.getInteger(request.getParameter("id")).intValue();

i tried this but not working
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64717
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Define "not working".

And I'd use Integer.valueOf().
 
sadhu charan
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Better you try

int id = Integer.ParseInt((request.getParameter("id"));
 
Sean Rowlandson
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not sure what you mean by not 'not working'.

However like what has already been posted the following should be fine:


int id = Integer.valueOf(request.getParameter("id")).intValue ();

 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13058
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


The usual problem with this kind of shortcut appears when getParameter("id") returns null rather than the expected String and you get a null pointer exception.

Therefore, try to recover the parameter String first, test for null and then decide what to do.

Bill
 
Sean Rowlandson
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Further to bills observation, any time you are dealing with objects such as requests it is good and advised practise to check for null first.

Including null checks is a good habit to get into in any code as it makes it more robust and also scales better... a few years down the line a joe bloggs decides to come along and use one of your methods then kindly passes a null value and.... POP.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic