I am rather new to servlets and currently I'm struggling with adding cookies. I believe this is a result of a modular approach i am taking in that I built a header utility class that simply inserts all the header information into the servlet so I want to take the same approach with adding cookies.
I also have a crediential validator class that excepts the user name and password, validates it, then returns a valid/invalid response. Here i believe lies the problem. In the login form that passes the username and password to the credential validator, I have the form action directing to the credential servlet and the form method as a post.
Doing it this way provides a problem if i want to send a value from the form to another servlet, or does it?
The goal of this project, for school, is to create a simple website strictly with servlets then we get to use JSP to ease the pain.
Is there another approach i should be considering? Is it possible to have these classes that perform a variety of functions on forms when the form action and method are utilized?
Thank you for any help and guidance.
Best
E
You could send requests to a servlet and then forward requests to another servlet if needed.
In your case, after validation, you can store result in an attribute and then transfer control to another servlet. (if that's what you want to do)
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/urlToServlet");
dispatcher.forward(request, response);
And this is how to deal with cookies.
create and send cookies
Cookie userCookie = new Cookie("name", "value");
userCookie.setMaxAge(60*60*24*365); //Store cookie for 1 year
response.addCookie(userCookie);
read cookie from client
String cookieName = "somecookie";
Cookie[] cookies = request.getCookies();
if (cookies != null)
{
for(int i=0; i<cookies.length; i++)
{
Cookie cookie = cookies[i];
if (cookieName.equals(cookie.getName()))
{
doSomethingWith(cookie.getValue());
}
}
}
else
{
//do something else for firsttime visitors
}
Are you using cookies for session tracking?
If yes, then use HttpSession
. Using HttpSession then there is not need to directly involve with cookies for session tracking.
For example, in a simple login page, this is what you do
HttpSession session = request.getSession();
session.setAttribute("username",username);
In other pages,
if(session.getAttribute("username")==null)
{
//forward to login page.
}
You need to use addCookie in HttpServletResponse. I'd suggest having the java doc to hand so that you can see what is available to a servlet. http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletResponse.html#addCookie(javax.servlet.http.Cookie)