Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Struts2 Hello World example


May 15, 2021 Struts2


Table of contents


By learning about the Struts2 framework, you can learn that when you click on a hyperlink or submit an HTML form in Struts2's web application, the controller collects input and sends a Java class called Actions. A fter Action is executed, Result selects a resource to respond. This resource is usually a JSP, or it can be a PDF file, an Excel table, or a Java widget window.

Assuming you've built your development environment, let's move on to the first Struts2 project: Hello World. T he goal of this project is to build a web application that collects user names and follows them with hello World. We need to build the following four components for each Struts2 project:

Serial number Name and description
1 Action (Action)
Create an action class that contains complete business logic and controls interaction between users, models, and views.
2 Interceptors (Interceptor)
This is part of the controller that can create interceptors on demand or use existing interceptors.
3 View (View)
Create a JSP to interact with the user, get input, and present the final information.
4 Configuration Files (Profile)
Create profiles to connect actions, views, and controllers, which are struts.xml web .xml, and struts.properties.

If we plan to use eclipse IDE, all the necessary components will be created under Dynamic Web Project. S o let's start by creating a dynamic Web project.

Create a dynamic Web project:

Start your Eclipse, then open "File" and "New" and "Dynamic Web Project" and enter the project name for "HelloWorldStruts2" to set additional options by referencing the figure below:
Struts2 Hello World example

Follow the figure below to select all the default options, and finally check the .xml the deployment descriptor option. T his will create a dynamic web project for you in Eclipse. Now click on "Windows", "Show", "View" and "Project Explorer" and you'll see your project window, as shown below:

Struts2 Hello World example
Now copy the following files from Struts2's lib folder C:\struts-2.2.3\lib to the project's WEB-INF\lib folder. You can drag and drop all the following files directly to the WEB-INF-lib folder.
  • commons-fileupload-x.y.z.jar
  • commons-io-x.y.z.jar
  • commons-lang-x.y.jar
  • commons-logging-x.y.z.jar
  • commons-logging-api-x.y.jar
  • freemarker-x.y.z.jar
  • javassist-x.y.z.GA
  • ognl-x.y.z.jar
  • struts2-core-x.y.z.jar
  • xwork-core.x.y.z.jar

Create an Aciton class

The Action class is the key to the Struts2 application, through which we implement most of the business logic. So let's create a java folder named "HelloWorldAction.java" under the class "Java Resources" and "src" and use a resource pack named "cn.w3cschool.struts2" that contains the following.
When the user clicks on a URL, the Action class responds to the user action. M ethods for one or more Action classes are executed and return a string result. Based on the value of the result, a specific JSP page is rendered.
package cn.w3cschool.struts2;

public class HelloWorldAction{
   private String name;

   public String execute() throws Exception {
      return "success";
   }
   
   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }
}
This is a very simple class with a "name" property. For the "name" property, we use the standard getter and setter methods, as well as an execution method that returns the "success" string.
The Struts2 framework creates an object for the HelloWorldAction class and calls the execute method in response to the user's actions. Y ou put your business logic into the execute method and end up with a string constant. Simply describing each URL, you need to implement an Action class, and you can also use the class name directly as your action name, or use the struts.xml file to map to other names as shown below.

Create a view

We need a JSP to present the final information, and when a predefined action occurs, the page is called by the Struts2 framework, and the image is defined in the struts .xml file. S o let's create the following JSP file HelloWorld in your Eclipse project's WebContent .jsp. Right-click on the WebContent folder in project explorer and select "New" and "JSP File".
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>Hello World</title>
</head>
<body>
   Hello World, <s:property value="name"/>
</body>
</html>
The Taglib directive tells the servlet container that this page will use Struts2 tags, and that these labels will be placed in front of the s. The s:property label shows the value of the Action class "name" property, which is returned using the getName() method of the HelloWorldAction class.

Create a home page

In the WebContent folder, we also need to .jsp index file, which is used as the initial action URL. By clicking on it, the user can command the Struts2 framework to call the definition method of the HelloWorldAction class and render a .jsp HelloWorld.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
   pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
   <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Hello World</title>
</head>
<body>
   <h1>Hello World From Struts2</h1>
   <form action="hello">
      <label for="name">Please enter your name</label><br/>
      <input type="text" name="name"/>
      <input type="submit" value="Say Hello"/>
   </form>
</body>
</html>
The hello action defined in the view file above .xml the HelloWorldAction class and its execute method through the struts and files. When the user clicks the submit button, the Struts2 framework runs the execute method in the HelloWorldAction class and selects an appropriate view to render as a response based on the return value of the method.

Profile

We need an image that links the URL, the HelloWorldAction class (model), .jsp helloWorld class (view). The image tells the Struts2 framework which class will respond to the user's actions (URLs), which method in the class will execute, and what the view will look like based on the string results returned by the method.
So let's create a file called struts .xml file. B ecause Struts2 requires the trust .xml file to appear in the classes folder, we're creating the struts file under the WebContent/WEB-INF/classes folder.xml file. E clipse doesn't create the classes folder by default, so you'll need to create it yourself. Right-click on the WEB-INF folder in project explorer and select "New" and "Folder" and your struts file .xml as follows:
<?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.devMode" value="true" />
   <package name="helloworld" extends="struts-default">
     
      <action name="hello" 
            class="cn.w3cschool.struts2.HelloWorldAction" 
            method="execute">
            <result name="success">/HelloWorld.jsp</result>
      </action>
   </package>
</struts>
Here are a few words about the above profile. H ere we set the value of constant struts.devMode to true because we are working in a development environment and need to look at some useful log messages. T hen we define a packet called helloworld. C reating a packet is useful when you want to bring your Actions together. I n our example, we named our action "hello", which is consistent with URL/hello.action and is backed up by HelloWorldAction .class the game. cute method is to run when URL/hello.action is called. If the execute method returns a result of "success," then we take the user to HelloWorld .jsp.
The next step is to create a web .xml file, which is an access point for any Struts2 request. I n the deployment descriptor (web .xml), the access point for the Struts2 application is defined as a filter. S o we'll .xml an access point for the org.apache.struts2.dispatcher.FilterDispatcher class in the web server, and the web.xml file needs to be created under WebContent's WEB-INF folder. E clipse has created a basic web .xml that you can use when you create a project. So, let's make the changes with reference to the following:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns="http://java.sun.com/xml/ns/javaee" 
   xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
   http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
   id="WebApp_ID" version="3.0">
   
   <display-name>Struts 2</display-name>
   <welcome-file-list>
      <welcome-file>index.jsp</welcome-file>
   </welcome-file-list>
   <filter>
      <filter-name>struts2</filter-name>
      <filter-class>
         org.apache.struts2.dispatcher.FilterDispatcher
      </filter-class>
   </filter>

   <filter-mapping>
      <filter-name>struts2</filter-name>
      <url-pattern>/*</url-pattern>
   </filter-mapping>
</web-app>
We have specified the index .jsp as our welcome file, then we have configured to run the Struts2 filter on all URLs (columns such as all the URLs that match /?modes).

Attention:

If it is a struts2-core-2.5 .jar, change the .xml class tag value in the web server to

<filter-class>

     org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter

</filter-class>

If it is a struts2-core-2.1.3 .jar, change the .xml class tag value in the web server to

<filter-class>

     org.apache.struts2.dispatcher.FilterDispatcher

</filter-class>

FilterDispatcher has not been recommended since Struts 2.1.3. If you are using an older version, the user is higher than the solution.

If it is a struts2-core-2.3.X .jar, change the .xml class tag value in the web server

<filter-class> 

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

</filter-class>

Enable detailed logs

By creating a logging.properties file under the WEB-INF/classes folder, you can enable full logging when using Struts 2. There are two lines to keep in the property file:
org.apache.catalina.core.ContainerBase.[Catalina].level = INFO
org.apache.catalina.core.ContainerBase.[Catalina].handlers = \
                              java.util.logging.ConsoleHandler

By default, log.properties specifies that a Console Handler sends logging to stdout and FileHandler along the specified route. The level threshold for program run logs can be used by SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINEST or ALL.

That way, we're ready to run our Hello World program using Struts 2.

Execute the application

Right-click on the project name, then click "Export" and "WAR File" to create a WAR file, and then deploy the WAR to Tomcat's webapps directory. Finally, starting the Tomcat server and attempting to access the URL http://localhost:8080/HelloWorldStruts2/index.jsp results as shown in the following image:

Struts2 Hello World example

Enter a "Struts2" value and submit the page, which you can see below

Struts2 Hello World example

Note that you can define an .xml as an action in the struts file so that you can call the index page http://localhost:8080/HelloWorldStruts2/index.action. See how indexes are defined as actions below:

<?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.devMode" value="true" />
   <package name="helloworld" extends="struts-default">

      <action name="index">
            <result >/index.jsp</result>
      </action>

      <action name="hello" 
            class="cn.w3cschool.struts2.HelloWorldAction" 
            method="execute">
            <result name="success">/HelloWorld.jsp</result>
      </action>

   </package>
</struts>