views:

68

answers:

2

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?

+2  A: 

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:

BalusC
*Be careful!* You're asking for an [XSS](http://en.wikipedia.org/wiki/Cross-site_scripting) attack if you don't escape or encode what's coming from the request.
kevingessner
@kevin: that's correct when it's user-controlled input (and that's not *only* the request!). See also: http://stackoverflow.com/questions/2658922/xss-prevention-in-java/2658941#2658941
BalusC
I vote for BalusC's answer, as EL is more proper than use of a scriplet. Plus, it's really really really important that his reputation count be at (92.7k + 15) rather than a lousy 92.7k. :)
Steve Perkins
@Steve: Uhm OK? Go get a [Greasemonkey script](http://userscripts.org/scripts/show/62486) to hide pointless data so that you won't be bothered :)
BalusC
+2  A: 

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.

Steve Perkins
Yes... obviously you would also want to sanitize the parameter, to avoid any kind of XSS or injection attack.
Steve Perkins