Saving and using cookies with CDI

I am trying to store a Cookie as requested by the user and later use this cookie to populate a textbox. I am using Java CDI and login bean. I'm new to all three. For online resources, all I can find is

@Inject @CookieParam
private String username;

      

and

@Inject @CookieParam("username")
private Instance<String> usernameResolver;
...
String username = usernameResolver.get();

      

For the first error message it says " Unsatisfied dependencies for type [String] with qualifiers [@Default]"

For the second, the only error I get is saying "Failed to start context"

How do I fix this problem?

thank

+3


source to share


1 answer


As the @CookieParam

package name suggests
, this is specific to JAX-RS, Java EE to other RESTful web services. This will only work in a JAX-RS managed resource in annotation @Path

. This won't work in a managed JSF or CDI bean, annotated @ManagedBean

or @Named

.

If you are using JSF @ManagedBean

to manage the bean then it is available by EL evaluation #{cookie.username}

as @ManagedProperty

.

@ManagedBean
public class Bean {

    @ManagedProperty("#{cookie.username}")
    private String username;

    // ...
}

      

If you are using CDI @Named

to manipulate the bean, you either resort to custom annotation or grab it as Cookie

from the current one FacesContext

. Since the former is not trivial (but actually a good idea for OmniFaces , although I'll only show the latter:

@Named
public class Bean {

    private String username;

    @PostConstruct
    public void init() {
        Cookie cookie = (Cookie) FacesContext.getCurrentInstance().getExternalContext().getRequestCookieMap().get("username");

        if (cookie != null) {
            username = cookie.getValue();
        }
    }

    // ...
}

      

Then, to keep it, the only way is to use it ExternalContext#addResponseCookie()

.



FacesContext.getCurrentInstance().getExternalContext().addResponseCookie("username", username, properties);

      

Remember to take into account that the cookie value is very restrictive on the characters allowed. You might need url-encode and -decode when saving and retrieving. The OmniFaces JSF Utility Library provides helper methods that do this implicitly.

username = Faces.getRequestCookie("username");

      

Faces.addResponseCookie("username", username, -1);

      


Unrelated to a specific issue, storing something sensitive like "username" as a cookie is scary. Did you know that cookies are manipulated by the end user? That the person who visits your web page can easily edit the cookie value representing the "username" for someone else?

+3


source







All Articles