September 28, 2011

Session Management Example in Struts2

0|) Implement the Hello World Example for the Struts 2 framework as explained in this example

1) Modify the execute() method within the HelloWorld.java action class to set a session attribute on the SessionMap object as follows,

public String execute()  {

   ActionContext context = ActionContext.getContext();
     
   ((SessionMap) context.getSession()).put("username", getName());
     
   setCustomGreeting( GREETING + getName() );
   return Action.SUCCESS;
}

2) Modify the Hello.jsp result JSP to add an additional link as follows,

<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
  <title>HelloWorld</title>
</head>
<body>

  <h1><s:property value="customGreeting"/></h1>
  <br/><br/>

  <s:a action="Linked">Click here</s:a>
</body>
</html>

3) Add a JSP - linkedPage.jsp - in the WebContent folder of the Web application,

<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
  <title>Linked Page</title>
</head>
<body>
   <h1>In Linked Page: <s:property value="%{#session.username}"/></h1>
</body>
</html>

4) Configure the new action in the struts.xml file as follows,

<action name="Linked">
   <result>/linkedPage.jsp</result>
</action>

5) Test the example with the following URL in the browser,

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

No comments:

Post a Comment