Thursday, January 10, 2013

JSF 2.x Tip of the Day: Determining the Base URL

This question has come up a couple of times in the last few days, so I thought I would write a couple of convenience methods to determine the Base URL.

I added them to my jsf-utils project for those who want to use my utilities.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/**
 * <p>Determines the Base URL, e.g.,
 * {@literal http://localhost:8080/myApplication} from the
 * {@link FacesContext}.</p>
 *
 * @param facesContext The {@link FacesContext} to examine.
 * @return the base URL.
 * @throws MalformedURLException if an exception occurs during parsing of
 * the URL.
 * @since 1.3
 */
public String getBaseURL(final FacesContext facesContext) throws MalformedURLException {
    return getBaseURL(facesContext.getExternalContext());
}
 
/**
 * <p>Determines the Base URL, e.g.,
 * {@literal http://localhost:8080/myApplication} from the
 * {@link ExternalContext}.</p>
 *
 * @param externalContext The {@link ExternalContext} to examine.
 * @return the base URL.
 * @throws MalformedURLException if an exception occurs during parsing of
 * the URL.
 * @since 1.3
 */
public String getBaseURL(final ExternalContext externalContext) throws MalformedURLException {
    return getBaseURL((HttpServletRequest) externalContext.getRequest());
}
 
/**
 * <p>Determines the Base URL, e.g.,
 * {@literal http://localhost:8080/myApplication} from the
 * {@link HttpServletRequest}.</p>
 *
 * @param request The {@link HttpServletRequest} to examine.
 * @return the base URL.
 * @throws MalformedURLException if an exception occurs during parsing of
 * the URL.
 * @see URL
 * @since 1.3
 */
public String getBaseURL(final HttpServletRequest request) throws MalformedURLException {
    return new URL(request.getScheme(),
            request.getServerName(),
            request.getServerPort(),
            request.getContextPath()).toString();
}

2 comments :

Unknown said...

A nice addition would be @Produces :)

John Yeary said...

The CDI man strikes again. ;-)

Popular Posts