What to do if cookie already exists? - java

In my application I have a dropdownlist and when the user clicks on an item is redirects them to a certain page. In this servlet I create a cookie with there selected item which contains the value of the drop-down list(So when they return the the previous page that item will be selected in the drop-down list)
What I want to know different values may be selected at different times it there a way to modify the cookie for that drop-down list or do I have to create a new one each time. I cant see that as being a sustainable way of doing it?

You can edit the cookie by getting it from the request and assigning the new value:
Cookie[] cookies = request.getCookies();
Cookie dropDownCookie = null;
for (Cookie cookie : cookies) {
if(cookie.getName().equals("DROP_DOWN_COOKIE")){
dropDownCookie = cookie;
}
}
if(dropDownCookie!=null){
dropDownCookie.setValue("THE NEW VALUE");
response.addCookie(dropDownCookie);
}

Related

Spring - HttpServletRequest object null when deleting JSESSIONID cookie?

I am testing a new functionality in my web app where i'm allowing the user to remain signed in even after the browing session expires. In order to achieve this, i have a "Keep me logged in" checkbox on my login page. Upon successful login, a cookie is created containing the userID and the login process continues normally. The first thing the first method in my main controller does is check for the presence of that cookie, read the userId in it, set the User object in the session correctly and bypass the login process, going directly to the home page. When the user signs out, the cookie is recreated with an expiration of 0 which means it's automatically deleted.
My Spring sessions last 30 minutes currently. I have successfully tested everything but i'm trying to replicate the Spring session expiring, which gets rid of the User object in memory and would normally force the user to login. In order to replicate it, i am deleting the JSESSIONID cookie from Chrome. When i do that, the HttpServletRequest object (which I am checking cookies on) is null.
Here is the first code that runs in my main controller :
#RequestMapping(value = {"/"}, method = RequestMethod.GET)
public String home(ModelMap model, HttpServletRequest request)
{
if (session.getAttribute("loggedInUser") != null)
{
return "home";
}
else
{
String userId = null;
for (Cookie cookie : request.getCookies())
{
if (cookie.getName().compareTo("MDHISStaySignedIn") == 0)
{
userId = cookie.getValue();
break;
}
}
if (userId != null)
{
session.setAttribute("loggedInUser", userService.findByUserId(userId));
return "redirect:/";
}
else
{
model.addAttribute("login", new Login());
model.addAttribute("register", new Register());
model.addAttribute("registering", false);
return "login";
}
}
}
Is it normal that my request object is null when deleting this cookie? Am i not correctly replicating the Spring session timing out by deleting it? This NullPointerException only happens when deleting this cookie and upon first running the web app, the controller does not thrown the exception when the cookie is created by the first run. Should i somehow be checking for this null value and redirecting the controller back to this method if it is?
Thanks!
The solution is to add the following method parameter :
#CookieValue(value = "MDHISStaySignedIn", defaultValue = "notFound") String cookie
This will assign the content of the cookie to the value if it's present and assign "notFound" if it is not. This way one can access cookies when the request object is null!

How to delete cookie while closing the browers tab using servlet cookie

{
final Cookie cookies = new Cookie(key, value);
cookies.setMaxAge(-1);
response.addCookie(cookies);
}
by setting the MaxAge = -1 will clear the cookie when the browser being closed. But I want to clear the cookie while closing the tab.

Delete a cookie by its value

How do I delete a cookie by its value?
In my.jsp page I am setting the cookie
String timeStamp = new SimpleDateFormat("dd:MM:yyyy_HH:mm:ss:SSS").format(Calendar.getInstance().getTime());
timeStamp = timeStamp + ":" + System.nanoTime();
String loc = "/u/poolla/workspace/FirstServlet/WebContent/WEB-INF/"+timeStamp;
Cookie cookie = new Cookie("path", loc);
Multiple users will have cookies with the same name but different loc values,
So, How do I get the cookie value in servlet.java and delete a particular loca value cookie??
Cookies are not same for each user. Generally cookies are tied to the client/user/browser which is accessing the JSP/application and each client can have a cookie value of its own.
When you delete a cookie you just delete it for the client which has made the request to your application. Rest of the clients will still have their own cookie without any effect in the value. Hence, you need not to worry about deleting a cookie may affect multiple users.
In order to delete a cookie, first get all the cookies from request and delete the cookie which has particular name/value.
public void delete(MyType instance) {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("test")) {
cookie.setValue(null);
cookie.setMaxAge(0);
cookie.setPath(theSamePathAsYouUsedBeforeIfAny);
response.addCookie(cookie);
}
}
}
}
You will need to call getCookies() on the request and loop through them until you find the one you're looking for.
here is a little simple example tha might help you
//declaring a cookie
Cookie cookie = new Cookie(name, value);
//getting the cookie name
String name = cookie.getName()
//getting the cookie value
String value= cookie.getValue();

java.lang.nullpointerexception when creating array of cookie objects in servlet

have a html form where 4 option buttons are there. when user click submit button servlet wil execute and need to create cookie of selected options.
i wrote following code, but when i "INITIALIZE ARRAY OF OBJECTS OF COOKIES" the nullpointerexception comes.WITHOUT COOKIE INITIALIZATION my program works well.
Cookie[] cookie=null; int i=1;
while(paramNames.hasMoreElements()){
String paramName = (String)paramNames.nextElement();
String[] paramValues = req.getParameterValues(paramName);
String paramValue = paramValues[0];
cookie[i] = new Cookie(paramName, paramValue); **//ERROR IS HERE**
cookie[i].setMaxAge(60*60*24);
resp.addCookie(cookie[i]);
i++}
I CHECKeD THE VALUES "paramName, paramValue". i got Correct Answer without Cookie. what will be the error when i initialize array of objects of cookie like this?
cookie is null and you are trying to access an index of an array which is null.
You should initialize it this way:
Cookie[] cookie = new Cookie[someNumber];
You have not initialized the array of Cookies.
use Cookie[] cookie=new Cookie[SIZE] instead of Cookie[] cookie=null to initialize it before assigning a value to it.

session servlets and href tag

what I'm trying to do is relative simple
In my webapp there are these two servlets:
(I will write some pseudocode)
servlet A code: :
HttpSession sess = req.getSession();
String str = (String) sess.getAttribute("log");
if(str == null)
{
// send html page with a form
// to enter password and name
// data will be proceessed by servlet B
}
else
{
// send html page with a form
// to enter only a name
//data will be proceessed by servlet B
}
servlet B code: :
HttpSession sess = req.getSession();
String logged = (String) sess.getAttribute("log");
if(logged == null)
{
//check if password correct
if(correct)
{
sess.setAttribute("log","ok");
// print name
// and tell the user
// that next time password
// will not be requested
}
else
{
// print error message
}
}
else
{
// print name
}
for some reason the second time the servlet A is called after that the user filled in password and name correctly
str is null so the if part gets printed.
EDIT:
I discovered that if the user after inserting the password and
being redirected to servletB writes the url of servletA by himself
all goes right , but it odesn't work when the user gets back to the previous
page using a link created by servletA:
A HREF=\"http://localhost:8080/Blog/ServletA\" back
again , any suggestions why this happens?
I believe its not entering in your if(correct) block i.e. correct condition is not getting satisfied. Correct the condition there and make sure, it sets the log attribute in the session. Once a attribute is set into the session, its there until session expires or your remove it.

Categories

Resources