How do I get request url in jsf managed bean without the requested servlet?

前端 未结 4 1591
予麋鹿
予麋鹿 2020-12-07 22:35

Assuming the URL is http://localhost:8080/project-name/resource.xhtml,

I want to obtain the following http://localhost:8080/project-name in a JSF managed bean.

4条回答
  •  我在风中等你
    2020-12-07 23:36

    You can get it as follows:

    HttpServletRequest req = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
    String url = req.getRequestURL().toString();
    return url.substring(0, url.length() - req.getRequestURI().length()) + req.getContextPath() + "/";
    // ...
    

    Note that there are possibly better ways to achieve the requirement. Getting the raw Servlet API inside a JSF managed bean is a code smell alarm.

提交回复
热议问题