Creating Servlet Cookies

I am new to servlets and am currently struggling with adding cookies. I believe this is the result of the modular approach that I take in that I built a header utility class that simply inserts all the header information into the servlet, so I want to use the same approach with adding cookies.

I also have a validation class that, with the exception of the username and password, validates it and then returns a valid / invalid response. Here I find the problem. In the login form, which passes the username and password to the credential validator, I have a form action that directs to the credential servlet and the form method as a message.

Doing this method creates a problem if I want to send a value from a form to another servlet or do it?

The goal of this project for the school is to create a simple website strictly with servlets, then we can use JSP to relieve pain.

Is there any other approach I should consider? Is it possible for these classes to perform many functions on forms using an action and a form method?

Thanks for any help and recommendations.

Best E

+4
source share
2 answers

You can send requests to the servlet and then redirect requests to another servlet, if necessary.

In your case, after checking, you can save the 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 here is how to handle 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 } 

Do you use session tracking cookies? If yes, use HttpSession . Using HttpSession, there is no need to directly enable cookies for session tracking.

For example, on 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. } 
+11
source

You need to use addCookie in the HttpServletResponse. I would advise you to pass a java document so that you can see what is available to the servlet. http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletResponse.html#addCookie(javax.servlet.http.Cookie )

+2
source

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


All Articles