Showing posts with label Cookies. Show all posts
Showing posts with label Cookies. Show all posts

October 8, 2011

Javascript to set cookies and get hold of a specific cookie

Write Javascript code to store a cookie and retrieve it - also check if cookies are enabled on the client.

Solution

<html>
<head>
<script type="text/javascript">

var cookieFunction = function() {
   
if (navigator.cookieEnabled) {
var name = prompt("Enter cookie name");
      var value= prompt("Enter cookie value");
      if ((name) && (value)) {
         var date = new Date("1 Jan 2015 11:30:00");
         document.cookie= name + "="+value+"; expires="+date.toGMTString()+";";
      }
   } else {
      alert("Cookies Not enabled");
   }
}

var getCookie = function() {
   var cookies=document.cookie;
   alert(cookies);
}

var getSpecificCookie = function() {
   var c_name = prompt("Enter cookie name");
   var all_cookies = document.cookie.split( ';' );
   for (i=0;i<all_cookies.length;i++) {
      x = all_cookies[i].substr(0, all_cookies[i].indexOf("="));
      y = all_cookies[i].substr(all_cookies[i].indexOf("=")+1);
      x = x.replace(/^\s+|\s+$/g,"");
      if (x == c_name) {
        alert( unescape(y));
        return;
     }
   }

   alert("Cookie does not exist");
}

window.onload = function() {
   document.getElementById("getCookieButton").onclick=getCookie;
   document.getElementById("getSpecificCookieButton").onclick=getSpecificCookie;
   document.getElementById("diceButton").onclick=rollDice;
}

</script>
</head>
<body>
<button id="cookieButton">Set Cookie</button>
<button id="getCookieButton">Get Cookies</button>
<button id="getSpecificCookieButton">Get Specific Cookie</button>

</body>
</html>

September 30, 2011

Setting a cookie in the response in Struts 2

1) Create an action class - CookieWriter.java - in the src folder of the web application

package info.icontraining.struts2;

import javax.servlet.http.Cookie;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class CookieWriter extends ActionSupport {

   public String execute() throws Exception {
      ServletActionContext.getResponse()
                    .addCookie(new Cookie("firstName", "Dinesh"));
      return SUCCESS;
   }
}

2) Create the result JSP - cookieWrite.jsp - in the WebContent folder of the web application. The JSP displays the cookie sent in the response

<html>
<head>
<script type="text/javascript">

function readCookie(name) {
   var nameEQ = name + "=";
   var ca = document.cookie.split(';');
   for(var i=0;i < ca.length;i++) {
      var c = ca[i];
      while (c.charAt(0)==' ') 
         c = c.substring(1,c.length);
      if (c.indexOf(nameEQ) == 0) 
         alert("value of " + name + " cookie is " 
                    +  c.substring(nameEQ.length,c.length));
   }
   return null;
}
</script>
</head>
<body>
Setting cookie that came with the response.<br/><br/>
<a href="javascript:readCookie('firstName')" href="#">Read cookie</a>

</body>
</html>

3) Configure the action in the struts.xml configuration file

<action name="cookieWrite" class="info.icontraining.struts2.CookieWriter">
   <result>/cookieWrite.jsp</result>
</action>

4) Test the code by accessing the URL in the browser,

http://localhost:8080/WebAppName/cookieWrite.action

Reading a cookie from the request in Struts2

1) Create an action class - CookieReader.java - in the src folder of the Struts 2 enabled Web Application

package info.icontraining.struts2;

public class CookieReader {
 
   private String message;
   private String userName;
   public static final String SUCCESS = "success";

   public String getUserName() {
      return userName;
   }

   public void setUserName(String userName) {
      this.userName = userName;
   }

   public void setMessage(String message) {
      this.message = message;
   }
   
   public String getMessage() {
      return this.message;
   }
   
   public String execute() throws Exception {
      setMessage("Hello " + getUserName());
      return SUCCESS;
   }
}

2) Create the result JSP - cookieRead.jsp - in the WebContent folder of the web application

<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>Cookie Read Example</title>
</head>
<body>
   <h1><s:property value="message"/></h1>
</body>
</html>

3) Configure the action in the struts.xml, along with the configuration for the cookie interceptor. The <param> element indicates the name of the cookie that to be read from the request,

<action name="cookieRead" class="info.icontraining.struts2.CookieReader">
   <result>/cookieRead.jsp</result>
   <interceptor-ref name="cookie">
      <param name="cookiesName">userName</param>
   </interceptor-ref>
</action>

4) Create an .html file to set the cookie on the browser - cookieTest.html - add the file to the WebCon tent folder of the web application

<html>
<head>
<script type="text/javascript">
   document.cookie="userName=dinipc";
</script>
</head>
<body>
Cookie userName set.
</body>
</html>

5) Test the example by first accessing the cookieTest.html from the browser. This will set the cookie.

http://localhost:8080/WebAppName/cookieTest.html

Next, access the cookieRead.jsp from the browser

http://localhost:8080/WebAppName/cookieRead.jsp

April 10, 2011

Set a Cookie in a Servlet

1) Create the CookieDemo.java Servlet class with code to set a cookie header in the response

package info.icontraining.servlets;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class CookieDemo extends HttpServlet {
 
   protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  
      Cookie cookie = new Cookie("cookiedemo","cookievalue");
      response.addCookie(cookie);
      PrintWriter out = response.getWriter();
      response.setContentType("text/html");
      out.println("Sending response with Cookie<br/>");
      out.println("<a href=\"cookieDemo2\">Click Link</a>");
   }
}


2) Create the CookieDemo2.java Servlet class with code to retrieve from the request that was set/sent in the previous Servlet.

import javax.servlet.http.*;
import java.io.*;

public class CookieDemo2 extends HttpServlet {
 
   protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  
      PrintWriter out = response.getWriter();
      Cookie[] cookies = request.getCookies();
  
      for (Cookie c: cookies) {
         out.println("Cookie Name is " + c.getName() + "<br/>");
         out.println("Cookie Value is " + c.getValue() + "<br/><br/>");
      }

      response.setContentType("text/html");
   }
}


3) Configure both servlets in the web.xml

<servlet>
   <servlet-name>CookieDemo</servlet-name>
   <servlet-class>info.icontraining.servlets.CookieDemo</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>CookieDemo</servlet-name>
   <url-pattern>/cookieDemo</url-pattern>
</servlet-mapping>

<servlet>
   <servlet-name>CookieDemo2</servlet-name>
   <servlet-class>info.icontraining.servlets.CookieDemo2</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>CookieDemo2</servlet-name>
   <url-pattern>/cookieDemo2</url-pattern>
</servlet-mapping>


4) Test the code with the following URL in the browser

http://localhost:8080/WebAppName/cookieDemo