September 30, 2011

Setting a cookie in the response in Struts 2

1) Create an action class - - 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 {
                    .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

<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;
Setting cookie that came with the response.<br/><br/>
<a href="javascript:readCookie('firstName')" href="#">Read cookie</a>


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

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

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


No comments:

Post a Comment