简体   繁体   中英

Access ViewScoped ManagedBean from Servlet

Background information: I have a file upload applet in my jsf page. This applet expects an adress where it can send it's POST request. (I can't edit this post request to add more fields or something). The post method of my servlet then stores the file. This job can't be done by a managed bean because the servlet has to be annotated with @MultiPartConfig and I can't add this annotation to the jsf managed bean. In order to force the upload applet to use the same session I added an URL attribute named jsessionId to the post request according to this post . In my servlet I am now able to access session scoped beans.

Now I have a ViewScoped bean where I store some form input data which I want to use in the servlet, since adding those inputs to the post request doesn't work (Applet is a third party project (JUploadApplet) and for some reason it doesn't work to add additional form data). Now is it possible to access the ViewScoped bean from within the servlet ? If I change the scope into SessionScope I am able to process the input but with ViewScoped I get a NullPointerException if I try to access the bean like this : UploadBean uploadBean = (UploadBean)request.getSession().getAttribute("uploadBean");

This is not possible. Your best bet is to let the view scoped bean generate an unique key, store itself in the session scope by that key and pass that key as additional parameter to the applet and finally let the servlet access the session attribute by that key.

Eg

private String sessionKey;

@PostConstruct
public void init() {
    sessionKey = UUID.randomUUID().toString();
    FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(sessionKey, this);
}

@PreDestroy
public void destroy() {
    FacesContext.getCurrentInstance().getExternalContext().getSessionMap().remove(sessionKey);
}

Let the applet pass the sessionKey as request parameter to the servlet, so that the servlet can do

String sessionKey = request.getParameter("sessionKey");
Bean bean = (Bean) request.getSession().getAttribute(sessionKey);
// ...

Note that instead of the bean itself, you can also just store an arbitrary bean/valueobject/etc.

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