Struts Hello World Example

In this tutorial we show you how to develop a hello world web application using classic Struts 1.3 framework.

Tools and technologies used :

  1. Struts 1.3.10
  2. Maven 2.x
  3. Eclipse 3.6

Final project structure

Let’s see the final folder structure first.

Struts-Hello-World-Maven

1. Maven Template

Generate a quick start Java project structure with Maven command “mvn archetype:generate“, select template 18 for a simple Java web project template.


Define value for groupId: : com.mkyong.common
Define value for artifactId: : StrutsExample
Define value for version:  1.0-SNAPSHOT: :
Define value for package:  com.mkyong.common: : com.mkyong.common
...
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1 minute 5 seconds
[INFO] Finished at: Thu Apr 08 11:29:30 SGT 2010
[INFO] Final Memory: 8M/14M
[INFO] ------------------------------------------------------------------------

2. pom.xml file configuration

Add the Struts dependencies in pom.xml. In Struts 1.x, you need the struts-core.jar for core module and struts-taglib.jar for tag library.


<project xmlns="http://maven.apache.org/POM/4.0.0" 
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
  http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.mkyong.common</groupId>
  <artifactId>StrutsExample</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>StrutsExample Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    
    <dependency>
      <groupId>org.apache.struts</groupId>
	  <artifactId>struts-core</artifactId>
      <version>1.3.10</version>
    </dependency>
    
    <dependency>
      <groupId>org.apache.struts</groupId>
	  <artifactId>struts-taglib</artifactId>
      <version>1.3.10</version>
    </dependency>
   
  </dependencies>
  <build>
    <finalName>StrutsExample</finalName>
  </build>
</project>

3. Eclipse IDE

Convert this project to Eclipse web project with Maven command “mvn eclipse:eclipse -Dwtpversion=1.5“. All the Struts dependent libraries will automatically download into your Maven local repository, link it in your project classpath, and convert it to Eclipse’s web project style.


E:\workspace\struts\StrutsExample>mvn eclipse:eclipse -Dwtpversion=1.5
[INFO] Scanning for projects...
[INFO] Searching repository for plugin with prefix: 'eclipse'.
[INFO] ------------------------------------------------------------------------
[INFO] Building StrutsExample Maven Webapp

Just import it into Eclipse IDE.

4. Action Form

Create a Struts Action Form to hold the “hello world” data later.


package com.mkyong.common.form;

import org.apache.struts.action.ActionForm;

public class HelloWorldForm extends ActionForm{
	
	String message;

	public String getMessage() {
		return message;
	}

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

5. Action (Controller)

Create a Struts Action (Action Controller) file to control how Struts will forward the request, just override the execute() method with your own logic here.


package com.mkyong.common.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.mkyong.common.form.HelloWorldForm;

public class HelloWorldAction extends Action{
	
	public ActionForward execute(ActionMapping mapping,ActionForm form,
		HttpServletRequest request,HttpServletResponse response)
        throws Exception {
		
		HelloWorldForm helloWorldForm = (HelloWorldForm) form;
		helloWorldForm.setMessage("Hello World! Struts");
		
		return mapping.findForward("success");
	}
	
}

6. JSP view page

Create a JSP page and access the Action Form object via Struts tag library and print it’s message property.

<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>




%MINIFYHTML6152a33ce0564487a2abfc2fc844a8b73%

7. struts-config.xml

Create a struts-config.xml file for the Struts configuration details, and put it into the WEB-INF folder.


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

<struts-config>

	<form-beans>
	   <form-bean name="helloWorldForm" 
		type="com.mkyong.common.form.HelloWorldForm"/>
	</form-beans>

	<action-mappings>
	   <action path="/helloWorld"
		type="com.mkyong.common.action.HelloWorldAction"
		name="helloWorldForm">
		<forward name="success" path="/HelloWorld.jsp"/>
			
	   </action>
	</action-mappings>

</struts-config>

Define a form bean named “helloWorldForm” and action controller mapping “HelloWorldAction“, match the /helloWorld web path to HelloWorldAction. It’s means all the request from /helloWorld web path will redirect to HelloWorldAction. The “name” attribute is use to define which action form will pass to this HelloWorldAction.

8. The Web Application Deployment Descriptor

In web.xml file, configure the Struts ActionServlet instance and map it with url-pattern “*.do”, so that the container is aware of all the “*.do” pattern will redirect to Struts ActionServlet.


<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Maven Struts Examples</display-name>
  
  <servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>
        org.apache.struts.action.ActionServlet
    </servlet-class>
    <init-param>
        <param-name>config</param-name>
        <param-value>
         /WEB-INF/struts-config.xml
        </param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
    
  <servlet-mapping>
       <servlet-name>action</servlet-name>
       <url-pattern>*.do</url-pattern>
  </servlet-mapping>

</web-app>

9. Java EE Module dependency (Optional)

If you want to do the debugging work in Eclipse IDE, you have to make sure the Java EE module dependencies is checked so that the Eclipse will deploy all the dependencies into correct folder. See details here.

10. Run it

In Eclipse IDE, create a new server plugin and start it. You can access this example in the following URL.

http://localhost:8080/StrutsExample/helloWorld.do

Struts-Hello-World-Maven2
HttpServletRequest class not found?
If you hit above error, make sure you include the javaee.jar (exists in your JDK/lib folder). Due to license issue, this javaee.jar is not able to use Maven to download it, you have to include it manually.

Download

Reference

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
34 Comment threads
14 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
37 Comment authors
Jorge AlfonsoBobVijay Sai KumarAnonymousWayne Kenneth Seymour III Recent comment authors
newest oldest most voted
Ogi
Guest
Ogi

i think you need to add the following dependency in the pom.xml

<dependency>
	<groupId>javax.servlet</groupId>
	<artifactId>servlet-api</artifactId>
	<version>2.3</version>
	<scope>provided</scope>
</dependency>
erkan
Guest
erkan

your sample is doesnt work 🙁

trackback
Criando um MĂłdulo Personalizado no JBoss AS 7.1.2 (JBoss EAP 6) | JBossDivers
Luciano Straga
Guest
Luciano Straga

I’m new in Struts, I’m getting every time a 404 error, after following all the steps described. I deployed successfully the war file with maven, it’s apparentliy running in tomcat’s mannager; but I get the 404. I reviewed all the paths of the files, to discard path mistakes but i couldn’t find the solution.

Thanks for all, mkyong

goods
Guest
goods

My husband and i got really excited when Michael could finish off his homework via the ideas he made out of the blog. It is now and again perplexing to just possibly be giving out information and facts which usually many people could have been selling. And we already know we now have the website owner to be grateful to for this. The entire explanations you have made, the straightforward site menu, the friendships your site assist to instill – it’s many remarkable, and it is helping our son and us consider that the article is interesting, and that is… Read more »

Peter Tarlos
Guest
Peter Tarlos

If you’re getting error:

Stacktrace:] with root cause
javax.servlet.jsp.JspException: Cannot find bean: ?helloWorldForm? in any scope
at org.apache.struts.taglib.TagUtils.lookup(TagUtils.java:934)

Remember to call the URL below, as instructed by the article, and not the “HelloWorld.jsp” directly. If you call the jsp directly it will not work because the struts action hasn’t set the form yet.
http://localhost:8080/StrutsExample/helloWorld.do

Isuru Chathuranga
Guest
Isuru Chathuranga

Hi Yong,
First of all I admire your works. I have got error of

HTTP Status 500 – java.lang.NullPointerException

exception

javax.servlet.ServletException: java.lang.NullPointerException
org.apache.struts.chain.ComposableRequestProcessor.process(ComposableRequestProcessor.java:286)
org.apache.struts.action.ActionServlet.process(ActionServlet.java:1913)
org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:449)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)

root cause

java.lang.NullPointerException
org.apache.struts.config.FormBeanConfig.createActionForm(FormBeanConfig.java:289)
org.apache.struts.config.FormBeanConfig.createActionForm(FormBeanConfig.java:357)
org.apache.struts.chain.commands.CreateActionForm.execute(CreateActionForm.java:92)
org.apache.struts.chain.commands.ActionCommandBase.execute(ActionCommandBase.java:51)
org.apache.commons.chain.impl.ChainBase.execute(ChainBase.java:191)
org.apache.commons.chain.generic.LookupCommand.execute(LookupCommand.java:305)
org.apache.commons.chain.impl.ChainBase.execute(ChainBase.java:191)
org.apache.struts.chain.ComposableRequestProcessor.process(ComposableRequestProcessor.java:283)
org.apache.struts.action.ActionServlet.process(ActionServlet.java:1913)
org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:449)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)

note The full stack trace of the root cause is available in the VMware vFabric tc Runtime 2.8.2.RELEASE/7.0.35.B.RELEASE logs.

So I have no idea abut that please help me. Thank you…

jjmkay
Guest
jjmkay

This example download badly needs to be re-factored and configured as a proper maven project.

Rahul Raja
Guest
Rahul Raja

This example works perfectly and I am able to find the flow of the code once I installed tomcat.. Thank you

Ankush yadav
Guest
Ankush yadav

Hi mkyong, i am following you since 4 year. this is the first example where i found something missing. it work in good way even run by mavne. but it show nothing on browser at first time, than i put some hard code in jsp page it those hard code value, than from other site i put the sample code for showing massages on jsp page and it work thanks. than i realize that your point number 6 about jsp page show only first line only. this much code only, i think it issue with my browser, can you check… Read more »

Camilo Uribe
Guest
Camilo Uribe

Archetype 18:
18: remote -> br.gov.frameworkdemoiselle.archetypes:demoiselle-jsf-jpa (-)

trackback
Struts Tutorials | Tutorials

[…] Struts hello world example Go thought a hello world example to understand how Struts MVC work. […]

Lijun
Guest
Lijun

It is un problem with:
org.apache.struts.chain.commands.InvalidPathException: No action config found for the specified url.
at org.apache.struts.chain.commands.AbstractSelectAction.execute(AbstractSelectAction.java:71)
at org.apache.struts.chain.commands.ActionCommandBase.execute(ActionCommandBase.java:51)
at org.apache.commons.chain.impl.ChainBase.execute(ChainBase.java:191)
at org.apache.commons.chain.generic.LookupCommand.execute(LookupCommand.java:305)
at org.apache.commons.chain.impl.ChainBase.execute(ChainBase.java:191)
at org.apache.struts.chain.ComposableRequestProcessor.process(ComposableRequestProcessor.java:283)
at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1913)
at org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:449)

dhruv
Guest
dhruv

Really i love this website . from where we can learn lot of concepts of java and lastly i want to say this website is my carrier. thank you

trackback
Google App Engine + Struts 1 example

[…] You may also interest at this Google App Engine + Struts 2 example.This example is going to merge Struts 1.x hello world example with this GAE + Java example.1. New Web Application ProjectIn Eclipse, create a new Web Application […]

Vinayak
Guest
Vinayak

Hi I am new to struts & done with maven setup. if I will go to bin folder of maven & check version from command prompt, I get details of maven. when I try to enter details with mvn command- archetype:generate & enter all as below

groupId: : com.mkyong.common
Define value for artifactId: : StrutsExample
Define value for version: 1.0-SNAPSHOT: :
Define value for package: com.mkyong.common: : com.mkyong.common

it do not accept any value. Please suggest me..how run this program…if first program will be done….I would be able to do rest all.

Vinayak
Guest
Vinayak

Done with all steps. build is successful. Tomcat is configured. HTTP 404 -/StrutsExmaples/helloWorld.do
Please help.

rijesh
Guest
rijesh

Hii
While running above program i got error as like this,please help me….

SEVERE: Servlet /Strut threw load() exception
java.lang.ClassNotFoundException: org.apache.struts.action.ActionServlet
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1711)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1556)
at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:532)
at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:514)
at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:133)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1136)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1080)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5027)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5314)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)

trackback
????????????? ????? » Blog Archive » ???????? ? «HelloWorld» ??????????? ?? Struts2
lonia
Guest
lonia

I download the zip and I try to run it but I have this error.

Stacktrace:] with root cause
javax.servlet.jsp.JspException: Cannot find bean: “helloWorldForm” in any scope
at org.apache.struts.taglib.TagUtils.lookup(TagUtils.java:864)
at org.apache.struts.taglib.bean.WriteTag.doStartTag(WriteTag.java:233)
at org.apache.jsp.pages.HelloWorld_jsp._jspx_meth_bean_005fwrite_005f0(HelloWorld_jsp.java:106)
at org.apache.jsp.pages.HelloWorld_jsp._jspService(HelloWorld_jsp.java:76)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:999)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:565)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:307)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)

Can you help me please!

Milan
Guest
Milan

e learning from this website will surely improve struts skills.

Ian
Guest
Ian

btw here is the link where the error happens http://sample.com/goalsunlimited/systemLogin.do Here are the configs: ******* web.xml ******* goalsunlimited action org.apache.struts.action.ActionServlet config /WEB-INF/struts-config.xml debug 2 detail 2 2 action *.do login.jsp 60 /WEB-INF/struts-bean.tld /WEB-INF/struts-bean.tld /WEB-INF/struts-html.tld /WEB-INF/struts-html.tld /WEB-INF/struts-logic.tld /WEB-INF/struts-logic.tld /WEB-INF/struts-nested.tld /WEB-INF/struts-nested.tld /WEB-INF/struts-tiles.tld /WEB-INF/struts-tiles.tld java.lang.Exception /error.jsp javax.servlet.jsp.jstl.fmt.localizationContext MessageResources ***************** struts-config.xml ***************** ********** spring.xml ********** classpath:com/mlm/dao/SqlMapConfig.xml true

kas5986
Guest
kas5986

I have tried it creating new and also try to work download your sample and go to the url but it say page not found i have donwload javaee.jar and place it to JDK/lib folder also in tomcat lib but it still say page not found with both mine and your sample too can you tell me where i am wrong ?

ekansh
Guest
ekansh

you can also try this example –this is much simple

http://www.ekjam.com/pages/tutorials/struts/helloWorld.jsp

kannan smart
Guest
kannan smart

Mr. mkyoung,

I am beginner of struts framework. please help, how to add maven artifacts and plugin jar to maven repository because i got missing jar files in maven repository. any one pls help me……..

Missing Libraries:

1.M2_REPO/antlr/antlr/2.7.2/antlr-2.7.2.jar
2.M2_REPO/commons-beanutils/commons-beanutils/1.8.0/commons-beanutils-1.8.0.jar
3.M2_REPO/commons-chain/commons-chain/1.2/commons-chain-1.2.jar
4.M2_REPO/commons-digester/commons-digester/1.8/commons-digester-1.8.jar
5.M2_REPO/commons-logging/commons-logging/1.0.4/commons-logging-1.0.4.jar
6.M2_REPO/commons-validator/commons-validator/1.3.1/commons-validator-1.3.1.jar
7.M2_REPO/junit/junit/3.8.1/junit-3.8.1.jar
8.M2_REPO/org/apache/struts/struts-core/1.3.10/struts-core-1.3.10.jar
9.M2_REPO/org/apache/struts/struts-taglib/1.3.10/struts-taglib-1.3.10.jar
10.M2_REPO/oro/oro/2.0.8/oro-2.0.8.jar

Thanks Advance.

awgtek
Guest
awgtek

For Maven, choose 19 now. and must do >mvn archetype:generate -DarchetypeCatalog=internal

SharkCode
Guest
SharkCode

Dear Mr.Yong,

After downloading & running the attached project, I found the below error:

descriptionThe server encountered an internal error that prevented it from fulfilling this request.

exception

javax.servlet.ServletException: javax.servlet.jsp.JspException: Cannot find bean: “helloWorldForm” in any scope

root cause

javax.servlet.jsp.JspException: Cannot find bean: “helloWorldForm” in any scope

could you please support?

Hardik Patel
Guest
Hardik Patel

config

/WEB-INF/struts-config.xml

I can’t getting above…please help.

Hardik Patel
Guest
Hardik Patel

i can’t getting this.

<init-param>
        <param-name>config</param-name>
        <param-value>
         /WEB-INF/struts-config.xml
        </param-value>
   </init-param>
Hardik Patel
Guest
Hardik Patel

i can’t getting this.

config

/WEB-INF/struts-config.xml