简体   繁体   中英

injecting FacesContext into spring bean

I have bean that i recently converted over from being a managed-bean to being a spring-bean.

Everything was ok until at some point the following method is called:

Exception e = (Exception) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get(
                    AbstractProcessingFilter.SPRING_SECURITY_LAST_EXCEPTION_KEY);

At this point things blow up because FacesContext.getCurrentInstance() returns null.

is it possible to inject the faces context into my bean?

I faced the exact same problem today, so I wanted to post this answer for future reference.

FacesContext can be injected using:

@ManagedProperty("#{facesContext}")
FacesContext faces;

It works for spring beans too, provided Spring and JSF are integrated properly in the application.

Reference:

Integrating Spring and JSF

Injecting FacesContext

is it possible to inject the faces context into my bean?

Not sure, but in this particular case it's not needed. The ExternalContext#getSessionMap() is basically a facade to the attributes of HttpSession . To the point, you just need to grab the HttpServletRequest in your Spring bean somehow and then get the HttpSession from it by HttpServletRequest#getSession() . Then you can access the session attributes by HttpSession#getAttribute() .

I don't do Spring, but Google learns me that you could obtain it as follows:

HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

Once done that, you can just do:

Exception e = (Exception) request.getSession().getAttribute(AbstractProcessingFilter.SPRING_SECURITY_LAST_EXCEPTION_KEY);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM