PDA

View Full Version : Passing variables in url


waxydock
Oct 11th, 2006, 01:48 AM
I have a spring mvc app and what i want to do is,

if there is an variable in the url when loading a jsp page (ie. http://www.site.com/db.nsf/test.jsp?arg1=4), read the variable then get something from the database (using dao) using that variable.

How do i pass the variable to the controller?

Does someone know how i can do this, or know of a site that does something similar.

Thanks :)

waxydock
Oct 11th, 2006, 11:11 PM
any ideas?

Marten Deinum
Oct 12th, 2006, 03:13 AM
Check the reference guide, chapter 6 which eplains about the different controllers.

But here is the short answer. In the formBackingObject and referenceData method you have access to your HttpServletRequest object. From this you can get variables which are put there with GET/POST.


String param = (String) request.getParameter("arg1");

waxydock
Oct 12th, 2006, 04:41 AM
hi,

i can now get the variable from the url, but how can i give this variable to my controller so i can use it to query to db.

thanks.

Sprang
Oct 12th, 2006, 05:14 AM
In your controller java that returns that jsp view you can use

String arg1 = ServletRequestUtils.getRequiredStringParameter(req uest, "arg1");

If you have a method in your dao which accepts a different type, you'll need to use the suitable getRequired method.

Record record = myDao.getRecord(arg1);

Marten Deinum
Oct 12th, 2006, 05:16 AM
You don't really 'give' anything to the controller. As I stated checkout the javadocs of the formBackingObject (http://static.springframework.org/spring/docs/2.0.x/api/org/springframework/web/servlet/mvc/AbstractFormController.html#formBackingObject(java x.servlet.http.HttpServletRequest)) and referenceData (http://static.springframework.org/spring/docs/2.0.x/api/org/springframework/web/servlet/mvc/SimpleFormController.html#referenceData(javax.serv let.http.HttpServletRequest)) methods on the SimpleFormController

When you just simple implemented the Controller (http://static.springframework.org/spring/docs/2.0.x/api/org/springframework/web/servlet/mvc/Controller.html) interface check the javadocs of that.

Also read the chapter about spring webmvc (http://static.springframework.org/spring/docs/2.0.x/reference/mvc.html) which explains how to use views/controllers in detail.

The most simple answer is in most methods in the controller you have access to the HttpServletRequest (http://java.sun.com/products/servlet/2.3/javadoc/javax/servlet/http/HttpServletRequest.html) object, this object has an getParameter (http://java.sun.com/products/servlet/2.3/javadoc/javax/servlet/ServletRequest.html#getParameter(java.lang.String) ) method which you can use to retrieve parameters from the request. Those parameters are either there through a GET request (parameters on the URL like to ones you did) or by a POST request (most of the times form are getting posted, and the input fields are then put in the request parameters).