session handling in JSF 1.2

荒凉一梦 提交于 2019-12-06 15:17:43

The session scope is programmatically available by ExternalContext#getSessionMap() which delegates under the covers to HttpSession#get/setAttribute().

Map<String, Object> sessionMap = FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
// ...

You can of course also just put a managed bean in the session scope. It's accessible from other managed beans by <managed-property> (or just a traversal of the session map using the managed bean name as map key).

I think you can use Java EE filters for this mechanism.

Filters are controlled by Servlet Container and runs first on an action depending on your web.xml order.

Add a servlet filter to your project.

public class YourFilter implements Filter {

public static final String USER = "USER_SESSION_KEY";

public void doFilter(ServletRequest req, ServletResponse response, FilterChain filterChain)
{

   HttpServletRequest request = (HttpServletRequest) req;
   HttpSession session = request.getSession(true);
       String servletpath = request.getServletPath();
if(!servletpath.contains("login.xhtml")) //exclude your login page and other pages required to pass this filter.
{
     if (session.getAttribute(USER) != null)
    {
    //Control your authentication and roles.
    }
    else
    {
    //There is no user in the session.
    }
}


    }
    filterChain.doFilter(request, response);
    }

Add your filter to your web.xml

<filter>
    <filter-name>YourFilter</filter-name>
    <filter-class>Package.YourFilter</filter-class>
</filter>
  <filter-mapping>
    <filter-name>YourFilter</filter-name>
    <servlet-name>Faces Servlet</servlet-name>
  </filter-mapping>

Secondly, put your User class to the session inside a JSF action.

public void userAction()
{


 User user = new User();
   //Build your User Class
  HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
    request.getSession(false).setAttribute("USER", user);

}

P.S. : User class is a user defined POJO class. you should implement it according to your needs.

public class User
{
    private String username;
       //Other properties and getter setter methods required.

}

If you want to implement this mechanism inside JSF context. You can build the same logic by implementing JSF phase listeners.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!