Home | Ajax | BioInformatics | Dojo | EAI | EJB | Hibernate | J2ME | Java | Java Glossary | Java Servlets | JavaScript | Jboss | JDBC | JDO | Jmeter | JSF | JSP | JUnit | Maven | MySQL | Spring Framework | SQL | Struts | Technology | WAP | Web Services | XML
Struts
  JDO Tutorials
  EAI Articles
  Struts Tutorials
  Java Tutorials
  Java Certification
  Java Applet
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:

                         

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

Latest Tutorials:
Horizontal Rule in HTM
Show Hyperlink in HTML
Unordered Lists
Paragraph in HTML
Password Field in HTML
Radio Buttons in HTML
Set Background Colors
Table & the Border att
Text Area in HTML
Text Field in HTML
Use of Text Field
Table Caption in HTM
J2ME Servlet Example
J2ME Cookies Example
J2ME Frame Animation2
J2ME Frame Animation
J2ME RMS Read Write
J2ME Record Data Base
J2ME Audio Record
J2ME Record Listener
J2ME Text Box Example
J2ME Timer Animation
J2ME Vector Example
J2ME Video Control Exa
J2ME Event Handling Ex
J2ME HashTable Example
J2ME Icon MIDlet Examp
J2ME Image Item Exampl
J2ME Image Example
J2ME Item State Listen
J2ME Key Codes Example
J2ME KeyEvent Example
J2ME Label Example
J2ME Random Number
J2ME Read File
J2ME RMS Sorting Examp
J2ME Timer MIDlet Exam
Custom Item in J2ME
Creational Design Patt
Design Patterns
Throwing Run time exce
Grid in Echo3
Creating Table in Echo
JPA Introduction
Java bigdecimal toBigI
Java bigdecimal shortV
Java bigdecimal shortV
Java bigdecimal signum
Java bigdecimal stripT
Java bigdecimal subtra
Java bigdecimal subtra
Java bigdecimal toBigI
Java bigdecimal toEngi
Java bigdecimal toPlai
Java bigdecimal toStri
Java bigdecimal ulp ex
Java bigdecimal unscal
Java bigdecimal valueO
Java bigdecimal valueO
Java bigdecimal valueO
Java bigdecimal setSca
Java bigdecimal setSca
Java bigdecimal scaleB
Java bigdecimal scale
Java bigdecimal round
Java bigdecimal remain
Java bigdecimal remain
Java bigdecimal precis
Java bigdecimal pow me
Java bigdecimal pow ex
Java bigdecimal plus m
Java bigdecimal plus e
Java bigdecimal negate
Java bigdecimal negate
Java bigdecimal multip
Java bigdecimal multip
Java BigDecimal movePo
Java bigdecimal movePo
Java bigdecimal min ex
Java bigdecimal max ex
CheckBox component in
Visibility of Componen
Loading delay componen
Simple input applicati
Opening a new window i
Hello World in Echo3 f
Use of Local Inner cla
JSP bean set property
Java Method Synchroniz
Java Method Return Val
JAVA Method Wait
JDBC vs ORM
Java BigDecimal divide
Java BigDecimal divide
Java BigDecimal divide
Java BigDecimal divide
Java BigDecimal divide
Java BigDecimal double
Java BigDecimal equals
Java BigDecimal hashCo
Java String toLowerCase Example
Java String toCharArray Example
Java String substring Example
Java String indexOf Example
Java String startsWith Example
Java String hashCode Example
Java String matches Example
Java String length Example
Java String lastIndexOf Example
Java String isEmpty Example
Java String equalsIgnoreCase Example
Java String equals Example
Java String endsWith Example
Java String copyValueOf Example
Java String contentEquals Example
  EAI Articles
  Java Certification
Tell A Friend
Your Friend Name
Search Tutorials

 

 
 
Browse all Java Tutorials
Java JSP Struts Servlets Hibernate XML
Ajax JDBC EJB MySQL JavaScript JSF
Maven2 Tutorial JEE5 Tutorial Java Threading Tutorial Photoshop Tutorials Linux Technology
Technology Revolutions Eclipse Spring Tutorial Bioinformatics Tutorials Tools SQL
 

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 | 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.