Recently I’ve started learning the Struts 2 framework. Though I’ve been using Struts 1.3 for quite some time, understanding Struts 2 was little tricky as the ‘Hello World sample application’ provided by Struts 2 site is little confusing. So, I was searching for a simple ‘Hello world example for Struts 2′ and after going through many different sites, finally I was able to run my first Struts 2 application. Here are the steps that I did to start with Struts 2. I am using Eclipse IDE and all the steps explained below are in referring to Eclispe 3 IDE.
Struts 2 Hello World Application – Getting started with Struts 2
- Create New : Project : Dynamic Web Project and give a name to your project and the location to save your project. For this example, I gave HelloWorld as my project name.
- Second step will be including JAR files required by Struts 2 framework to our project’s WEB-INF/lib folder. You can either download below JARs separately or simple copy them from the lib folder of struts2-blank-application provided by Struts 2 website. Note that the version numbers in the JAR files are the latest ones when this article written. You may use the latest JARs if they are available.
- commons-logging-1.0.4.jar
- freemarker-2.3.8.jar
- ognl-2.6.11.jar
- struts2-core-2.0.11.jar
- xwork-2.0.4.jar
- Next step will be configuring struts 2 filter in web.xml file. Have a look at the below sample configuration.
<?xml version="1.0" encoding="UTF-8"?> <web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <display-name>Struts 2 : Hello World</display-name> <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> </web-app>
- Now we will create a struts action class HelloWorld.java. To do this, create a new package tutorial under the project’s source folder and inside the tutorial package, create a new class file and name it HelloWorld.java. Below is the source code for this class file.
package tutorial; import com.opensymphony.xwork2.ActionSupport; public class HelloWorld extends ActionSupport { private static final long serialVersionUID = 1L; private String message; public String execute() { setMessage("Hi there! This is a warm hello from Struts 2"); return SUCCESS; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } } - Notice that above class extends
ActionSupportand it implements theexecute()method. As per Struts 2, any class which does these two things are considered as Struts action classes. - We have our action class is ready. Now it’s the time to create the presentation page, i.e JSP. Create a new JSP file HelloWorld.jsp inside the WebContent folder and type in below code in this JSP file.
<%@ page contentType="text/html; charset=UTF-8" %> <%@ taglib prefix="s" uri="/struts-tags" %> <html> <head> <title>Struts 2 - Hello World tutorial</title> </head> <body> <h2><s:property value="message"/></h2> If you can see above message, Congrats! You have successfully created your first Struts 2 application. </body> </html>
- Now we will create the very important struts.xml file which glues our action class with the presentation JSP file. Since Struts 2 requires struts.xml to be present in classes folder, we will create stuts.xml file inside the source folder, so that when building the WAR file, struts.xml will be put in classes folder. Below is the code for struts.xml file.
<?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="false" /> <package name="tutorial" namespace="/" extends="struts-default"> <action name="HelloWorld" class="tutorial.HelloWorld"> <result>/HelloWorld.jsp</result> </action> </package> </struts>
- Now we are good to go. Right click on the project name and click Export ? WAR File. Then deploy this WAR in the Tomcat’s webapps directory. Now start Tomcat server and point your browser to the URL http://localhost:8080/HelloWorld/HelloWorld.action and Tada! Your first struts 2 application is delivering the JSP page with a hello message to you!!
So, that’s it. Now the Hello World application is done using this latest Struts framework.
{ 48 comments }
Excellent starting point buddy. You are right, existing examples are pretty confusing. Your article is simple, precise. Thanks
Thanks Amit!
Thanks a lot!!!!!!!!!!!!!!!
was very useful…………..
You are welcome, Priya!
Thanks Veerasundar. This was very helpful
///Thanks Veerasundar. This was very helpful//
Thanks Neena!
I tried this Sample code in following Config.
Eclipse, tomcat 5.0, jre 1.5
I deployed this sample application WAR file into tomcat.
I have tried to launch this by typing its url as
http://localhost:8080/HelloWorld
but it was showing Error as below -
type Status report
message /HelloWorld/WEB-INF/web.xml
description The requested resource (/HelloWorld/WEB-INF/web.xml) is not available.
Hi Atul,
The error you got is possibly because of (as the error message says) the web.xml may not be present in the WAR file that you had deployed. Can you please check your WAR file to see whether the web.xml present inside the WEB-INF folder?
Yes this war files contents web.xml.
i tried this example 3 – 4 time from scratch.
but each time i get same error.
Actually i put struts.xml file into WEB-INF folder.
but i seen in some example it is with scr files.
after that i tried this also but i get an error :-
resource is not available.
wht should i do.
i think some libraries are required in tomcat to read and convert these xml files.
Thanks Veer, I am able to run my fist struts 2 application. That was an excellent starting point.
Atul,
Open the Manager console in Apache Tomcat server and see the status of the struts application. If it is false, then the web application is not deployed correctly and some problem with the application WAR itself. If it is the error with any Java files, then the IDE would have shown at the compilation time itself, but if there is any error with web.xml or struts.xml, then IDE won’t show any errors, but application won’t be deployed in Tomcat. Please check if there is any syntax error with xml files.
Hi Mahesh,
Thanks for your feedback.
Hi Mahesh,
Thanks for your feedback.
thanx man,
thanx man,
i need some help form u. i normally tried ur application
1)i created the HelloWorld folder
in that i created src folder and WEB-INF folder and Helloworld.jsp placed in same folder
and then
2) in WEB-INF folder i placed web.xml and lib and i placed all neccessary jar files.
3) in src folder i placed the HelloWorld.java and struts.xml
i run the appl it showing 404 status error . i am running the appl in tomcat5.5 and i checked the web.xml and struts.xml it shows correctly .where i gettong the probelm i don’t no..
Normally in struts1.1 we placed the strut.xml placed parallel to web.xml . here we have to place in src folder i dont know just i am asking.
in previous u told that checked in tomcat manager i checked there it showing false but i checked all directory twice but it showing error. even i compile i try to compile to java file it shows error ActionSupport .
i hope u understood my probelm. i hoping positive response from u.
Thanks
Lakshman
Hi,
I have tried deploying your application exactly the way you have told but when I run it using Tomcat6.0.I am getting HTTP error saying HelloWorld.action resource not found.I checked struts.xml and web.xml again.It seems to be fine.My folder strusture is exactly the same as u have shown in ur UI view.Could you please tell me what exactly is the problem?Even if I try to just run HelloWrold.jsp it sayd HelloWorld.jsp not available.I’ll be thankful if you could help me.
Arti
Hi Lakshman, Arti
I couldn’t able to figure out the issue from your questions. Anyhow, please check the below points once again, just to make sure that everything is fine.
1. Check the placement of struts.xml. In Sturuts2 its placed inside the “source” folder.
2. Check the action declaration in struts.xml file.
3. Check if the “struts2″ filter and filter mapping defined correctly in “web.xml” file.
As said, I can’t figure out the exact issue just by looking at your questions. So, if possible, can you please send your files to my email id (available in the contact page), so that I can have a look at it and get back to you?
HTTP Status 404 – /HelloWorld/HelloWorld.action
——————————————————————————–
type Status report
message /HelloWorld/HelloWorld.action
description The requested resource (/HelloWorld/HelloWorld.action) is not available.
——————————————————————————–
Apache Tomcat/5.5.17
i am getting this error page. could you please tell me why it is happing so.
Thanks, works good (if you stick to the names…
.
BR,
Hansi
Hi shankar
i posted my application but i didn’t get the Response form u. when the Run the Application in server console i getting the following error .
pr 2, 2009 10:48:54 AM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFO: The Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: E:\Program Files\Java\jre1.5.0_14\bin;.;C:\WINDOWS\system32;C:\WINDOWS;E:\Program Files\Java\jre1.5.0_14\bin\client;E:\Program Files\Java\jre1.5.0_14\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program Files\TortoiseSVN\bin;E:\Program Files\Java\jdk1.5.0_14\bin;.;E:\Program Files\apache-ant-1.7.1\bin;.;
Apr 2, 2009 10:48:54 AM org.apache.coyote.http11.Http11BaseProtocol init
INFO: Initializing Coyote HTTP/1.1 on http-8080
Apr 2, 2009 10:48:54 AM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 672 ms
Apr 2, 2009 10:48:54 AM org.apache.catalina.core.StandardService start
INFO: Starting service Catalina
Apr 2, 2009 10:48:55 AM org.apache.catalina.core.StandardEngine start
INFO: Starting Servlet Engine: Apache Tomcat/5.5.27
Apr 2, 2009 10:48:55 AM org.apache.catalina.core.StandardHost start
INFO: XML validation disabled
Apr 2, 2009 10:48:55 AM org.apache.catalina.core.StandardContext filterStart
SEVERE: Exception starting filter struts2
java.lang.ClassNotFoundException: org.apache.struts2.dispatcher.FilterDispatcher
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1386)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1232)
at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:207)
at org.apache.catalina.core.ApplicationFilterConfig.setFilterDef(ApplicationFilterConfig.java:302)
at org.apache.catalina.core.ApplicationFilterConfig.(ApplicationFilterConfig.java:78)
at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:3635)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4222)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1014)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:736)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1014)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
at org.apache.catalina.core.StandardService.start(StandardService.java:448)
at org.apache.catalina.core.StandardServer.start(StandardServer.java:700)
at org.apache.catalina.startup.Catalina.start(Catalina.java:552)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:295)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:433)
Apr 2, 2009 10:48:55 AM org.apache.catalina.core.StandardContext start
SEVERE: Error filterStart
Apr 2, 2009 10:48:55 AM org.apache.catalina.core.StandardContext start
SEVERE: Context [/HelloWorld1] startup failed due to previous errors
Apr 2, 2009 10:48:55 AM org.apache.coyote.http11.Http11BaseProtocol start
INFO: Starting Coyote HTTP/1.1 on http-8080
Apr 2, 2009 10:48:55 AM org.apache.jk.common.ChannelSocket init
INFO: JK: ajp13 listening on /0.0.0.0:8009
Apr 2, 2009 10:48:55 AM org.apache.jk.server.JkMain start
INFO: Jk running ID=0 time=0/31 config=null
Apr 2, 2009 10:48:55 AM org.apache.catalina.storeconfig.StoreLoader load
INFO: Find registry server-registry.xml at classpath resource
Apr 2, 2009 10:48:55 AM org.apache.catalina.startup.Catalina start
INFO: Server startup in 671 ms
i pasted the server log error to u. Every thing i checked the staging directory it is fine but where it getting error still i didn’t find . if it possible to u check my application , which i already send to u and solve my problem.
Waiting a positive Response from u.
Regards
Lakshman
Hi,
I am not able to deploy my HelloWorld.war into Webapps in Tomcat.It is not showing any error messages.I am new to Struts,please help me!
Thanks,
Prathibha
Hi Lakshman,
Firstly, I am not Shankar. I am Sundar.
Regarding the error you are getting, I just googled for the error message and it look’s like the error message is not a serious one. Please check this thread : http://www.coderanch.com/t/85960/ApacheTomcat/Tomcat-Native-library-not-found
Please follow the names I’ve given in my examples so that the code works fine (Pleas refer Hansi’s comment in the comment section of this blog post!). I was kinda busy with my work these days, didn’t get time to go through your code.
If you need any urgent assistance in Struts 2, try posting your query in forums like JavaRanch or Struts mailing archives
Have a nice day!
Hi Prathibha ,
Got your email. Glad that my tutorial helped you.
Thanks.
I tried a lot of examples but very confusing… and didn’t worked out.
Fortunately, I found this site. Thanks man, nice work. keep it up
i followed ur tutorial.. but when to view in browser. it not appear..
error displayed
”
type Status report
message There is no Action mapped for namespace / and action name HelloWorld.
description The requested resource (There is no Action mapped for namespace / and action name HelloWorld.) is not available.
”
what i need to do??
i used tomcat.. cant to..
i used jboss.. also cant..
7.Now we will create the very important struts.xml file which glues our action class with the presentation JSP file. Since Struts 2 requires struts.xml to be present in classes folder, we will create stuts.xml file inside the source folder, so that when building the WAR file, struts.xml will be put in classes folder.
Actually i need create struts.xml at where folder??
A) HelloWorld -> struts.xml
B) HelloWorld -> JavaResources : source -> tutorial -> struts.xml
C) HelloWorld -> WebContent -> struts.xml
im really confusing… i use eclipse.. but i cant create file in the answer B..
Hi Kvic,
If you look at the directory structure diagram (http://veerasundar.com/blog/wp-content/uploads/2008/11/struts-2-folder-structure.png), you can see that the struts.xml file is placed under the source folder. The point here is struts.xml file should be present in the classpath.
So, to create a XML file in eclipse, in Project explorer view, right click on your project’s source folder and click New -> File and give the file name as “struts.xml”.
I hope this helps.
im so careless.. actually my problem got solution.
should be like this for struts.xml
HelloWorld -> JavaResources : source -> struts.xml
i used jboss.
thanks.. this tutorial.. so easy to follow.. so easy to understand the concept..
thanks alot…
i hope got tutorial for the better practise..
this is the nice one.
but people who are using jboss. you have to add jboss-web.xml, under webinf directory. der u need to add context path. using that u have to trigger d url.
jboss-web.xml
login
url
http://localhost:8080/login/example/Login.action
regards,
karthik.
Thanks for such a nice and quick explanation.
I was just going to copy/paste my error log and then, thought of giving one more try from scratch…..And, this helped me… I am very very new to struts itself.
This tutorial was the best I have ever found. Thanks.
Can you please explain, how can you access property values from JSP?
Thanks a lot.
Thanks for your feedback, Manasvi!
//Can you please explain, how can you access property values from JSP?//
If you want to load a properties file in JSP page, it requires adding a Java code to the JSP file, which is like adding business logic in the presentation layer. But this is not a good practice. So, it is good to load the properties file in your servlet and pass the values to your JSP page.
Have a look at this link on how to smartly load properties file in Java.
I hope this helps.
cheers.
I created the project in the same way as described in the tutorial, but I am not able to see the “message” property set in Action class. And, JSP is displayed perfectly without any errors. Any clues?
Thanks.
Hi Manasvi,
There is a setter method for the ‘message’ property in the ‘HelloWorld’ action class. This is how the message value is passed on to the JSP page.
Ok. Thanks. I got it working now.
Hay.. Thank you for your nice tutorial. Its really east, and I just done it. Hope more tutorials form you…
Enjoy Madi.
hi all:
first I imported latest struts-2.1.6 release jar file. Tomcat cannot deploy my application. after I changed jar file to struts-2.0.14, all worked fine . If your Tomcat cannot deploy your application, try to change your jar files version. This may help..
thanks this tutorial.
kind regards:
Jim
I had the same issue as many here: The resource xxx was not available.
I looked into the Tomcat’s log and found that the origin of the problem was:
Caused by: java.lang.ClassNotFoundException: org.apache.commons.fileupload.FileUploadException
So, I copyied the commons-fileupload-1.2.1.jar file found in the struts-2.1.6.zip (under the lib directory) to the proyects WEB-INF/lib and it worked.
Hope that helps anyone!
hi atul m getting the same error as you got. can you or any one else help me out.
thanx in advance
Hi,
I was able to successfully read the message when I accessed http://localhost:8080:HelloWorld/HelloWorld.jsp
and not http://localhost:8080/HelloWorld/HelloWorld.action. The latter throws up an error.
Anyone care to point out the difference ?
Thanks
Just a heads up here….at first I couldn’t get this to work because I had struts 2.1.x as my struts package.
Make sure you are using some variant of 2.0.x
Best wishes…
To people who had a problem with missing resource, the problem could also be that you have additional jars in your lib folder (like struts1-core.jar). So make sure that only struts2 jars are present.
Great tutorial!
HI
im trying to run the above program, but it is not working properly. can any one solve my problem
hi,
can you give us more details on the error that your are getting?
Hiii, m getting the following message
HTTP Status 404 – /HelloWorld/
——————————————————————————–
type Status report
message /HelloWorld/
description The requested resource (/HelloWorld/) is not available.
——————————————————————————–
Apache Tomcat/5.0.28
Hi VS. Nice tutorial. I am getting this error. :
HTTP Status 500 –
——————————————————————————–
type Exception report
message
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: org.apache.jasper.JasperException: Unsupported encoding: UTF-8
org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:515)
org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:422)
root cause
org.apache.jasper.JasperException: Unsupported encoding: UTF-8
org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:51)
org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:409)
org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:116)
org.apache.jasper.compiler.JspUtil.getReader(JspUtil.java:1091)
org.apache.jasper.compiler.ParserController.doParse(ParserController.java:250)
org.apache.jasper.compiler.ParserController.parseDirectives(ParserController.java:120)
org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:165)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:332)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:312)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:299)
org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:586)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:317)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:342)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:267)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
Hi Digant,
Which server are you using? Is it Tomcat?
Yes Veera, I am using tomcat 6
Comments on this entry are closed.