Struts2 Hello World example using Eclipse and Maven2

May 20, 2009

Submitted by: Fayçal

Category: Computers

6,484 views

Not satisfied by struts2-archetype-starter (a little bit complicated for a starter kit) and not able to create a Maven project using struts2-archetype-blank (from Internal Catalog)… After hours of googling through many different tutorials, I was finally able to run a very basic Hello World example of Struts using Maven2 under Eclipse IDE… this is my step-by-step story :

Update: Special note to linux (ubuntu based dist) users

1- Check that JAVA_HOME environment variable is correctly set to your installed JDK (and not JRE) folder (In my case : JAVA_HOME = C:Program FilesJavajdk1.6.0_07)

2- Check that your Eclipse is also correctly set to use this JDK : Window ->; Preferences -> Installed JRE (jdk1.6.0_07 must be checked)

3- If not already done, install http://m2eclipse.codehaus.org and if you are behind a proxy, don’t forget to update your C:Documents and Settingsuser.m2settings.xml

...
<proxies>
  <proxy>
    <active>true</active>
    <protocol>http</protocol>
    <username>agafix</username>
    <password>guess what</password>
    <host>host.org</host>
    <port>3128</port>
  </proxy>
</proxies>
...

4- Create a new maven project : File ->; New -> Project -> Maven Project, then click Next

Maven project

leave default -> Next

Maven Project 2

5- Having the Nexus Indexer Catalog, tape “webapp” as a filter and then choose the l’Artifact Id “maven-archetype-webapp”

maven-archetype-webapp

6- Finish Completing the missing Archetype parameters, in this tutorial case :

Archetype parameters

7- Those steps will create for you this project structure

jsp web app

8- Set the tools.jar dependence in your pom.xml

<project ...>
  ...
  <!-- tools.jar dependecy -->
  <profiles>
    <profile>
      <id>default-tools.jar</id>
      <activation>
        <property>
          <name>java.vendor</name>
          <value>Sun Microsystems Inc.</value>
        </property>
      </activation>
      <dependencies>
        <dependency>
          <groupId>com.sun</groupId>
          <artifactId>tools</artifactId>
          <version>1.5.0</version>
          <scope>system</scope>
          <systemPath>C:/Program Files/Java/jdk1.6.0_07/lib/tools.jar</systemPath>
        </dependency>
      </dependencies>
    </profile>
  </profiles>
  <dependencies>
  ...
  </dependencies>
</project>

9- Add struts2

<project ...>
  ...
  <dependencies>
	...
	<dependency>
        <groupId>org.apache.struts</groupId>
        <artifactId>struts2-core</artifactId>
        <version>2.0.11.2</version>
    </dependency>
  </dependencies>
</project>

10- The finale pom.xml will look like

<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>org.agafix</groupId>
  <artifactId>tuto_hello</artifactId>
  <packaging>war</packaging>
  <version>1.0</version>
  <name>tuto_hello Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <!-- tools.jar dependecy -->
  <profiles>
    <profile>
      <id>default-tools.jar</id>
      <activation>
        <property>
          <name>java.vendor</name>
          <value>Sun Microsystems Inc.</value>
        </property>
      </activation>
      <dependencies>
        <dependency>
          <groupId>com.sun</groupId>
          <artifactId>tools</artifactId>
          <version>1.5.0</version>
          <scope>system</scope>
          <systemPath>C:/Program Files/Java/jdk1.6.0_07/lib/tools.jar</systemPath>
        </dependency>
      </dependencies>
    </profile>
  </profiles>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
	<dependency>
        <groupId>org.apache.struts</groupId>
        <artifactId>struts2-core</artifactId>
        <version>2.0.11.2</version>
    </dependency>
  </dependencies>
  <build>
    <finalName>tuto_hello</finalName>
  </build>
</project>

11- Let’s complete the creation of our suource folders: Right click on tuto_hello project -> New -> Source Folder and create folders with the names “src/main/java”, “src/test/java” and “src/test/resources”.
Finally create a package in your “src/main/java” and “src/test/java” (right click on source folder then New -> Package)

source folders

12- Create the HelloAction class in your package

package tutorial;
import com.opensymphony.xwork2.ActionSupport;
public class HelloAction extends ActionSupport
{
  private static final long serialVersionUID = 1L;
  public static final String MESSAGE = "La vache quoi !!!";
  private String message;
  public String execute()
  {
      setMessage(MESSAGE);
      return SUCCESS;
  }
  public String getMessage() {
      return message;
  }
  public void setMessage(String message) {
      this.message = message;
  }
}

13- Update index.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
  <body>
    <h2>
      <s:property value="message"/>
    </h2>
  </body>
</html>

14- Create the struts.xml config file in “src/main/resources”

<?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>
	<package name="tutorial" namespace="/" extends="struts-default">
        <action name="hello" class="tutorial.HelloAction">
            <result>/index.jsp</result>
        </action>
    </package>
</struts>

15- Reference the struts action filter in web.xml

<!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>A real struts/maven hello world project</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>index.jsp</welcome-file>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>
</web-app>

16- Create the HelloActionTest class for JUnit in the package already created in “src/test/java”

package tutorial;
import junit.framework.TestCase;
import com.opensymphony.xwork2.ActionSupport;
public class HelloActionTest extends TestCase
{
  public void testhelloAction() throws Exception
  {
    HelloAction index = new HelloAction();
    String result = index.execute();
    assertTrue("Expected a success result!", ActionSupport.SUCCESS.equals(result));
    assertTrue("Expected the default message!", HelloAction.MESSAGE.equals(index.getMessage()));
    }
}

17- Folders and files organization summary

struts folders organization

click to enlarge

18- Do a right click on the project: Run as -> Maven install

Maven install target

click to enlarge

19- This will compile, test and build the war file in the target folder of your project and also in your Maven2 local repository

Maven's BUILD SUCCESSFUL

click to enlarge

20- Deploy this war file in your J2EE application server (Sun GlassFish in this tutorial)

Deploy in GlassFish

click to enlarge

21- Launch your MVC Hello World via http://localhost:8080/tuto_hello/hello.action

MVC Hello World

click to enlarge

You can download this eclipse project via this link

  tuto_hello.zip (6.5 MiB, 539 hits)

Special note to linux (ubuntu based dist) users

1- If not already done, install JRE and JDK

sudo apt-get install sun-java6-jdk sun-java6-jre

2- tell your ubuntu based dist to use sun jre and not openjdk

sudo update-alternatives --config java

3- Set JAVA_HOME to JDK folder by adding the two following lines in /etc/bash.bashrc

JAVA_HOME="/usr/lib/jvm/java-6-sun"
export JAVA_HOME

4- To install m2eclipse use http://m2eclipse.sonatype.org/update-dev/ and not http://m2eclipse.sonatype.org/update/

5- m2eclipse will report you that no settings.xml was found, to hide this warning, just create a blank one in ${user.home}/.m2/settings.xml having

<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                      http://maven.apache.org/xsd/settings-1.0.0.xsd">
  <localRepository/>
  <interactiveMode/>
  <usePluginRegistry/>
  <offline/>
  <pluginGroups/>
  <servers/>
  <mirrors/>
  <proxies/>
  <profiles/>
  <activeProfiles/>
</settings>

6- Since your JAVA_HOME is correctly set, update pom.xml to use it for the tools.jar system path

...
<systemPath>${java.home}/../lib/tools.jar</systemPath>
...
linux pom

click to enlarge

7- Install Tomcat6

sudo apt-get install tomcat6 tomcat6-admin tomcat6-doc

8- Create profiles and user to access the manager (http://locahost:8080/manager/html) and the host-manager (http://locahost:8080/host-manager/html) web application. just add in /etc/tomcat6/tomcat-users.xml:

<tomcat-users>
<role rolename="admin"/>
<role rolename="manager"/>
<user username="tomcat" password="guess what" roles="admin,manager"/>
</tomcat-users>

click to enlarge

tomcat-manager

9- Update /etc/default/tomcat6

JAVA_HOME=/usr/lib/jvm/java-6-sun
# do not use security manager so tomcat6 could write to directories other than the default.
TOMCAT6_SECURITY=no

click to enlarge

test_tomcat_deploy

If you liked this, please share it at your favorite sites:
  • Digg
  • Reddit
  • del.icio.us
  • Wikio
  • Facebook
  • Google
  • Technorati
  • TwitThis
  • MySpace
  • N4G
  • NewsVine
  • StumbleUpon
  • BlogMemes
  • Blogsvine
  • blogtercimlap
  • DotNetKicks
  • eKudos
  • Faves
  • Fleck
  • Scoopeo
  • Socialogs
  • Upnews
  • Yigg
  • E-mail this story to a friend!
  • Mixx

4 Responses :D Pretty Cool

  • tout-est-signe

    May 20th, 2009

    at 20:08

    Je vous remercie pour l’effort que vous avez déployé en présentant ce post Bon pour ce que vous avez avancé être un ptit peu chwiyya franc, je suis intéressé par Maven et j’ai utilisé le code que vous avez avancé vainement…A chaque fois j’obtiens le message d’erreur suivant: BOOM…:D and guess what I don’t like your horrible patcha :P

  • BOOM comme message d’erreur ?!! :D
    ewa 3la slama be3da ;)

  • .. and finally a new topic in agafix.org !
    Good job.

  • :D Good good good… it’s work!!!! :up:

Leave a Reply

:D :) :cry: :( 8O :twisted: :!: :vangry: :XO: :up: ;) :mrgreen: :halo: :kiss: :roll: :? 8) :evil: :oops: :| :?: :x :$: