Hi all. I was wondering if there's a way to assign the value in a text field to a variable in jsp using Java (not Javascript). Normally in Javascript you might do something like: document.formName.fieldName.value to access the value. How can this be achieved using Java? :icon_confused:

Recommended Answers

All 6 Replies

If you want to use java it must be done at the server. Meaning before you render the page.
For example.
Put a value at the request request.setAttribute("key","The Value") Then submit, redirect or whatever and at jsp, get it and put it at the field:

String something =  (String)request.getAttribute("key");
...

<input type="text" name="someName" value="<%= something %>" />

Cool, so what about if it's from form to form on the same page?

By that I mean going from textfield --> variable --> textfield all on the same page.

If you have a value in a textfield and want to put it in a java variable, you need to submit the form (or pass it as parameter at a hyperlink)

If you want to put a java variable to a textfield, when you go to the page you need to take it from the request and put it to the field when the page renders.

Remember first the code executes at the server and then the page is loaded. So you take the value from the request and then the field with the value will be displayed:

String something =  (String)request.getAttribute("key");
...
<input type="text" name="someName" value="<%= something %>" />

At the server huh, so what should I do if I wanted that process to take place in after the page loaded?

Meaning put some value to a field and then push something so that this value would be put to a java variable?

Yes, submit the page.

When you see the JSP page, java code has already been executed. If you want to execute some more you need to go to the server by submitting.
If you have java code in a jsp page, that code is first executed at the server and then page is displayed.
So when you submit, the code that gets executed (getting values from the request) is at the server. When this is done, you see the page

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.