Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

injecting FacesContext into spring bean

Tags:

java

spring

jsf

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?

like image 486
mkoryak Avatar asked Dec 23 '10 00:12

mkoryak


2 Answers

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

like image 104
coolscitist Avatar answered Sep 17 '22 16:09

coolscitist


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);
like image 32
BalusC Avatar answered Sep 20 '22 16:09

BalusC