Last updated on May 5th, 2016 at 01:59 am
Java Servlet create cookie example, Just a straight forward and simple example on using Servlet to create a cookie and read it..
All you have to do is copy the below script and Name it as HttpCookie.java, Modify the code according to your needs.
import javax.servlet.http.Cookie; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Date; import java.io.*; public class HttpCookie extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); InputStream input = null; try { String getData = request.getParameter("Username"); Cookie userCookie = new Cookie("username",getData); //setting cookie to expiry in 30 mins userCookie.setMaxAge(30*60); response.addCookie(userCookie); Date date = new Date(); out.println("<html><title>Welcome</title><body>"); out.println("User ID "+getData+" Has Logged In Now @ "+date.toString()); System.out.println("User ID "+getData+" Has Logged In Now @ "+date.toString()); String username = "novalue"; Cookie[] cookies = request.getCookies(); for (int i = 0; i < cookies.length; i++) { if ((cookies[i].getName()).equals("username")) { username = cookies[i].getValue(); out.println("<div>Welcome <div id='username'>"+cookies[i].getValue()+"</div></div>"); } } out.println("</body></html>"); } finally { if (input != null) { try { input.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
Now compile the script by using
javac HttpCookie.java
Copy the class file created to the WEB-INF/classes directory.
Edit the web.xml file and add this
<servlet> <servlet-name>HttpCookie</servlet-name> <servlet-class>HttpCookie</servlet-class> </servlet> <servlet-mapping> <servlet-name>HttpCookie</servlet-name> <url-pattern>/HttpCookie.do</url-pattern> </servlet-mapping>
Save the file and make sure the application got reloaded by checking the server.log file if you are using Jboss.
Using the URL http://yourwebsite/HttpCookie.do?Username=admin and see the output how the servlet set the cookie and read the value of the cookie.