I have a form in jsp. I have to populate it based on the request object (from the servlet). How do i use Java Script for accessing request object attributes or if you can suggest me any other better way to populate form dynamically?
Just print it as if it is a JavaScript variable. E.g.
var foo = '${foo}';
This will print the result of String.valueOf(pageContext.findAttribute("foo"))
to the response and end up being the value of a JavaScript variable. The webbrowser will retrieve like this:
var foo = 'somevalue';
You also see that those singlequotes are mandatory for JavaScript, not for Java/JSP.
See also:
Update: some may suggest to use an ugly and old fashioned scriptlet for this, e.g. <%= request.getAttribute("foo") %>
. Its use is however strongly discouraged since over a decade. You should perefer taglibs and EL over scriptlets. Also, as per the comments, when it concerns user-controlled input, you'd like to escape it to avoid XSS attacks:
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
...
var foo = '${fn:escapeXml(foo)}';
See also:
If you're pre-populating the form fields based on parameters in the HTTP request, then why not simply do this on the server side in your JSP... rather than on the client side with JavaScript? In the JSP it would look vaguely like this:
<input type="text" name="myFormField1" value="<%= request.getParameter("value1"); %>"/>
On the client side, JavaScript doesn't really have the concept of a "request object". You pretty much have to parse the query string yourself manually to get at the CGI parameters. I suspect that isn't what you're actually wanting to do.