Get Cookies from ServletRequest

I use ServletRequestListener to join new requests, get the ServletRequest object and extract cookies from it.

I noticed that only HTTPServletRequest has cookies, but I did not find a connection between the two objects.

Can i use

 HttpServletRequest request = ((HttpServletRequest) FacesContext.getCurrentInstance() .getExternalContext().getRequest()); 

to get a request in the RequestInitialized method? (I want to run every request)

FYI - all this is done in the JSF 1.2 application

+4
source share
2 answers

This is not true. FacesContext not available in ServletRequestListener as such. getCurrentInstance() can return null , which will result in NPE.

If you use webapp on an HTTP web server (and thus are not a Portlet web server, for example), you can simply drop ServletRequest to HttpServletRequest .

 public void requestInitialized(ServletRequestEvent event) { HttpServletRequest request = (HttpServletRequest) event.getServletRequest(); // ... } 

Note that a more common practice is to use Filter for this, since you can map it to a fixed URL pattern, such as *.jsf , or even to specific servlets so that it runs only when FacesServlet starts. For example, you can 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); } 

If you are already inside the JSF context (in a managed bean, phase designer, or something else), you can simply use ExternalContext#getRequestCookieMap() to get cookies.

 Map<String, Object> cookies = externalContext.getRequestCookieMap(); // ... 

When running JSF on top of the servlet API, the map value is of type javax.servlet.http.Cookie .

 Cookie cookie = (Cookie) cookies.get("name"); 
+5
source

Yes you can do it. In web scenarios this will always be ok. If you want to be sure, you can check the type first. (Anyway, good practice):

 if (FacesContext.getCurrentInstance().getExternalContext().getRequest() instanceof HttpServletRequest) { ... 

By the way: why do you use FacesContext ? Where do you call this code from?

0
source

Source: https://habr.com/ru/post/1345058/


All Articles