I have Two different JSF page Let Us suppose A.jsf and B.jsf But Both calling same managed bean different methods ManagedBean.java
A.jsf is calling a SessionScoped Managed bean method where i set some attribute in Request class object
HttpServletRequest request = (HttpServletRequest) FacesContext
.getCurrentInstance().getExternalContext().getRequest();
request.setAttribute("token", requestToken.getToken());
request.setAttribute("tokenSecret", requestToken.getTokenSecret());
Then redirecting some other side like this
response.sendRedirect(requestToken.getAuthorizationURL());
Now after successful login i am opening another JSF page of my website suppose b.jsf and from this page i am calling method like this
<f:event listener="#{ManagedBean.redirectLogin2}" type="preRenderView" />
and calling same Managedbean but another method
public String redirectLogin2() throws TwitterException {
HttpServletRequest request = (HttpServletRequest) FacesContext
.getCurrentInstance().getExternalContext().getRequest();
}
But when i am doing in above method redirectLogin2()
request.getAttribute("token")
request.getAttribute("tokenSecret")
Both giving Null. What cab be the issue here?
Request scoped attribute life span will be lost on sendRedirect. You should set value on session scope.
HttpSession session=request.getSession();
session.setAttribute("token", requestToken.getToken());
session.setAttribute("tokenSecret", requestToken.getTokenSecret());
After setting value to session. You can access that from request like
HttpServletRequest request = (HttpServletRequest) FacesContext
.getCurrentInstance().getExternalContext().getRequest();
request.getSession().getAttribute("token");
request.getSession().getAttribute("tokenSecret");
Although, above code will work but that is not good practice. JSF has #SessionScoped annotation which will make available of your variable access with login session.
Related
I want to join an existing conversation scope.
I start the conversation with:
conversation.begin(packageId);
I got close with using the following which seems to work:
#Inject #Http CoversationContext context;
context.activate(packageId);
However I'm seeing a warning in the log which suggests I'm not getting it right.
WARN: WELD-000335: Conversation context is already active, most likely
it was not cleaned up properly during previous request processing:
HttpServletRequestImpl [ POST /path/to/url ]
I'm also happy if there is an alternative way to just drop the conversation and recreate (so long as I can continue using the same custom conversation ID) I'm trying to avoid the user reloading the page multiple times filling up memory with duplicates of the same package data.
I also considered using a #SessionScoped bean but I thought if I can set the package ID to be the conversation ID then I can avoid the need to manage a #SessionScoped bean.
As long as the cid parameter is in request, and the conversation is long-running (since you did conversation.begin(packageId)) then there is no need to join a conversation context, it is already active in current request.
What you need to do however is to include the cid in every request form or in url parameters through:
e.g.
<h:link>
<f:param name="cid" value="#{javax.enterprise.context.conversation.id}"/>
</h:link>
or
<h:form>
<f:param name="cid" value="#{javax.enterprise.context.conversation.id}"/>
/h:form>
Note that the conversation must be long-running by explicitly starting it as conversation.begin(id)
Also:
At the end of your step processing, you need to explicitly call conversation.end() otherwise the conversation scoped beans will be destroyed only at the end of the session context
For book marking, then you need to include the cid parameter or any logical mapping in the path, and then use a filter to forward with the cid parameter:
#WebFilter(urlPatterns = "/*")
public class CidFilter implements Filter {
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {
String cid = extractCidParameterIfAny(request);
HttpServletRequest httpRequest = (HttpServletRequest) request;
if (cid != null) {
String forwardUrl = buildForwardUrlWithCidParameter(cid);
HttpServletRequest wrapper = new CidHttpServletRequest(httpRequest);
httpRequest.getRequestDispatcher(forwardUrl).forward(wrapper, response);
} else {
chain.doFilter(request, response);
}
}
}
I have a problem with handling sessions between Java servlet, jsp page and Struts Action. Java servlet adds some param to session when get request and sendRedirect to some page1.jsp. On page1 I have an url to Struts Action like strutsAction.do. When StrutsAction recevies request, the session doesn't contain attributes I added in Java servlet. Clicking on page returned by this action doesnt refresh session of Java Servlet, but they have the same SessionId. So, after session.getMaxInactiveInterval() of servlet session pass I'm getting sessionDestroyed() event, even when i taking actions on page returned by StrutsAction. How to fix this issue?
In case of SendRedirect call old request and response object is lost because it’s treated as new request,
You should try the following code
RequestDispatcher rd = servletContext.getRequestDispatcher("/pathToResource");
rd.forward(request, response);
becuase when forward is called on requestdispather object we pass request and response object so our old request object is present on new resource which is going to process our request.
i have a below method in theme:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)throws IOException, ServletException {
((HttpServletRequest) request).getSession().setAttribute("test", "abc");
}
i am trying to fetch above session object in doView method of portlet.
HttpSession httpSession =PortalUtil.getHttpServletRequest(renderRequest).getSession();
System.out.println("httpSession obj"+(String)httpSession.getAttribute("test"));
i even tried using as below :
HttpServletRequest request1 =PortalUtil.getHttpServletRequest(renderRequest);
HttpServletRequest originalRequest = PortalUtil.getOriginalServletRequest(request1);
HttpSession httpsession = originalRequest.getSession();
System.out.println("httpSession ==> " + httpsession);//session object gets printed
System.out.println("test "+httpsession.getAttribute("test"));//null
i get the null value when i try to fetch from doview method. Can anyone please suggest how to fetch the value from theme to portal
You only get the portletRequest adapted to the ServletRequest interface. In addition you'll need PortalUtil.getOriginalHttpServletRequest().
Here's some more information about the difference between the two.
Should you use it? No.
I can't imagine what the theme would need to write to the session. And the order of execution might not even be defined.
What should you use instead? I don't know as I font know what you're trying to achieve in the first place
I am trying to understand how to sending HttpSession as a parameter in the spring controller works.
I have a jsp which does a post request on clicking the submit button. In the controller, reading the sessions as follows
In the controller:
public ModelAndView viewEditFundClass(HttpServletRequest request,HttpServletResponse response,Model model){
HttpSession session = (HttpSession)request.getSession();
java.util.Date startDate = sesseion.getAttribute("startDate");
However, when I just change the controller to the following, I am still able to access the session
public ModelAndView viewEditFundClass(HttpServletRequest request,HttpServletResponse response, HttpSession session,Model model)
I would like to know how this is done in Spring, ie how did the post request pass the HttpSession as a parameter? will this session be valid?
Assuming you're using Spring 3+ #Controller and #RequestMapping handler methods, Spring defines a default set of supported argument types for your handlers
Session object (Servlet API): of type HttpSession. An argument of
this type enforces the presence of a corresponding session. As a
consequence, such an argument is never null.
Spring uses the strategy pattern to accomplish this, using the interface HandlerMethodArgumentResolver. It checks the parameter types of your handler methods and, for each type, tries to find a HandlerMethodArgumentResolver that will be able to resolve an argument for it.
For HttpSession, that implementation is ServletRequestMethodArgumentResolver.
I'm using ServletRequestListener to attach to new requests, get a ServletRequest object and extract cookies from it.
I've noticed that only HTTPServletRequest has cookies but I haven't found a connection between those two objects.
Is it okay to use
HttpServletRequest request = ((HttpServletRequest) FacesContext.getCurrentInstance()
.getExternalContext().getRequest());
to retrieve the request while in a RequestInitialized method? (I do want to run on every request)
FYI - This is all done in a JSF 1.2 Application
This is not correct. The FacesContext isn't available in a ServletRequestListener per se. The getCurrentInstance() might return null, leading to NPE's.
If you're running the webapp on a HTTP webserver (and thus not some Portlet webserver for example), you could just cast the ServletRequest to HttpServletRequest.
public void requestInitialized(ServletRequestEvent event) {
HttpServletRequest request = (HttpServletRequest) event.getServletRequest();
// ...
}
Note that a more common practice is to use a Filter for this since you can map this on a fixed URL pattern like *.jsf or even on specific servlets so that it runs only when the FacesServlet runs. You might for example want to skip cookie checks on static resources like CSS/JS/images.
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) {
HttpServletRequest request = (HttpServletRequest) req;
// ...
chain.doFilter(req, res);
}
When you happens to be already inside the JSF context (in a managed bean, phaselistener or whatever), you could just use ExternalContext#getRequestCookieMap() to get the cookies.
Map<String, Object> cookies = externalContext.getRequestCookieMap();
// ...
When running JSF on top of Servlet API, the map value is of type javax.servlet.http.Cookie.
Cookie cookie = (Cookie) cookies.get("name");
Yes, you can do that. In Web scenarios, this will always be ok. If you want to be sure, you could do a check for the type first. (Good practice anyway):
if (FacesContext.getCurrentInstance().getExternalContext().getRequest() instanceof HttpServletRequest) {
...
By the way: Why do you have to use FacesContext? From where are you calling this code?