Cookie example Program using getComment(), setComment() methods to get or set a comment
GetComment.java
package com.candidjava; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * Servlet implementation class GetComment */ public class GetComment extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public GetComment() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { // TODO Auto-generated method stub String str = req.getParameter("Name"); System.out.println(str); // Cookie(key,value); Cookie ck = new Cookie("key", str); PrintWriter out = res.getWriter(); res.setContentType("text/html"); // HttpServletResponse.addCookie(Cookie); res.addCookie(ck); ck.setComment("to calculate the time"); String s = ck.getComment(); HttpSession ses = req.getSession(true); ses.setAttribute("k1", str); ses.setAttribute("k2", s); res.sendRedirect("Comment.jsp"); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } }
web.xml
comment GetComment GetComment com.candidjava.GetComment GetComment /GetComment Comment.html
Comment.html
Comment.jsp
comment output page Your cookie's name
your cookie's comment is
Output
Output 1:
Output 2:
Download Source: Comment
This post first appeared on Core Java,Servlet,Jsp,Struts,Hibernate,Spring Fram, please read the originial post: here