I need to do very simple thing - pass current URL from JSF (2.0) page to the managed bean. This is needed to get URL of the login form which will redirect user back to the current page after login. (I use GAE and the bean is the wrapping around its user service, if it does matter). Any obvious way I tried doesn't work
<c:set />
- doesn't work (w/o any error or warning message)
getter which takes current URL as a parameter - doesn't work.
So many questions and many recipes, but all are complex and not elegant. Why? May be I (as other who asking) missed a key design principle? I'll appreciate any answer - simple and straightforward recipe or explanation why not to do so.
views:
28answers:
1
A:
It's available by #{request.requestURL}
(or if you only want the domain-relative path, use #{request.requestURI}
). Use f:param
to pass it and @ManagedProperty
to handle it.
<h:commandButton action="#{bean.submit}" value="submit">
<f:param name="url" value="#{request.requestURL}" />
</h:commandButton>
with
@ManagedProperty("#{param.url}")
private String url;
Noted should be that f:param
inside a h:commandButton
doesn't work in JSF 1.x. You'd like to use h:commandLink
instead.
Update as per the comments: I understood that you wanted to "pass current URL to the managed bean". But you actually want to "access current URL in managed bean".
In that case, either replace #{param.url}
by #{request.requestURL}
:
@ManagedProperty("#{request.requestURL}")
private String url;
Or obtain the raw HttpServletRequest
instance from under the JSF hoods by ExternalContext#getRequest()
:
HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
String requestURL = request.getRequestURL();
BalusC
2010-08-13 15:44:32
Yes, I understand that it will work, when user press submit button. But can I set some bean property without any interaction with user? I need to initialize a bean property with the specific requestURI just after HTTP GET request is received and be able to get other property which depends on the requestURI below on the page. Is it possible?
Max Doronin
2010-08-13 16:03:39
Truly this is possible. See the updated answer.
BalusC
2010-08-13 16:22:35
Yes, it was my fault, I'm sorry for ambiguous question. Now both options work do exactly what I need! Thank you BalusC!
Max Doronin
2010-08-14 01:33:17
@ManagedProperty does not work in @ViewScopebe aware!
Odelya
2010-08-15 06:28:25
@Odelya: Only when the scope of the property is shorter than the bean's scope. In this particular example the property is request scoped, then the bean must be request scoped, it can't have a broader scope than that.
BalusC
2010-08-15 12:53:14