Every Flavour Beans

“The time has come…to talk of many [technologies].” –Lewis Carroll(’The Walrus and the Carpenter’)
Development Tools. Web Frameworks. GNU/Linux. Nokia N800. Video Encoding.

July 30, 2008

“Hello, World” Web Application using Struts 2 in NetBeans IDE 6.1

Filed under: Java, Netbeans, Struts 2 — tabrez @ 11:52 pm

This tutorial guides you through the process of creating and running a basic "Hello, World" Struts 2 web application using the NetBeans IDE 6.1.

NOTE: I recommend trying to follow the NetBeans tutorial on the Struts 2 website first. If you find any problems following it, then come back to my tutorial. I have tried to make this more beginner friendly by including a lot of screenshots.

Download/Install Java SE, NetBeans and Struts 2

  1. Download and Install the latest version of Sun JDK: Sun Java SE 6 Update 7.
  2. Download and Install the latest version of NetBeans IDE: NetBeans IDE 6.1.
  3. Download the Struts 2 "Full Distribution" package(~90MB) and extract it in a directory. You can also opt for the smaller "Essential Dependencies Only" package if you want to later incrementally add additional packages as and when the need arises.

    Download Struts 2 Full Distribution or Dependecy Only package.

  4. Run the NetBeans IDE and create a new Web Application project in it. Name it "HelloStruts2World" or something like that.

    Create a new web application project in NetBeans.

    Don't select any frameworks, especially Struts 1.2.9, to be added to the project.

Add Struts 2 Libraries to Web Application project in NetBeans and configure web.xml file

  1. Add the Struts 2 library files to the web application project: Expand the web application project structure in the Project pane if not already expanded; right-click on the Libraries folder and click the Add JAR/Folder... menu item.

    Add Struts 2 JAR library files to NetBeans Web application project.

    In the Add JAR/Folder file chooser dialog box, browse to the extracted Struts 2 directory, go to lib directory in it and select all the JAR files that you want to add to the project. Hold down the Ctrl button to select multiple files.

    Add basic Struts 2 JAR library files to NetBeans Web Application project.

    The following JAR library files are essential for most Struts 2 projects(and for this tutorial) but you can select more if you know that you need them(you can add additional libraries later also):

    • commons-logging
    • ognl
    • struts2-core
    • xwork
    • freemarker

    Libraries folder in your project will now look like this:

    Struts 2 JAR files added to Libraries folder of web project in NetBeans.

  2. Add a filter element to web.xml deployment descriptor to let Struts 2 handle all the requests for your web application. Expand the Configuration Files folder and double-click on web.xml file, select the XML tab and copy paste the following code in it.
    XML:
    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    3.     <filter>
    4.         <filter-name>Struts 2 filter</filter-name>
    5.         <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
    6.     </filter>
    7.     <filter-mapping>
    8.         <filter-name>Struts 2 filter</filter-name>
    9.         <url-pattern>/*</url-pattern>
    10.     </filter-mapping>
    11.     <session-config>
    12.         <session-timeout>
    13.             30
    14.         </session-timeout>
    15.     </session-config>
    16. </web-app>

    You can enter the same data in Filters tab also:

Create Struts 2 action Java class and JSP result page and configure struts.xml file

  1. We need one or more Java packages to store all the Java classes(Struts 2 actions) in it. Let's call the first package "hello." Right click Sources Package directory, select New and then select Java Class... menu item. Enter a name for the Java class(say HelloStruts2World") and enter a package name(say hello) and click Finish.
  2. Edit the HelloStruts2World.java file so that it looks like this:
    JAVA:
    1. package hello;
    2. import com.opensymphony.xwork2.ActionSupport;
    3.  
    4. public class HelloStruts2World extends ActionSupport {
    5.     private String userName;
    6.     public String getUserName() {
    7.         return userName;
    8.     }
    9.     public void setUserName(String userName) {
    10.         this.userName = userName;
    11.     }
    12.  
    13.     private String message;
    14.     public String getMessage() {
    15.         return message;
    16.     }
    17.  
    18.     @Override
    19.     public String execute() {
    20.         message = "Hello, " + userName + ".";
    21.         return SUCCESS;
    22.     }
    23. }

  3. We now need to configure the Java class created in the above step as a Struts 2 Action and map it to a result page. To do so, we need to create two Struts 2 configuration files - struts.xml and struts.properties - in the source package.
    1. Right-click on hello package in Source Packages folder and select New and then select XML document... and enter struts as the file name. This will create struts.xml file.
    2. Right-click on hello package in Source Packages folder and select New and then select Properties File... and enter struts as the file name. This will create struts.properties file.

    Edit struts.xml file such that it has the following content:

    XML:
    1. <!DOCTYPE struts PUBLIC
    2.     "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    3.     "http://struts.apache.org/dtds/struts-2.0.dtd">
    4.  
    5. <struts>
    6.     <package name="/" extends="struts-default">
    7.         <action name="HelloStruts2World" class="hello.HelloStruts2World">
    8.             <result name="success">/index.jsp</result>           
    9.         </action>
    10.     </package>
    11. </struts>

    This maps the requests sent to the "/HelloStruts2World.action" url to HelloStruts2World.java Struts 2 action and after the successful execution of the request, it gets directed to the index.jsp result page. Leave the struts.properties file empty for now.

  4. Let us access the message property set by HelloStruts2World action and display it in the index.jsp page. Edit index.jsp so that it looks like this:
    HTML:
    1. <%@page contentType="text/html" pageEncoding="UTF-8"%>
    2. <%@taglib prefix="s" uri="/struts-tags" %>
    3. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    4.    "http://www.w3.org/TR/html4/loose.dtd">
    5.  
    6.     <head>
    7.         <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    8.         <title>Hello Struts 2 World Result Page</title>
    9.     </head>
    10.     <body>
    11.         <h2>Hello World!</h2>       
    12.         Struts 2 Message: <s:property value="message" default="Guest." />       
    13.        
    14.         <s:form method="GET" action="hello/HelloStruts2World.action">
    15.             Enter your name:<s:textfield name="userName" />
    16.             <s:submit value="Submit" />
    17.         </s:form>               
    18.     </body>
    19. </html>

Run the Struts 2 Web Application Project in NetBeans 6.1 IDE

  1. The "HelloStruts2World" web application project structure, when relevant folders expanded, should look like this:

    Hello World Struts 2 web application project structure in NetBeans IDE.

  2. Run the web application by going to Run -> Run Main Project and then access the following URL in a web browser: http://localhost:8080/HelloStruts2World/. You may have to modify this URL depending on what port the web server is running("8080") and what is the name of your web application("HelloStruts2World").

    Struts 2 Action redirects to JSP "SUCCESS" result page

Other Options:

This is the manual way to develop Struts 2 web applications in the NetBeans IDE but it is at least more beginner friendly than working from the command line using just the Maven build tool. There is a Struts 2 plugin called nbstruts available for NetBeans; its functionality is currently limited but it is under active development. Other popular alternative IDEs for developing web applications using Struts 2 are Eclipse and IntelliJ IDEA.


If you want to receive future posts by email, enter your email address here:

Related Posts:

  • Struts 2 Plugin for NetBeans IDE - nbstruts2support
  • “Hello, World” Web Application using Struts 2 in IntelliJ IDEA 8.0 M1
  • “Hello, World” Web Application in Ruby on Rails using Aptana Studio
  • Setting Up Rails Development Environment on Windows Vista/XP
  • Creating “Hello World” Web Application Using the Grails Framework
  • Setting Up Rails Development Environment using Aptana Studio
  • Setting Up Development Environment For Grails on Windows Vista/XP

  • Readers who viewed this page, also viewed:


    9 Comments »

    1. [...] Java, Netbeans, struts2 — tabrez @ 10:09 pm As mentioned in my previous post about creating Struts 2 web applications in NetBeans IDE, there is a Struts 2 plugin available for the NetBeans IDE but it is still under development. You [...]

      Quote

      Pingback by Struts 2 Plugin for NetBeans IDE - nbstruts2support — August 4, 2008 @ 10:09 pm

    2. Good Forum for Learners.

      Quote

      Comment by Krishna — August 18, 2008 @ 4:37 pm

    3. [...] experience with NetBeans or Eclipse IDEs even with the help of the plugins: see my previous posts “Hello, World” Web Application using Struts 2 in NetBeans IDE 6.1 and Struts 2 Plugin for NetBeans IDE - nbstruts2support for example. All we need to do now is to [...]

      Quote

      Pingback by “Hello, World” Web Application using Struts 2 in IntelliJ IDEA 8.0 M1 — August 20, 2008 @ 7:19 pm

    4. I cant not run the project!!!

      Estado de HTTP 503 -

      type Informe de estado

      Mensaje

      DescripciónEl servicio solicitado () no se encuentra disponible actualmente.
      Sun Java System Application Server 9.1_02

      Helpme!!!! please

      Quote

      Comment by Manuel Jara — September 23, 2008 @ 8:46 am

    5. instead of hello I've used my.strut2.hello package.
      in form i use action="my/strut2/hello/HelloStruts2World.action", but I'm getting following exception:

      java.lang.IllegalArgumentException: URI is not hierarchical

      Servlet.service() for servlet jsp threw exception
      java.lang.RuntimeException: java.lang.RuntimeException: java.lang.RuntimeException: java.lang.RuntimeException: java.lang.RuntimeException: java.lang.RuntimeException: java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
      at com.opensymphony.xwork2.inject.ContainerImpl$MethodInjector.inject(ContainerImpl.java:290)

      Quote

      Comment by Lonely Soul — September 23, 2008 @ 11:31 am

    6. If your actions reside in the same package, you can try specifying just the action name(note that there is not .action extension):
      action="HelloStruts2World"

      Quote

      Comment by tabrez — September 23, 2008 @ 5:48 pm

    7. Hello,
      I've followed you tutorial which run fine and displayed the hello world page, but if I write my name and then click the submit button I obtain the following error:
      (FYI the url displayed is: http://localhost:8080/HelloStruts2World/hello/HelloStruts2World?userName=zaf)

      error in the page HTTP Status 404

      type Status report
      message
      descriptionThe requested resource () is not available.

      and in the IDE :
      under glassfish :
      No configuration found for the specified action: 'hello/HelloStruts2World' in namespace: ''. Form action defaulting to 'action' attribute's literal value.

      Have you any idea about this problem ?

      Thanks for your answer

      Quote

      Comment by zafnormand — October 11, 2008 @ 7:42 pm

    8. I´m getting the same error that happened with zaf.
      What i do to resolve this?

      thanks

      Quote

      Comment by GVSOUZA — October 17, 2008 @ 7:46 am

    9. I am getting the following error:
      Deployment error:
      The module has not been deployed.
      See the server log for details.
      at org.netbeans.modules.j2ee.deployment.devmodules.api.Deployment.deploy(Deployment.java:163)
      at org.netbeans.modules.j2ee.ant.Deploy.execute(Deploy.java:104)
      at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:288)
      at sun.reflect.GeneratedMethodAccessor166.invoke(Unknown Source)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
      at java.lang.reflect.Method.invoke(Method.java:597)
      at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:105)
      at org.apache.tools.ant.Task.perform(Task.java:348)
      at org.apache.tools.ant.Target.execute(Target.java:357)
      at org.apache.tools.ant.Target.performTasks(Target.java:385)
      at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1329)
      at org.apache.tools.ant.Project.executeTarget(Project.java:1298)
      at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:41)
      at org.apache.tools.ant.Project.executeTargets(Project.java:1181)
      at org.apache.tools.ant.module.bridge.impl.BridgeImpl.run(BridgeImpl.java:277)
      at org.apache.tools.ant.module.run.TargetExecutor.run(TargetExecutor.java:460)
      at org.netbeans.core.execution.RunClassThread.run(RunClassThread.java:151)
      Caused by: The module has not been deployed.
      at org.netbeans.modules.j2ee.deployment.devmodules.api.Deployment.deploy(Deployment.java:157)
      ... 16 more
      BUILD FAILED (total time: 17 seconds)

      Could you please advice me.

      Quote

      Comment by Mariaprabudass — November 14, 2008 @ 3:58 pm

    RSS feed for comments on this post. TrackBack URI

    Leave a comment

    Subscribe without commenting


    Copyright (c) 2006, 2007 Tabrez Iqbal.
    Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. Verbatim copying and distribution of this entire article is permitted in any medium without royalty provided this notice is preserved. A copy of the license is included in the section entitled "GNU Free Documentation License".


    Powered by WordPress
    This website is hosted by Dreamhost