Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing int as parameter from JSP to servlet

Tags:

jsp

servlets

I am trying to pass studentId of datatype int to servlet but it does not accept it and forces to change the datatype to String

    int studentId;
    String studentName;

    studentId = request.getParameter("StudentId");   // (cannot convert from int to String).

I can't change it to String as in the database studentId is an integer (primary key) and my java class also takes an int as a parameter.

How can I solve this?

like image 688
Muhammad Avatar asked Mar 05 '12 17:03

Muhammad


People also ask

How to get Integer parameter in JSP?

getParameter() is the method in request object, which returns String value always. So convert that string output to Integer [ line number 21] Integer. parseInt(-String-) gives integer value.

What is getParameter in servlet?

getParameter. java.lang.String getParameter(java.lang.String name) Returns the value of a request parameter as a String , or null if the parameter does not exist. Request parameters are extra information sent with the request. For HTTP servlets, parameters are contained in the query string or posted form data.


2 Answers

you need to parse the parameter as an int. In a request the parameters are just strings at the end of the day (they were typed into a browser, or stored in the html of a webpage after all), so you need to interpret it on the server as the type you expect.

studentId = Integer.parseInt(request.getParameter("StudentId"));
like image 195
Sam Holder Avatar answered Oct 16 '22 08:10

Sam Holder


private int roll;

int roll = Integer.parseInt(request.getParameter("roll"));

Here request is the object of HttpServletRequest and hence it will the getParameter() and we are getting the value as string.

like image 35
user1364078 Avatar answered Oct 16 '22 07:10

user1364078