Reputation: 121
I would like to know what is the best way to read a text input on a jsp page? Could anyone tell what is the difference between the two java code separated by VS?
<input type=text id=myInput value="myInput">
<%
String data = request.getParameter("myinput");
//VS
request.setAttribute("myInput", data);
%>
Upvotes: 2
Views: 7369
Reputation: 358
I think you want the difference between a request attribute
and parameter
.
A request parameter
is always a String
(i.e. they are always represented by a String
even integers, booleans, floats etc like for eg: "1", "1.1", "true") and in a certain URL like: http://google.com/search?q=question&cat=images
q
and cat
are called parameters
or query parameters
and their value is question
and images
respectively. This is an example of GET
request.
POST
request parameters would be those which are submitted through an html <form>
.
Now request attributes
are objects as opposed to parameters
. And their value can only be set by using request.setAttribute("myInput", data);
here data
can be a String
, instance or object of a Person
class etc, in short data
is an object.
And one more difference is you don't have a method request.setParameter("myinput", data);
there is no such method, so request parameters are only set when a html <form>
is submitted or the URL contains parameters as explained above.
Now with parameters
you can get them as:
String data = request.getParameter("myinput");`
even if value of "myInput"
may be an int
or boolean
.
For an attribute you can get them as:
String data = (String) request.getAttribute("myInput");` // if "myInput" is a String
Person data = (Person) request.getAttribute("myInput");` // if "myInput" is an instance of Person class
Long data = (Long) request.getAttribute("myInput");` // if "myInput" is a Long
So now you know what is the different between the two codes, one reads the value from a request parameter (request.getParameter()
) and other from request attribute (request.getAttribute()
).
Let me know if this is not what you wanted.
Upvotes: 2