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

No comments:

Post a Comment