Frameworks| Hibernate| Struts| JSF| JavaFX| Ajax| Spring| DOJO| JDO| iBatis| Questions?

 

 

 

 

 

 

 

 

 

 

 

 

 

Search Tutorials

Latest Questions
Comments
 
Struts 2 Session Scope 
 

In this section, you will learn to create an AJAX application in Struts2 Framework that displays some messages with session.

 

Struts 2 Session Scope

                         

In this section, you will learn to create an AJAX application in Struts2 Framework that displays some messages with session.

The current application displays a jsp page having the two text fields. 
If the user enters nothing in the text fields and submit the form it displays an error message "nothing entered". 
If the user enters some text in the WELCOME1 field, then the corresponding attribute is set to "welcome1". 
If the user leaves the WELCOME1 field empty and enters some text in the WELCOME2 field, then the corresponding attribute is set to "welcome2".

This application is created with AJAX in Struts2 Framework. Before we start the things, we need to do the following:

  1. Download Struts2 from Apache.org
  2. Deploy the jars under Tomcat server WEB-INF/lib
  3. Rename the jars containing "plug-in" (this is very important as our application doesn't need any plugin's and Tomcat class loader sometimes fails to find the class files associated with the plugin's)
  4. Make sure the Tomcat server is the latest (Tomcat 5.5.0 and above) 
  5. Download xwork-2.0.4.jar from opensymphony.com as it is not available with the Struts2 distribution.

The struts.xml file contains the information about the files, constants, packages and actions to be included. The <include file> tag provides standard information provided by Struts2. The <constant> tags  are also there, you may set the struts.devMode constant to true, but it is not necessary. The package tag specifies a name, namespace and extends attributes. 

Pay attention to namespace as it affects the URL you have to type in the browser. If you give a namespace say "/roseindia" then your URL will be "http://localhost:8080/struts2tutorial/roseindia/showAjaxTestActionForm.action". 

To make it simpler as we don't have many packages we have set the namespace to blank so that we need only use the URL "http://localhost:8080/struts2tutorial/roseindia/showAjaxTestActionForm.action"

The action with name showAjaxTestActionForm shows in the view AjaxTest.jsp. Note that the pages don't have to be in the classpath.

struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

<!-- Rose India Struts 2 Tutorials -->
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="true" />

<include file="struts-default.xml"/>
<package name="roseindia" namespace="/roseindia" extends="struts-default">

<action name="showAjaxTestActionForm">
<result>/pages/AjaxTest.jsp</result>
</action>
<action name="AjaxTestAction" class="net.roseindia.SampleForm">
<result name="error">/pages/AjaxTest.jsp</result>
<result name="success">/pages/AjaxTest.jsp</result>
<result>/pages/AjaxTest.jsp</result>
</action>

<!-- Add actions here -->
</package>

<!-- Add packages here -->

</struts>

The action AjaxTestAction is the form action attribute. It is associated with the support class net.roseindia.SampleForm which is in the class path. The result tags mean as follows:

  • If the class returns "error" then show the error message set in the Java class in the view.
  • If the class returns "success" then update the view.
  • If the class returns nothing then update the view.

The JSP file contains a form, two text fields and a submit button. The <s:actionerror>, <s:fielderror> and <s:actionmessage> tags will display the errors associated while processing this form. The <s:div id="loginDiv" theme="ajax"> tag prints a message at the top of the view indicating which textfield has been set. It displays a message from the session's set attribute.

Here is the code for the JSP form: AjaxTest.jsp

<%taglib prefix="s" uri="/struts-tags" %>

<html>
  <head>
    <s:head theme="ajax" debug="true"/>
  </head>
  <body>
    <s:div id="loginDiv" theme="ajax">
        <h3> Your Session: <s:property value="#session.ret" /></h3>
    <div style="width: 300px;border-style: solid">
      <s:form action="AjaxTestAction"  validate="false">
        <tr>
          <td colspan="2">
            Run Test
          </td>
        </tr>
        <tr>
          <td colspan="2">
            <s:actionerror />
            <s:fielderror />
            <s:actionmessage/>
          </td>  
          <s:textfield name="welcome1" label="WELCOME1"/>
          <s:textfield name="welcome2" label="WELCOME2"/>
          <s:submit value="Submit" theme="ajax" targets="loginDiv" 
                                  notifyTopics=
"/AjaxTestAction"/>
        </tr>
      </s:form>
    </div>
    </s:div>
  </body>
</html>

The following java class extends the ActionSupport class that implements the SessionAware interface. This way we can get the best of the both worlds because SessionAware will add attributes to the session that can be accessed from the JSP. In our case it will be the "ret" attribute. The setter and getter methods are straightforward. 

Here is the code of SampleForm.java:

package net.roseindia;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.interceptor.SessionAware;
import java.util.Map;

public class SampleForm extends ActionSupport implements SessionAware{
  //Fields that hold data
  private String Welcome1="";
  private String Welcome2="";
    private Map session;

  public String execute() throws Exception {
    if (getWelcome1().trim().equals(""&& getWelcome2().trim().equals("")){
      addActionError("nothing entered");
            return ERROR;
    }
    if (!getWelcome1().trim().equals(""&& !getWelcome2().trim().equals("")){
      addActionMessage("Both have data!");
            return ERROR;
        }
        if (!getWelcome1().trim().equals("")){
      getSession().put("ret""welcome1");
      addActionMessage("Welcome 2 is empty!");
      return ERROR;
        }
        if (!getWelcome2().trim().equals("")){
      getSession().put("ret""welcome2");
      addActionMessage("Welcome 1 is empty!");
      return ERROR;
        }
        return SUCCESS;
  }
  public void setWelcome1(String s) {
    this.Welcome1= s;
  }
  
  public String getWelcome1() {
    return Welcome1;
  }

  public void setWelcome2(String s) {
    this.Welcome2= s;
  }
  
  public String getWelcome2() {
    return Welcome2;
  }

  public void setSession(Map session) {
    this.session = session;
  }
  
  public Map getSession() {
    return session;
  }

}

Compile the class, start the Tomcat, and test the application by typing the following URL on the address bar of web browser: "http://localhost:8080/struts2tutorial/roseindia/showAjaxTestActionForm.action"

Output:

When this application executes you get a page as shown:

If you leave the "WELCOME1" and "WELCOME2" field empty then a message is displayed with session as shown below:

After clicking the "Submit" button then you get:

If you leave the "WELCOME1" field empty and just fill the "WELCOME2" field then a message is displayed with session as shown below:

If you fill the "WELCOME1" field and just leave the "WELCOME2" field empty then a message is displayed with session as shown below:

If you fill both field then you get:

                         

» View all related tutorials
Related Tags: c ajax error com application login debug io user get password word display page field name bug widget using fields

Leave your comment:

Name:

Email:

URL:

Title:

Comments:


Enter Code:

Audio Version
Reload Image
 

Note: Emails will not be visible or used in any way, and are not required. Please keep comments relevant. Any content deemed inappropriate or offensive may be edited and/or deleted.

No HTML code is allowed. Line breaks will be converted automatically. URLs will be auto-linked. Please use BBCode to format your text.

Add This Tutorial To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 

Current Comments

7 comments so far (
post your own) View All Comments Latest 10 Comments:

It was very helpful

Posted by Riyaz on Monday, 09.22.08 @ 21:19pm | #80610

Unfortunatelly, This tutorial doesn't work in IE 7. I tried my best to do that, but failed. Could any one make it work and post modified codes? I'd be appreciated.

Posted by Johnnie on Wednesday, 11.21.07 @ 19:44pm | #38197

This tutorial works perfect well in Firefox, but it didn't work in IE 7. I tried my best to fix the bug, eventually failed. Could any one post some codes to make this tutorial work in IE 7? Thanks in advance!

Posted by Johnnie on Wednesday, 11.21.07 @ 19:33pm | #38194

Hi Anita!
We got your request to know about the tabbed Panel in struts 2 using Ajax theme.

Please visit:
Struts 2 tabbedpanel tag

And try again, <s:div id=" "> if this id is same then it gives an error (widget ID collsion on ID).

Thanks for visiting our site:
Vinod Kumar

Posted by Vinod Kumar on Tuesday, 10.23.07 @ 10:45am | #34603

struts2 and java is powerfull

Posted by yos on Saturday, 10.20.07 @ 08:11am | #34433

I want to know abt the tabbed panel in stuts2 using ajax theme.
i am trying this tabbedpanel using ajax theme in struts 2, but i am getting an error (widget ID collsion on ID). please guide me on this

Posted by Anita on Friday, 10.12.07 @ 16:35pm | #33440

Most excellently superb tutorial. May I ask what wall of bathroom u found it. thx

Posted by Nagi Najer on Thursday, 09.20.07 @ 01:11am | #27877

Training Courses
Tell A Friend
Your Friend Name
Software Solutions
Least Viewed
Most Rated
Recently Viewed
Search Tutorials

 

 
 

Home | JSP | EJB | JDBC | Java Servlets | WAP  | Free JSP Hosting  | Search Engine | News Archive | Jboss 3.0 tutorial | Free Linux CD's | Forum | Blogs

About Us | Advertising On RoseIndia.net  | Site Map

India News

Indian Software Development Company | iPhone Development Company in India | Flex Development Company in India | Java Training Delhi | Java Training at Noida |

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright © 2008. All rights reserved.