September 30, 2011

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

No comments:

Post a Comment