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
 
 
Search All Tutorials
  

 
Programming Tutorials: Ajax | Articles | JSP | Bioinformatics | Database | Free Books | Hibernate | J2EE | J2ME | Java | JavaScript | JDBC | JMS | Linux | MS Technology | PHP | RMI | Web-Services | Servlets | Struts | UML
 
Struts
  JDO Tutorials
  EAI Articles
  Struts Tutorials
  Java Tutorials
  Java Certification
  Java Applet
Questions
Comments

Writing JSP, Java and Configuration for Hello World Application

                         

In this section we will write JSP, Java and required configuration files for our Struts 2 Hello World application. Now in struts 2 struts.xml is used to configure the applications.

Understanding the application

Our application is very simple application that displays Hello World message along with current date and time of the server. When user clicks on the "Run Struts 2 Hello World Application" link on the tutorial home page, a request is sent to the struts framework. Then struts framework sends the input to the action class (in our case Struts2HelloWorld.java). After action is fired the Result selects the resource "/pages/HelloWorld.jsp" to render the response. 

In this example we have to develop three parts view, Action class and mapping (struts.xml) to couple action and page. By creating these three components we are separating the application in three parts View, Model and Controller.

Developing View:
This page is used to display the result on the browser. The HelloWorld.jsp is view part of our application. Create "HelloWorld.jsp" in the struts2tutorial\pages directory and add the following content:

<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>Struts 2 Hello World Application!</title>
</head>
<body>
<h2><s:property value="message" /></h2>
<p>Current date and time is: <b><s:property value="currentTime" /></b>
</body>
</html>

The line <%@ taglib prefix="s" uri="/struts-tags" %> declares data tag library of struts. The struts data tag is used to display the dynamic data. The tag <s:property value="message" /> and <s:property value="currentTime" /> calls the methods getMessage() and getCurrentTime() respectively of the Struts2HelloWorld action class and merges the values with response.

Developing Action (to interact with Model):

Now create Struts2HelloWorld.java and saves it to the "struts2tutorial\WEB-INF\src\java\net\roseindia" directory. This action class creates the message to be displayed on the screen. Here is the code of Struts2HelloWorld.java:

package net.roseindia;
import com.opensymphony.xwork2.ActionSupport;
import java.util.Date;

public class Struts2HelloWorld extends ActionSupport {

    public static final String MESSAGE = "Struts 2 Hello World Tutorial!";

    public String execute() throws Exception {
        setMessage(MESSAGE);
        return SUCCESS;
    }

    private String message;

    public void setMessage(String message){
        this.message = message;
    }

    public String getMessage() {
        return message;
    }

  public String getCurrentTime(){
      return new Date().toString();
  }
}

Developing Controller Configuration File:

Struts 2 uses the struts.xml file for configuring the application. Create struts.xml file and save it in the "struts2tutorial\WEB-INF\src" directory with the following content.

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

<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="true" />

<package name="roseindia" namespace="/roseindia" extends="struts-default">

<action name="HelloWorld" class="net.roseindia.Struts2HelloWorld">
<result>/pages/HelloWorld.jsp</result>
</action>

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


<!-- Add packages here -->

</struts>

The struts.xml file should be present in the class path of the application, you can either include it in the jar and place in the lib directory of the application or place it in the classes directory of the web application. In our application we are using ant build tool which is including it in the jar file.

Building the application

I am assuming that you have already installed ant build tool on your machine. Since we are using the ant built tool, building application by using is very easy. To build the application open command prompt and go to "struts2tutorial\WEB-INF\src" directory of the web application and issue the "ant" command. The ant build tool will compile the java file and create jar file "struts2tutorial.jar" into the lib directory of your web application. Here is the output of ant build tool:


C:\apache-tomcat-6.0.10\apache-tomcat-6.0.10\webapps\struts2tutorial\WEB-INF\src
>ant
Buildfile: build.xml

clean:
[delete] Deleting directory C:\apache-tomcat-6.0.10\apache-tomcat-6.0.10\webapps\struts2tutorial\WEB-INF\classes
[mkdir] Created dir: C:\apache-tomcat-6.0.10\apache-tomcat-6.0.10\webapps\struts2tutorial\WEB-INF\classes

prepare:

resources:

compile:
[javac] Compiling 1 source file to C:\apache-tomcat-6.0.10\apache-tomcat-6.0.10\webapps\struts2tutorial\WEB-INF\src\classes
[jar] Building jar: C:\apache-tomcat-6.0.10\apache-tomcat-6.0.10\webapps\struts2tutorial\WEB-INF\lib\struts2tutorial.jar

project:

all:

BUILD SUCCESSFUL
Total time: 7 seconds
C:\apache-tomcat-6.0.10\apache-tomcat-6.0.10\webapps\struts2tutorial\WEB-INF\src
>

Testing Struts 2 Hello World Application

In the above section we have compiled our application and now finally we will test our application. To test the application start the tomcat server and type http://localhost:8080/struts2tutorial/ and then select "Run Struts 2 Hello World Application" from the list. 
Here is the screen shot of our struts 2 tutorial home page:

 Select "Run Struts 2 Hello World Application" link. Our first application "Struts 2 Hello World" will look like the following:

The application will display message "Struts 2 Hello World Tutorial!" along with current date and time of the server.

How application works?

Here is the brief description on how Struts 2 Hello World Application works:

Your browser sends a request to the web server for the URL http://localhost:8080/tutorial/HelloWorld.action.

  1. When you click on the "Run Struts 2 Hello World Application" link, the browser sends a request for the url http://localhost:8080/struts2tutorial/roseindia/HelloWorld.action. The container requests for the resource "HelloWorld.action". By default web.xml file of struts blank application is configured to route all the request for *.action through  org.apache.struts2.dispatcher.FilterDispatcher. Here is the configuration from web.xml file:
    <filter>
    <filter-name>struts2</filter-name>
    <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
    </filter>

    <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
    </filter-mapping>

      
  2. Then the framework looks for the mapping for the action "HelloWorld" and then framework instantiates the appropriate class and calls the execute method. In this case action class is Struts2HelloWorld. Here is the configuration file from struts.xml which defines the action mapping:
    <action name="HelloWorld" class="net.roseindia.Struts2HelloWorld">
    <result>/pages/HelloWorld.jsp</result>
    </action>

          
  3. Then the execute method sets the message and returns SUCCESS. 
    public String execute() throws Exception {
        setMessage(MESSAGE);
        return SUCCESS;
    }


    Then framework determines which page is to be loaded if SUCCESS is returned. In our case framework tells the container to load HelloWorld.jsp and render the output
    .

    In the struts 2 framework Actions are used to process the form and user request. The execute method of the action returns SUCCESS, ERROR, or INPUT value. Then based on these values framework tells the container to load and render the appropriate result.
     
  4. Container process the HelloWorld.jsp and generates the output.
     
  5. Then the output in the HTML format is sent to the browser.

Download the application and source code:
You can download the application and source code of the tutorial and to save your time and efforts spent on configuring the application. Click here to download the code. 

Our goal is to provide the working skeleton of the application based on ant tool. So you can download the application and then use ant tool to compile the java classes. Application is in the exploded directory structure and can be deployed as it is on tomcat server. If any of our visitor finds and problem please discuss it. We request you to share your experiences with us.

                           

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

Current Comments

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

Please can someone fix the cannot find action error?

i have tried the things the previous commenter suggested and it is still not working


Posted by alan on Monday, 10.13.08 @ 11:47am | #81039

The error comes because we are trying to put the jar file in lib directory as well as the compiles classes in the classes directory .. please remove all the directory from the classes directory if u are using ant...

Posted by amit on Thursday, 09.25.08 @ 11:23am | #80688

It was really inspiring for me to go through this tuorial.I would be really proud to & eager to see more tutorials like this to improve our knowldge.

Posted by Beta on Saturday, 09.20.08 @ 15:34pm | #80565

I'm having problems running this. I've followed the instructions closely, but get a message "There is no Action mapped for action name HelloWorld."


Posted by Ed Hoover on Wednesday, 09.3.08 @ 23:29pm | #77020

hello,
so , thanks a lot for all those samples,there are a explained verry well ... thank's .
i have a problem with my HelloWorls sample , i use the IDE eclipse 3.3 , his structure is diffrent par rapport the othrs version of eclipse and i didn't khnow where i put my struts.xml file ???
it take me a long time this error , i tryed to mades it iin any places , but it doesn't work ... plz help me :: i am new in Struts 2 ...

Sometimes i ha a following error " the filtr dispatchrcan't .............." , i added in my web.xml file the tag <filter > the dispatcher filtre ... even this it oesent' work ...
always its displayed
"Etat HTTP 404- /struts2tutorial/example/login.jsp ..... "

Thanks
Please where is the plroblem :(

Posted by younes on Tuesday, 08.26.08 @ 14:12pm | #75230

hello,
so , thanks a lot for all those samples,there are a explained verry well ... thank's .
i have a problem with my HelloWorls sample , i use the IDE eclipse 3.3 , his structure is diffrent par rapport the othrs version of eclipse and i didn't khnow where i put my struts.xml file ???
it take me a long time this error , i tryed to mades it iin any places , but it doesn't work ... plz help me :: i am new in Struts 2 ...

Sometimes i ha a following error " the filtr dispatchrcan't .............." , i added in my web.xml file the tag <filter > the dispatcher filtre ... even this it oesent' work ...
always its displayed "ERROR 404 sources not found ..... "

Thanks

Posted by younes on Saturday, 08.23.08 @ 19:24pm | #74629

My Struts2 application not run. it gives 404 error.Why?
i am just download file and put it to web app for sample application but it gives the resoureces not found 404 error.
i am using tomcat 5.0
java 1.5

Where the problem please tell me?

Posted by Buro on Sunday, 08.10.08 @ 01:07am | #71962


I am new to struts 2. I have problem to start the sturts 2 framework. Whenever I put web.xml under WEB-INF direcotry, the application starts to fail, but it works when I remove web.xml. Does anyone oan tell why?

Thanks,

-- Allen --

Posted by Allen on Saturday, 08.9.08 @ 03:58am | #71827

Hi, I have a weird problem. When I go to the address: http://localhost:8080/struts2tutorial/index.html the application works fine, however if I go to http://localhost:8080/struts2tutorial/ then the application redirects me to the http://localhost:8080/struts2tutorial/example/HelloWorld.action,
which is what the example index.html does (which I have deleted, rebuilt the whole application and restarted Tomcat). Does anybody know why this is happening?
Thanks

Posted by peter on Friday, 05.30.08 @ 17:45pm | #61448

Hi Andrew

I tried the solution posted by you to remove the namespace entry in the package tag. I still see the same error. Was anyone else successful in resolving this error?

Thanks
Krishna

Posted by Krishna on Wednesday, 05.7.08 @ 22:41pm | #58819

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.

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

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

Copyright © 2008. All rights reserved.