Excuse me, I'm recently learning programming and Java, mostly from YouTube videos. The problem is that all these videos are based on outdated frameworks, while I am trying to do the same thing using modern versions of the software.
I recently encountered a problem, I could not get a CDI Bean (@SessionScoped) in a servlet (regular @WebServlet) as a session attribute (in turn obtained from an HTTP request), although this is exactly what was shown in the video (True, it was not a CDI Bean, but a @ManagedBean (eager = true) that was used there - depricated). The bean was null all the time. For about a week I tried to find something about this on the Internet, I thought that the problem was just in the “eager” property (CDI has “lazy”, and it seems that it cannot be changed), but the only thing I found out is that, access to the Face Context is “not guaranteed” from files and classes that are not related to JSF tools, such as WebServlets. I still solved this situation in my own way - right in the CDI constructor I put Bean in the session (using ExternalContext.getSession), and in the servlet processing the request I took Bean out of the session:
@Named(value = "searchController")
@SessionScoped
public class SearchController implements Serializable {
private Class class;
private static Map<String, SearchType> searchList = new HashMap<String,
SearchType>();
...
public SearchController() {
........
**((HttpSession)FacesContext.getCurrentInstance()
.getExternalContext().getSession(false))
.setAttribute("searchController", this);**
}
and in WebServlet:
SearchController searchController = (SearchController)
request.getSession(false).getAttribute("searchController");
But this is not the ending.
I've published this variant under one of similar topic here, and received an advice just to inject the CDI Bean in @WebServlet, through annotation @Inject. Without any details. So I,ve tried to do it, added in @WebServlet @Inject SerchController searchController, removed definition of this attribute from the constructor, but it doesn't work, in WebServlet FaceContext is null. WebServlet is not a Face component. Fs I understood when I was learning Spring (in this project i don't use Spring), we always injected beans in Spring components, but how to resolve this problem here? What I'm doing wrong?
My advisors on the previous thread gave me a link to a post 13 years ago NullpointerException in getExternalContext in FacesContext, but even there I read the same thing I already read: @Inject does not work (or work is not guaranteed) if CDI beans are injected into elements that are not JSF components. My comment was hidden, I agree, it was far from the question, but I would like these knowledgeable guys to come here and show me their solution, especially since it is much simpler than mine. I would be very grateful.
I wanted to receive a signuture - how to inject CDI Bean in @WebServlet