Tutorial: Create Struts 2 Application in Eclipse

struts2-hello-world
Welcome to the Part 2 of 7-part series where we will explore the world of Struts 2 Framework. In previous article we went through the basics of Struts2, its Architecture diagram, the request processing lifecycle and a brief comparison of Struts1 and Struts2. If you have not gone through the previous article, I highly recommend you to do that before starting hands-on today.

Things We Need

Before we starts with our first Hello World Struts 2 Example, we will need few tools.

  1. JDK 1.5 above (download)
  2. Tomcat 5.x above or any other container (Glassfish, JBoss, Websphere, Weblogic etc) (download)
  3. Eclipse 3.2.x above (download)
  4. Apache Struts2 JAR files:(download). Following are the list of JAR files required for this application.
    • commons-logging-1.0.4.jar
    • freemarker-2.3.8.jar
    • ognl-2.6.11.jar
    • struts2-core-2.0.12.jar
    • xwork-2.0.6.jar

    Note that depending on the current version of Struts2, the version number of above jar files may change.

Our Goal

Our goal is to create a basic Struts2 application with a Login page. User will enter login credential and if authenticated successfully she will be redirected to a Welcome page which will display message ” Howdy, <username>…!“. If user is not authenticated, she will be redirected back to the login page.
struts2-application-login-page

Getting Started

Let us start with our first Struts2 based application.
Open Eclipse and goto File -> New -> Project and select Dynamic Web Project in the New Project wizard screen.
Dynamic Web Project in Eclipse

After selecting Dynamic Web Project, press Next.
Eclipse Struts2 Project

Write the name of the project. For example StrutsHelloWorld. Once this is done, select the target runtime environment (e.g. Apache Tomcat v6.0). This is to run the project inside Eclipse environment. After this press Finish.

Once the project is created, you can see its structure in Project Explorer.
Eclipse Project Explorer: Struts2 Example

Now copy all the required JAR files in WebContent -> WEB-INF -> lib folder. Create this folder if it does not exists.
struts2-webinf-jars

Mapping Struts2 in WEB.xml

As discussed in the previous article (Introduction to Struts2), the entry point of Struts2 application will be the Filter define in deployment descriptor (web.xml). Hence we will define an entry of org.apache.struts2.dispatcher.FilterDispatcher class in web.xml.

Open web.xml file which is under WEB-INF folder and copy paste following code.

<?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>Struts2 Application</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>
	<welcome-file-list>
		<welcome-file>Login.jsp</welcome-file>
	</welcome-file-list>

</web-app>

The above code in web.xml will map Struts2 filter with url /*. The default url mapping for struts2 application will be /*.action. Also note that we have define Login.jsp as welcome file.

Note: The FilterDispatcher filter is deprecated since Struts version 2.1.3. If you are using latest version of Struts2 ( > 2.1.3) use StrutsPrepareAndExecuteFilter class instead.

<filter>
	<filter-name>struts2</filter-name>
	<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
	<filter-name>struts2</filter-name>
	<url-pattern>/*</url-pattern>
</filter-mapping>

The Action Class

We will need an Action class that will authenticate our user and holds the value for username and password. For this we will create a package net.viralpatel.struts2 in the source folder. This package will contain the action file.
struts2-source-package
Create a class called LoginAction in net.viralpatel.struts2 package with following content.

package net.viralpatel.struts2;

public class LoginAction {
	private String username;
	private String password;

	public String execute() {

		if (this.username.equals("admin") 
				&& this.password.equals("admin123")) {
			return "success";
		} else {
			return "error";
		}
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
}

Note that, above action class contains two fields, username and password which will hold the values from form and also contains an execute() method that will authenticate the user. In this simple example, we are checking if username is admin and password is admin123.

Also note that unlike Action class in Struts1, Struts2 action class is a simple POJO class with required attributes and method.

The execute() method returns a String value which will determine the result page. Also, in Struts2 the name of the method is not fixed. In this example we have define method execute(). You may want to define a method authenticate() instead.

The ResourceBundle

ResourceBundle is very useful Java entity that helps in putting the static content away from the source file. Most of the application define a resource bundle file such as ApplicationResources.properties file which contains static messages such as Username or Password and include this with the application.

ResourceBundle comes handy when we want to add Internationalization (I18N) support to an application.

We will define an ApplicationResources.properties file for our application. This property file should be present in WEB-INF/classes folders when the source is compiled. Thus we will create a source folder called resources and put the ApplicationResources.properties file in it.

To create a source folder, right click on your project in Project Explorer and select New -> Source Folder.
struts2-resource-folder
Specify folder name resources and press Finish.

Create a file ApplicationResources.properties under resources folder.
struts-2-application-resources-properties
Copy following content in ApplicationResources.properties.

label.username= Username
label.password= Password
label.login= Login

The JSP

We will create two JSP files to render the output to user. Login.jsp will be the starting point of our application which will contain a simple login form with username and password. On successful authentication, user will be redirected to Welcome.jsp which will display a simple welcome message.

Create two JSP files Login.jsp and Welcome.jsp in WebContent folder of your project. Copy following content into it.

Login.jsp

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Struts 2 - Login Application | ViralPatel.net</title>
</head>

<body>
<h2>Struts 2 - Login Application</h2>
<s:actionerror />
<s:form action="login.action" method="post">
	<s:textfield name="username" key="label.username" size="20" />
	<s:password name="password" key="label.password" size="20" />
	<s:submit method="execute" key="label.login" align="center" />
</s:form>
</body>
</html>

Welcome.jsp

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Welcome</title>
</head>

<body>
	<h2>Howdy, <s:property value="username" />...!</h2>
</body>
</html>

Note that we have used struts2 <s:> tag to render the textboxes and labels. Struts2 comes with a powerful built-in tag library to render UI elements more efficiently.

The struts.xml file

Struts2 reads the configuration and class definition from an xml file called struts.xml. This file is loaded from the classpath of the project. We will define struts.xml file in the resources folder. Create file struts.xml in resources folder.
struts2-struts-xml
Copy following content into 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>
	<constant name="struts.enable.DynamicMethodInvocation"
		value="false" />
	<constant name="struts.devMode" value="false" />
	<constant name="struts.custom.i18n.resources"
		value="ApplicationResources" />

	<package name="default" extends="struts-default" namespace="/">
		<action name="login"
			class="net.viralpatel.struts2.LoginAction">
			<result name="success">Welcome.jsp</result>
			<result name="error">Login.jsp</result>
		</action>
	</package>
</struts>

Note that in above configuration file, we have defined Login action of our application. Two result paths are mapped with LoginAction depending on the outcome of execute() method. If execute() method returns success, user will be redirected to Welcome.jsp else to Login.jsp.

Also note that a constant is specified with name struts.custom.i18n.resources. This constant specify the resource bundle file that we created in above steps. We just have to specify name of resource bundle file without extension (ApplicationResources without .properties).

Our LoginAction contains the method execute() which is the default method getting called by Sturts2. If the name of method is different, e.g. authenticate(); then we should specify the method name in <action> tag.

	<action name="login" method="authenticate"
		class="net.viralpatel.struts2.LoginAction">

Almost Done

We are almost done with the application. You may want to run the application now and see the result yourself. I assume you have already configured Tomcat in eclipse. All you need to do:
Open Server view from Windows -> Show View -> Server. Right click in this view and select New -> Server and add your server details.
To run the project, right click on Project name from Project Explorer and select Run as -> Run on Server (Shortcut: Alt+Shift+X, R)

But there is one small problem. Our application runs perfectly fine at this point. But when user enters wrong credential, she is redirected to Login page. But no error message is displayed. User does not know what just happened. A good application always show proper error messages to user. So we must display an error message Invalid Username/Password. Please try again when user authentication is failed.

Final Touch

To add this functionality first we will add the error message in our ResourceBundle file.
Open ApplicationResources.properties and add an entry for error.login in it. The final ApplicationResources.properties will look like:

label.username= Username
label.password= Password
label.login= Login
error.login= Invalid Username/Password. Please try again.

Also we need to add logic in LoginAction to add error message if user is not authenticated. But there is one problem. Our error message is specified in ApplicationResources.properties file. We must specify key error.login in LoginAction and the message should be displayed on JSP page.

For this we must implement com.opensymphony.xwork2.TextProvider interface which provides method getText(). This method returns String value from resource bundle file. We just have to pass the key value as argument to getText() method. The TextProvider interface defines several method that we must implement in order to get hold on getText() method. But we don’t want to spoil our code by adding all those methods which we do not intend to use. There is a good way of dealing with this problem.

Struts2 comes with a very useful class com.opensymphony.xwork2.ActionSupport. We just have to extend our LoginAction class with this class and directly use methods such as getText(), addActionErrors() etc. Thus we will extend the LoginAction class with ActionSupport class and add the logic for error reporting into it. The final code in LoginAction must look like:

package net.viralpatel.struts2;

import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport {
	private String username;
	private String password;

	public String execute() {

		if (this.username.equals("admin") 
				&& this.password.equals("admin123")) {
			return "success";
		} else {
			addActionError(getText("error.login"));
			return "error";
		}
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
}

And that’s it. Our first Hello World Struts2 Application is now ready.

That’s All Folks

Execute the application in Eclipse and run it in your favorite browser.
Login page
struts2-application-login-page

Welcome page
struts2-welcome-page

Login page with error
struts2-login-page-error

Download Source Code

Source Code without JAR files (9 KB)
Source Code with JAR files (3 MB)

Moving On

Now that we have created our first webapp using Struts2 framework, we know how the request flows in Struts2. We also know the use of struts.xml and properties file. In this application we implemented a preliminary form of validation. In next part we will learn more about Validation Framework in Struts2 and implement it in our example.

If you read this far, you should follow me on twitter here.



348 Comments

  • Naresh 6 June, 2013, 11:22

    Getting exception…

    HTTP Status 500 –
    ——————————————————————————–
    type Exception report

    message

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

    exception

    java.lang.NullPointerException
    org.apache.struts2.impl.StrutsActionProxy.getErrorMessage(StrutsActionProxy.java:69)
    com.opensymphony.xwork2.DefaultActionProxy.prepare(DefaultActionProxy.java:185)
    org.apache.struts2.impl.StrutsActionProxy.prepare(StrutsActionProxy.java:63)
    org.apache.struts2.impl.StrutsActionProxyFactory.createActionProxy(StrutsActionProxyFactory.java:39)
    com.opensymphony.xwork2.DefaultActionProxyFactory.createActionProxy(DefaultActionProxyFactory.java:58)
    org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:500)
    org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:434)

    note The full stack trace of the root cause is available in the Apache Tomcat/7.0.35 logs.

    ——————————————————————————–

    Apache Tomcat/7.0.35

    Can any one discuss about this …..!

    • MOHAN 12 June, 2013, 15:05

      HI naresh, Even i am also getting same error all of sudden.. i have been working on my application since 2 years. And now all of sudden when i am trying to write a code likr this …

      setShowRecords(getText(“label.ah.button.show”));

      action class error… like null pointer exception…. can not resolve getText()…………………..

      i dont know why…… instead of doing in action class i am writing a small code in jsp…. in jsp i am loading my property class and usaing that value…

    • aparna 28 June, 2013, 1:18

      looks like you have some mapping issue please check you struts.xml and jsp once again.

    • David 26 October, 2013, 19:09

      I’ve got exactly the same problem. Did you find any fixes ?

  • Soumi 23 June, 2013, 2:08

    Thanks.. It’s really helpful for beginners.. :) I followed your tutorial and my login application is up and running.. :) Definitely a happy beginning.. Will ask you if I need any help in the further functionaries I am adding in the app..
    Thanks and Regards,
    Soumi B

  • aparna 28 June, 2013, 1:17

    Thank you so much for your time and effor for putting up the steps and code for struts2 login application, As a beginner i tried it and i have mu working login application up!!, it brings my intrest and boost me up to practice more…

    Thank you a tone.
    Aparna

  • Suman Kumar Dey 1 July, 2013, 16:10

    Every time I have to face this problem for this particular example,which is stated above.I am a beginner to sturts,please help me to sort out this problem.

    HTTP Status 404 – /Sturts2SumanExample/Login.jsp

    my application name is Sturts2SumanExample nd login.jsp is the 1st page..all others are as same as the example

  • Milan 3 July, 2013, 15:52

    I’m new in JEE.I follow the steps in the tuotrial. I was using weblogic server .
    jars using:
    -commons-logging-1.1.3
    -freemarker-2.3.8
    -orgnl-2-6.11
    -struts2-core-2.3.15
    -xwork-2.o.6

    But is not working,this error:
    java.lang.NoClassDefFoundError: org/apache/struts2/dispatcher/Dispatcher
    at org.apache.struts2.views.jsp.TagUtils.getStack(TagUtils.java:58)
    at org.apache.struts2.views.jsp.StrutsBodyTagSupport.getStack(StrutsBodyTagSupport.java:44)
    at org.apache.struts2.views.jsp.ComponentTagSupport.doStartTag(ComponentTagSupport.java:48)
    at jsp_servlet.__login._jsp__tag0(__login.java:114)
    at jsp_servlet.__login._jspService(__login.java:83)
    at weblogic.servlet.jsp.JspBase.service(JspBase.java:35)
    at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:227)
    at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:125)
    at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:292)
    at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:176)
    at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3495)
    at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
    at weblogic.security.service.SecurityManager.runAs(Unknown Source)
    at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2180)
    at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2086)
    at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1406)
    at weblogic.work.ExecuteThread.execute(ExecuteThread.java:201)
    at weblogic.work.ExecuteThread.run(ExecuteThread.java:173)

    Can anyone help me

  • Rishi Kumar 4 July, 2013, 19:33

    Thank You very much, this was really a nice tutorial for beginner on struts 2, i was stuck from 3
    day to find some good tutorial and it really helped , thanks again

  • Shashi Ranjan 9 July, 2013, 15:24

    Needfull Jars

    asm-3.3.jar
    asm-commons-3.3.jar
    asm-tree-3.3.jar
    commons-fileupload-1.3.jar
    commons-io-2.0.1.jar
    commons-lang3-3.1.jar
    commons-logging-1.1.3.jar
    freemarker-2.3.19.jar
    javassist-3.11.0.GA.jar
    log4j-1.2.17.jar
    ognl-3.0.6.jar
    struts2-core-2.3.15.jar
    xwork-core-2.3.15.jar

  • ST 9 July, 2013, 18:29

    I am trying to get this example “Create Hello World in Struts 2″ using RAD 8 / Websphere 8. I get an error ” Could not find a valid parent module to add to the server”. Googling didn’t throw out any pointers. Any ideas? Thanks.

    • Tom Li 10 April, 2014, 10:14

      u cannot run on server without creating ear module when create web project

  • amar 12 July, 2013, 13:41

    hi,actully when i runing my login page…it doest go on welcome page…and also not make a classes folder into a web content….so pls give me solution

  • buchireddy 25 July, 2013, 13:12

    those jars nor sufficent try
    these jars it will work….

    asm-3.3.jar
    asm-commons-3.3.jar
    asm-tree-3.3.jar
    commons-fileupload-1.3.jar
    commons-io-2.0.1.jar
    commons-lang3-3.1.jar
    commons-logging-1.1.3.jar
    freemarker-2.3.19.jar
    javassist-3.11.0.GA.jar
    log4j-1.2.17.jar
    ognl-3.0.6.jar
    struts2-core-2.3.15.jar
    xwork-core-2.3.15.jar

    but i am geting warning
    WARNING: No configuration found for the specified action: ‘login.action’ in namespace: ‘/’. Form action defaulting to ‘action’ attribute’s literal value.
    Jul 25, 2013 1:08:36 PM org.apache.struts2.components.ServletUrlRenderer warn
    WARNING: No configuration found for the specified action: ‘login.action’ in namespace: ‘/’. Form action defaulting to ‘action’ attribute’s literal value.

    please replay

  • priyanshu gupta 29 July, 2013, 12:31

    sir I have a problem of installing struts2 pluging in eclipse
    so kindly suggest me proper way of instaling plugin of struts 2

  • Ramachandran 8 August, 2013, 12:52

    Thank you very much, This tutorial very useful for me thank you

  • thennarasu 12 August, 2013, 12:44

    if i do the application without internet connection eclipse is not recognizing the DTD(http://struts.apache.org/dtds/struts-2.1.7.dtd) in struts.xml file please help…

  • prashant 12 August, 2013, 17:22

    Nice tutorial. I understood lots!!!
    Thanks!!

  • Raghu 24 August, 2013, 9:51

    Hi,

    i try to do as per the above said, but i had a problem error undefined method getText(), even i have import that particular package. i tried even without that line it seems like a error “the requested resource not available Login.jsp”

  • Fayaaz 8 September, 2013, 17:22

    Im getting this error…
    Sep 08, 2013 5:20:59 PM org.apache.catalina.core.AprLifecycleListener init
    INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jre7\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:\oraclexe\app\oracle\product\10.2.0\server\bin;C:\Program Files (x86)\PC Connectivity Solution\;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\Microsoft\Web Platform Installer\;C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET Web Pages\v1.0\;C:\Program Files (x86)\Windows Kits\8.0\Windows Performance Toolkit\;C:\Program Files\Microsoft SQL Server\110\Tools\Binn\;C:\Program Files\Microsoft SQL Server\110\DTS\Binn\;C:\Program Files (x86)\Microsoft SQL Server\110\Tools\Binn\ManagementStudio\;C:\Program Files (x86)\Microsoft SQL Server\110\Tools\Binn\;C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\PrivateAssemblies\;C:\Program Files (x86)\Microsoft SQL Server\110\DTS\Binn\;C:\Program Files\Java\jdk1.7.0_07\bin;C:\Program Files\Java\jdk1.7.0_07\bin\javaw.exe;.
    Sep 08, 2013 5:21:00 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
    WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property ‘source’ to ‘org.eclipse.jst.jee.server:StrutsHelloWorld’ did not find a matching property.
    Sep 08, 2013 5:21:03 PM org.apache.coyote.AbstractProtocol init
    INFO: Initializing ProtocolHandler ["http-bio-8080"]
    Sep 08, 2013 5:21:03 PM org.apache.coyote.AbstractProtocol init
    INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
    Sep 08, 2013 5:21:03 PM org.apache.catalina.startup.Catalina load
    INFO: Initialization processed in 5877 ms
    Sep 08, 2013 5:21:03 PM org.apache.catalina.core.StandardService startInternal
    INFO: Starting service Catalina
    Sep 08, 2013 5:21:03 PM org.apache.catalina.core.StandardEngine startInternal
    INFO: Starting Servlet Engine: Apache Tomcat/7.0.42
    Sep 08, 2013 5:21:05 PM org.apache.catalina.util.SessionIdGenerator createSecureRandom
    INFO: Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [432] milliseconds.
    Sep 08, 2013 5:21:07 PM org.apache.struts2.dispatcher.Dispatcher error
    SEVERE: Dispatcher initialization failed
    java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
    at com.opensymphony.xwork2.inject.ContainerImpl$MethodInjector.inject(ContainerImpl.java:301)
    at com.opensymphony.xwork2.inject.ContainerImpl$ConstructorInjector.construct(ContainerImpl.java:438)

    at ognl.OgnlRuntime.(OgnlRuntime.java:168)
    … 33 more
    Caused by: java.lang.ClassNotFoundException: javassist.ClassPool
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1714)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1559)
    at java.lang.Class.forName0(Native Method)

  • Fayaaz 8 September, 2013, 17:23

    Hi viral,

    what is the cause of relect invocation target excepion ?

  • Danny 17 September, 2013, 0:38

    HI,
    when I am using struts2-core-2.3.1.2.jar ablove example works file but when I ma using struts2-core-2.3.15.1.jar its giving error
    HTTP Status 404 – /StrutsHelloWorld/

    type Status report

    message /StrutsHelloWorld/

    description The requested resource is not available.

    ——————————————————————————–

    Apache Tomcat/7.0.42

    • santhosh 18 October, 2013, 18:47

      404 resource not available is due to error or mistakes in struts.xml or web.xml

    • Jassi 28 October, 2013, 17:34

      Pls help in this case as it is not due to problem in web.xml or struts.xml. I used jars xwork-core-2.3.15.2.jar and struts2-core-2.3.15.2.jar instead of those provided in this tutorial and it fails. Just by replacing the jars with the ones provided here,it works.No other change has been made. Can anyone pls explain the scenerio?

      • ra 16 April, 2014, 16:54

        if u get the solution …please post it here…i am facing the same problem.

  • Sandeep 17 September, 2013, 15:35

    Thnaks #buchireddy, your solution helped a lot,

  • Swapnil Zurange 17 September, 2013, 17:18

    Thank you very much…..it is very helpful for me…..and also helpful for every beginer…

    Thanks again…

  • gwen 24 September, 2013, 0:54

    I saved the web.xml file under ‘WebContent/WEB_INFO’ folder but my eclipse keeps showing ‘Error Page’ under the ‘Deployment Descriptor’. When I click on it, web.xml will open up. It doesn’t seem to be a problem while I build the project (no error msg) but after publishing it to the server, I have trouble bring up the Login page. Error msg ’404, The requested resource (/StrutsHelloWorld2/) is not available’. Please help. BTW, I am using Eclipse Juno, Apache-Tomcat 7 and jdk 1.7.

  • Lokesh Arora 26 September, 2013, 19:35

    Very nice tutorial. Helped a lot. Great work viral.

  • Memo 4 October, 2013, 9:42

    I was getting the same error that most of you got. 404 with SEVERE: Exception starting filter Struts2. As people have mentioned, the tutorial works with the exact jars otherwise you have to import extra jars. Using Camel, I set a dependency for struts 2 and it important the following:

    aopalliance-1.0.jar
    asm-3.3.jar
    asm-commons-3.3.jar
    asm-tree-3.3.jar
    commons-fileupload-1.3.jar
    commons-io-2.0.1.jar
    commons-lang3-3.1.jar
    commons-logging-1.1.1.jar
    freemarker-2.3.19.jar
    javassist-3.11.0.GA.jar
    ognl-3.0.6.jar
    spring-aop-3.0.5.RELEASE.jar
    spring-asm-3.0.5.RELEASE.jar
    spring-beans-3.0.5.RELEASE.jar
    spring-context-3.0.5.RELEASE.jar
    spring-core-3.0.5.RELEASE.jar
    spring-expression-3.0.5.RELEASE.jar
    spring-test-3.0.5.RELEASE.jar
    struts2-core-2.3.15.jar
    struts2-junit-plugin-2.3.15.jar
    xwork-core-2.3.15.jar

    My application is working now.

  • jagnya 4 October, 2013, 10:30

    Thank u sir……………

  • Ramesh 14 October, 2013, 10:30

    Hi

    Thanks for the wonderful Tutorial. I have a doubt on how the variables username and password of LoginAction.java are assigned the values of textfield values in the Login.jsp. I even tried renaming the variables in the java class. Still its logging in successfully

    Thanks,
    Ramesh

  • Rajeshkumar 17 October, 2013, 9:37

    Nice tutorial and worked fine.

  • Rahul 17 November, 2013, 1:03

    Error message is displayed in BLACK color. How to change it in red

  • Hari 20 November, 2013, 19:30

    I need to implement code(Invalid username or Password) with in Action class it self for my requirement ……can you mail me that code….Krishv_1@yahoo.com

  • pankaj 27 November, 2013, 16:33

    really great tutorail dude.thnx man

  • Umapathy 29 November, 2013, 18:30

    classy example ever … _/\_

  • JR Chung 2 December, 2013, 14:19

    Viral, thank you for your posting with kind explanation.

    I am new to Struts2 and tried your example after failing my first Hello World example.
    However, it’s failing with the same issue.
    I tried to replicate the exact steps following yours, but the error I got is as below:

    Please correct me where I got wrong…

    Thanks again in advance.
    ================================
    HTTP Status 500 – java.lang.ClassNotFoundException: org.apache.jsp.StrutsHelloWorld.Login_jsp

    type Exception report

    message java.lang.ClassNotFoundException: org.apache.jsp.StrutsHelloWorld.Login_jsp

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

    exception

    org.apache.jasper.JasperException: java.lang.ClassNotFoundException: org.apache.jsp.StrutsHelloWorld.Login_jsp
    org.apache.jasper.servlet.JspServletWrapper.getServlet(JspServletWrapper.java:177)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:369)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
    root cause

    java.lang.ClassNotFoundException: org.apache.jsp.StrutsHelloWorld.Login_jsp
    java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    java.security.AccessController.doPrivileged(Native Method)
    java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    org.apache.jasper.servlet.JasperLoader.loadClass(JasperLoader.java:132)
    org.apache.jasper.servlet.JasperLoader.loadClass(JasperLoader.java:63)
    org.apache.jasper.servlet.JspServletWrapper.getServlet(JspServletWrapper.java:172)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:369)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
    note The full stack trace of the root cause is available in the Apache Tomcat/7.0.47 logs.

  • JR Chung 2 December, 2013, 14:21

    If I refresh the page, I got this message.
    With the previous one, the two error messages are toggling:

    ================================
    HTTP Status 500 – /StrutsHelloWorld/Login.jsp (line: 2, column: 40) File “/struts-tags” not found

    type Exception report

    message /StrutsHelloWorld/Login.jsp (line: 2, column: 40) File “/struts-tags” not found

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

    exception

    org.apache.jasper.JasperException: /StrutsHelloWorld/Login.jsp (line: 2, column: 40) File “/struts-tags” not found
    org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:42)
    org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:443)
    org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:133)
    org.apache.jasper.compiler.TagLibraryInfoImpl.(TagLibraryInfoImpl.java:166)
    org.apache.jasper.compiler.Parser.parseTaglibDirective(Parser.java:410)
    org.apache.jasper.compiler.Parser.parseDirective(Parser.java:475)
    org.apache.jasper.compiler.Parser.parseElements(Parser.java:1427)
    org.apache.jasper.compiler.Parser.parse(Parser.java:138)
    org.apache.jasper.compiler.ParserController.doParse(ParserController.java:242)
    org.apache.jasper.compiler.ParserController.parse(ParserController.java:102)
    org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:198)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:373)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:353)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:340)
    org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:646)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:357)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
    note The full stack trace of the root cause is available in the Apache Tomcat/7.0.47 logs.

  • Rishi Kumar 4 December, 2013, 15:31

    Thanks, it helped a lot

  • Rahul Makwana 9 December, 2013, 16:33

    Thank You So much for explaining in such a simple way.. perfectly running…

  • Manuel 18 December, 2013, 9:50

    Any idea why I am getting the following error when click on the submit button…..Thanks

    HTTP Status 404 – There is no Action mapped for namespace [/] and action name [login] associated with context path [/StrutsHelloWorld].

    ——————————————————————————–

    type Status report

    message There is no Action mapped for namespace [/] and action name [login] associated with context path [/StrutsHelloWorld].

    description The requested resource is not available.

    ——————————————————————————–

    Apache Tomcat/7.0.47

  • suresh 21 December, 2013, 23:27

    Please help me in solving following problem:

    SEVERE: Dispatcher initialization failed
    Unable to load configuration. - action - file:/C:/login/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/Jaganji/WEB-INF/classes/struts.xml:11:55
    	at com.opensymphony.xwork2.config.ConfigurationManager.getConfiguration(ConfigurationManager.java:70)
    	at org.apache.struts2.dispatcher.Dispatcher.init_PreloadConfiguration(Dispatcher.java:446)
    	at org.apache.struts2.dispatcher.Dispatcher.init(Dispatcher.java:490)
    	at org.apache.struts2.dispatcher.ng.InitOperations.initDispatcher(InitOperations.java:74)
    Caused by: Action class [java4s.LogingEx] not found - action - file:/C:/login/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/Jaganji/WEB-INF/classes/struts.xml:11:55
    	at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.verifyAction(XmlConfigurationProvider.java:482)
    	at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.addAction(XmlConfigurationProvider.java:426)
    	at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.addPackage(XmlConfigurationProvider.java:552)
    	at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.loadPackages(XmlConfigurationProvider.java:292)
    	at org.apache.struts2.config.StrutsXmlConfigurationProvider.loadPackages(StrutsXmlConfigurationProvider.java:112)
    	at com.opensymphony.xwork2.config.impl.DefaultConfiguration.reloadContainer(DefaultConfiguration.java:250)
    	at com.opensymphony.xwork2.config.ConfigurationManager.getConfiguration(ConfigurationManager.java:67)
    	... 22 more
    Dec 21, 2013 11:11:00 PM org.apache.catalina.core.StandardContext filterStart
    SEVERE: Exception starting filter struts2
    Unable to load configuration. - action - file:/C:/login/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/Jaganji/WEB-INF/classes/struts.xml:11:55
    	at org.apache.struts2.dispatcher.Dispatcher.init(Dispatcher.java:502)
    	at org.apache.struts2.dispatcher.ng.InitOperations.initDispatcher(InitOperations.java:74)
    	at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.init(StrutsPrepareAndExecuteFilter.java:57)
    
    Caused by: Unable to load configuration. - action - file:/C:/login/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/Jaganji/WEB-INF/classes/struts.xml:11:55
    	at com.opensymphony.xwork2.config.ConfigurationManager.getConfiguration(ConfigurationManager.java:70)
    	at org.apache.struts2.dispatcher.Dispatcher.init_PreloadConfiguration(Dispatcher.java:446)
    	at org.apache.struts2.dispatcher.Dispatcher.init(Dispatcher.java:490)
    	... 20 more
    Caused by: Action class [java4s.LogingEx] not found - action - file:/C:/login/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/Jaganji/WEB-INF/classes/struts.xml:11:55
    	at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.verifyAction(XmlConfigurationProvider.java:482)
    	at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.addAction(XmlConfigurationProvider.java:426)
    
    	at com.opensymphony.xwork2.config.ConfigurationManager.getConfiguration(ConfigurationManager.java:67)
    	... 22 more
    
  • Varun Pant 14 February, 2014, 11:07

    WARNING: No configuration found for the specified action: ‘login’ in namespace: ”. Form action defaulting to ‘action’ attribute’s literal value.
    Feb 14, 2014 12:01:57 PM org.apache.struts2.components.Form evaluateExtraParamsServletRequest
    The error suggests that Struts 2 couldn’t load your XML configuration. Make sure your struts.xml is inside WEB-INF/classes directory. (The rest of the configuration looks fine.)

    Happy Valentine’s Day
    Cheers :)

  • Pmytrinh 19 February, 2014, 8:33

    I follow step 2 to build the hello world struts appl. I use
    commons-logging-1.1.3.jar
    freemarker-2.3.19.jar
    ognl-3.0.6.jar
    struts2-core-2.3.16.jar
    xwork-core-2.3.16.jar
    and when I try to run on server glassfish I have error below.Please help
    HTTP Status 500 – Internal Server Error

    ——————————————————————————–

    type Exception report

    messageInternal Server Error

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

    exception
    org.apache.jasper.JasperException: The Struts dispatcher cannot be found. This is usually caused by using Struts tags without the associated filter. Struts tags are only usable when the request has passed through its servlet filter, which initializes the Struts dispatcher needed for this tag. – [unknown location]

    root cause
    The Struts dispatcher cannot be found. This is usually caused by using Struts tags without the associated filter. Struts tags are only usable when the request has passed through its servlet filter, which initializes the Struts dispatcher needed for this tag. – [unknown location]

    note The full stack traces of the exception and its root causes are available in the GlassFish Server Open Source Edition 4.0 logs.

  • p 23 February, 2014, 0:25

    For those who have same error as me…
    I scratch my head few days and it still didn’t work.
    So, I just download the strut2-blank.war from Strut website http://struts.apache.org/download.cgi. , unzip that war and copy all jar file under WEB-INF/lib to the Hello World application and it works .

    Viral..Thanks for giving the tutorial. Could you please also update this page to specified, it needs all the jar files from the strut2-blank.war

  • Ashish 23 February, 2014, 1:06

    also if I run the Login Page it give the error
    HTTP Status 500 –

    ——————————————————————————–

    type Exception report

    message

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

    exception

    java.lang.NullPointerException
    org.apache.struts2.impl.StrutsActionProxy.getErrorMessage(StrutsActionProxy.java:69)
    com.opensymphony.xwork2.DefaultActionProxy.prepare(DefaultActionProxy.java:185)
    org.apache.struts2.impl.StrutsActionProxy.prepare(StrutsActionProxy.java:63)
    org.apache.struts2.impl.StrutsActionProxyFactory.createActionProxy(StrutsActionProxyFactory.java:39)
    com.opensymphony.xwork2.DefaultActionProxyFactory.createActionProxy(DefaultActionProxyFactory.java:58)
    org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:500)
    org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:434)

    note The full stack trace of the root cause is available in the Apache Tomcat/7.0.47 logs.

    ——————————————————————————–

    Apache Tomcat/7.0.47

  • prakash 3 March, 2014, 19:29

    hi all,

    I am facing this issue in my appliation.

    Could any one please help:

    Error 500–Internal Server Error
    The Struts dispatcher cannot be found. This is usually caused by using Struts tags without the associated filter. Struts tags are only usable when the request has passed through its servlet filter, which initializes the Struts dispatcher needed for this tag. – [unknown location]
    at org.apache.struts2.views.jsp.TagUtils.getStack(TagUtils.java:60)
    at org.apache.struts2.views.jsp.StrutsBodyTagSupport.getStack(StrutsBodyTagSupport.java:52)
    at org.apache.struts2.views.jsp.ComponentTagSupport.doStartTag(ComponentTagSupport.java:49)
    at jsp_servlet.__login._jsp__tag0(__login.java:114)
    at jsp_servlet.__login._jspService(__login.java:83)
    at weblogic.servlet.jsp.JspBase.service(JspBase.java:34)
    at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:227)
    at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:125)
    at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:300)
    at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:183)
    at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.wrapRun(WebAppServletContext.java:3714)
    at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3681)
    at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
    at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120)
    at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2277)
    at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2183)
    at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1454)
    at weblogic.work.ExecuteThread.execute(ExecuteThread.java:209)
    at weblogic.work.ExecuteThread.run(ExecuteThread.java:178)

    I am not able to resolve this issue.

  • Prakash 4 March, 2014, 15:11

    I am getting the following error while making the appliaction:

    Could any one please help:

    java.lang.NoClassDefFoundError: com/opensymphony/xwork2/util/logging/LoggerFactory
    at org.apache.struts2.dispatcher.Dispatcher.(Dispatcher.java:103)
    at org.apache.struts2.views.jsp.TagUtils.getStack(TagUtils.java:58)
    at org.apache.struts2.views.jsp.StrutsBodyTagSupport.getStack(StrutsBodyTagSupport.java:44)
    at org.apache.struts2.views.jsp.ComponentTagSupport.doStartTag(ComponentTagSupport.java:48)
    at jsp_servlet.__login._jsp__tag0(__login.java:114)
    Truncated. see log file for complete stacktrace
    Caused By: java.lang.ClassNotFoundException: com.opensymphony.xwork2.util.logging.LoggerFactory
    at weblogic.utils.classloaders.GenericClassLoader.findLocalClass(GenericClassLoader.java:297)
    at weblogic.utils.classloaders.GenericClassLoader.findClass(GenericClassLoader.java:270)
    at weblogic.utils.classloaders.ChangeAwareClassLoader.findClass(ChangeAwareClassLoader.java:64)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:305)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:246)
    Truncated. see log file for complete stacktrace

    I amusing the following jar:

    commons-logging-1.0.4.jar
    freemarker-2.3.8.jar
    ognl-2.6.11.jar
    struts2-core-2.3.12.jar
    xwork-2.0.6.jar

    Web.xml

    Struts2 Application

    struts2
    org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter

    struts2
    /*

    Login.jsp

  • Sahil 4 March, 2014, 18:28

    java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catal
    ina.LifecycleException: Failed to start component [StandardEngine[Catalina].Stan
    dardHost[localhost].StandardContext[/StrutsHelloWorld]]
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase
    .java:904)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:87
    7)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:633)

    at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:983)

    at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:
    1660)
    at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
    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)
    Mar 4, 2014 6:24:00 PM org.apache.catalina.startup.HostConfig deployDirectory
    INFO: Deploying web application directory C:\apache-tomcat-7.0.47\webapps\BasicS
    trust2ProjectEclipse
    Mar 4, 2014 6:24:01 PM org.apache.catalina.startup.HostConfig deployDirectory
    INFO: Deploying web application directory C:\apache-tomcat-7.0.47\webapps\docs
    Mar 4, 2014 6:24:01 PM org.apache.catalina.startup.HostConfig deployDirectory
    INFO: Deploying web application directory C:\apache-tomcat-7.0.47\webapps\exampl
    es
    Mar 4, 2014 6:24:02 PM org.apache.catalina.startup.HostConfig deployDirectory
    INFO: Deploying web application directory C:\apache-tomcat-7.0.47\webapps\host-m
    anager
    Mar 4, 2014 6:24:02 PM org.apache.catalina.startup.HostConfig deployDirectory
    INFO: Deploying web application directory C:\apache-tomcat-7.0.47\webapps\manage
    r
    Mar 4, 2014 6:24:02 PM org.apache.catalina.startup.HostConfig deployDirectory
    INFO: Deploying web application directory C:\apache-tomcat-7.0.47\webapps\ROOT
    Mar 4, 2014 6:24:02 PM org.apache.catalina.startup.HostConfig deployDirectory
    INFO: Deploying web application directory C:\apache-tomcat-7.0.47\webapps\struts
    2HelloWord
    Mar 4, 2014 6:24:02 PM org.apache.coyote.AbstractProtocol start
    INFO: Starting ProtocolHandler ["http-bio-9999"]
    Mar 4, 2014 6:24:02 PM org.apache.coyote.AbstractProtocol start
    INFO: Starting ProtocolHandler ["ajp-bio-8009"]
    Mar 4, 2014 6:24:02 PM org.apache.catalina.startup.Catalina start
    INFO: Server startup in 4548 ms

    The requested resource is not available.

    KIndly help me…..

  • vikas mane 7 March, 2014, 14:24

    Awesome tutorial…i have been trying running struts 2 program from last 10 days.your tutorial helped me get a headstart..thank you

  • akki 18 March, 2014, 2:45

    HTTP Status 404 – /StrutsHeloWorld/
    what to doo

  • ManhQuyen 1 April, 2014, 7:23

    You should note that “The FilterDispatcher filter is deprecated since Struts version 2.1.3. If you are using latest version of Struts2 ( > 2.1.3) use StrutsPrepareAndExecuteFilter class instead.”

Leave a Reply

Your email address will not be published. Required fields are marked *

Note

To post source code in comment, use [code language] [/code] tag, for example:

  • [code java] Java source code here [/code]
  • [code html] HTML here [/code]