Struts Tutorial for Beginners | DevsDay.ru

IT-блоги Struts Tutorial for Beginners

DigitalOcean Community Tutorials 3 августа 2022 г. Pankaj


Welcome to Struts Tutorial for Beginners. Struts is one of the oldest frameworks to build **[Java Web Application](/community/tutorials/java-web-application-tutorial-for-beginners "Java Web Application Tutorial for Beginners")**. ## Struts Tutorial [![struts tutorial, struts 2, struts 2 tutorial, struts2](https://journaldev.nyc3.digitaloceanspaces.com/2013/09/struts-tutorial.png)](https://journaldev.nyc3.digitaloceanspaces.com/2013/09/struts-tutorial.png) Struts was the initial implementation of MVC design pattern and it has evolved a lot along with latest enhancements in Java, Java EE technologies. Struts tutorial article is aimed to provide basic details of Struts 2 and how we can create our first "Hello World" Struts 2 application. ### Struts 2 Apache Struts 2 is an open source, industry standard, flexible and extendable framework to build Java EE web application. Struts 2 is based on **OpenSymphony WebWork framework**. Struts 2 is very flexible in terms of development and configurations and we will see how easy it is to develop a web application using Struts 2 framework. ### Struts 2 Architecture Diagram Below diagram shows different component of Struts 2 in a web application. [![Struts 2 Architecture Diagram](https://journaldev.nyc3.digitaloceanspaces.com/2013/09/Struts-2-Architecture-Diagram-450x251.png)](https://journaldev.nyc3.digitaloceanspaces.com/2013/09/Struts-2-Architecture-Diagram.png) ### Struts 2 Interceptors **Struts Interceptors** are like [Servlet Filters](/community/tutorials/java-servlet-filter-example-tutorial "Java Servlet Filter Example Tutorial") that executes before and after the request is being processed. They are used to perform common operations for different actions. For example logging, session validation, adding common headers to response etc. ### Struts 2 ValueStack and OGNL **ValueStack** is the storage area where the application data is stored by Struts 2 for processing a client request. The data is stored in `ActionContext` objects that use [**ThreadLocal**](/community/tutorials/java-threadlocal-example) to have values specific to the particular request thread. **Object-Graph Navigation Language** (OGNL) is a powerful Expression Language that is used to manipulate data stored on the ValueStack. As you can see in architecture diagram, both interceptors and result pages can access data stored on ValueStack using OGNL. ### Struts 2 Action Struts 2 Action components handle the client requests. Struts 2 provides different ways to create Action classes. 1. By implementing `com.opensymphony.xwork2.Action` interface. 2. By extending `com.opensymphony.xwork2.ActionSupport` class. Usually it's used to create empty action classes to forward request to another resource. 3. Annotating a class with @Action or @Actions annotation. 4. Following naming convention for classes, name should end with _Action_ and should have execute() method. ### Struts 2 Result Result components are usually JSP or HTML pages to create view for client response. Struts 2 provides their own tags that we can use in JSP pages to create response. Struts tags are great example of **[JSP Custom Tags](/community/tutorials/jsp-custom-tags-example-tutorial "JSP Custom Tags Example Tutorial")**. ### Struts 2 Declarative Architecture and Wiring Struts 2 provides two ways to configure our application for action classes and result pages. 1. **Struts XML File**: We have **struts.xml** file in WEB-INF/classes directory where we can configure our application action classes and result pages. 2. **Annotation**: We can use **[Java Annotations](/community/tutorials/java-annotations)** to provide metadata information about a class. Struts 2 convention plugin can be used to annotate java classes with @Action and @Result annotations to create configure action classes and associated result pages. Whichever way we use to configure our application, the end result will always be the same. ## Struts Tutorial - Hello World XML Based Application Let's see how we can create our first Struts 2 Hello World application. First of all we need is Struts 2 jar files, the easiest way is to download it from [Struts 2 Official Downloads page](https://struts.apache.org/download.cgi). But when you will check out the libs in the downloaded archive, you will see a lot of jar files that we don't need for our simple application. So I will create a **maven project** and add struts-core dependency only, all the other transitive dependency jars will be automatically downloaded and added to the application. Our final project structure will be like below image. [![Struts tutorial, struts 2 Hello World](https://journaldev.nyc3.digitaloceanspaces.com/2013/09/Struts-2-Hello-World-Project-390x450.png)](https://journaldev.nyc3.digitaloceanspaces.com/2013/09/Struts-2-Hello-World-Project.png) Create a new **Dynamic Web Project** Struts2XMLHelloWorld in Eclipse and then convert it to maven project like below image. [![Eclipse Convert Dynamic Web Application To Maven Project](https://journaldev.nyc3.digitaloceanspaces.com/2013/09/Convert-Dynamic-Web-Application-To-Maven-Project-450x431.png)](https://journaldev.nyc3.digitaloceanspaces.com/2013/09/Convert-Dynamic-Web-Application-To-Maven-Project.png) You will notice pom.xml file is added in the root directory of the project. Our project setup in Eclipse is ready, let's look at the different components in order. ### pom.xml Open pom.xml file and add struts core dependency, the final pom.xml will look like below. ``` 4.0.0 Struts2XMLHelloWorld Struts2XMLHelloWorld 0.0.1-SNAPSHOT war org.apache.struts struts2-core 2.3.15.1 src maven-compiler-plugin 3.1 1.6 1.6 maven-war-plugin 2.3 WebContent false ${project.artifactId} ``` Notice that I have overridden `finalName` element to avoid version number getting added in the WAR file when we do maven build. Other parts are added by Eclipse itself, the only dependency we need is struts2-core whose current version is 2.3.15.1 (as of 10-Sep-2013). Just do maven build of the application and you will see a lot of jars added to the application lib directory and shown in Maven Dependencies section of the project like below image. [![Struts 2 maven dependencies, struts tutorial](https://journaldev.nyc3.digitaloceanspaces.com/2013/09/Struts2-maven-dependencies.png)](https://journaldev.nyc3.digitaloceanspaces.com/2013/09/Struts2-maven-dependencies.png) ### Struts 2 web.xml configuration We need to add `org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter` filter to the web application and provide the URL pattern where we want Struts to take care of the client request. Our web.xml looks like below; ``` Struts2XMLHelloWorld struts2 org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter struts2 /* ``` For Struts 2 version below 2.1.3, the filter-class was `org.apache.struts2.dispatcher.FilterDispatcher`. ### Struts Tutorial - Result Pages We have three JSP pages that will be used by the application, we are using Struts 2 tags to create our JSP pages. `login.jsp` ``` <%@ page language="java" contentType="text/html; charset=US-ASCII" pageEncoding="US-ASCII"%> <%-- Using Struts2 Tags in JSP --%> <%@ taglib uri="/struts-tags" prefix="s"%> Login Page

Welcome User, please login below

``` Notice the form field names are _name_ and _pwd_, we will see how they are used in Action classes. `welcome.jsp` ``` <%@ page language="java" contentType="text/html; charset=US-ASCII" pageEncoding="US-ASCII"%> <%@ taglib uri="/struts-tags" prefix="s"%> Welcome Page

Welcome

``` Notice the struts tag s:property that we can use to get request attributes, the name is same as in login.jsp. `error.jsp` ``` <%@ page language="java" contentType="text/html; charset=US-ASCII" pageEncoding="US-ASCII"%> <%@ taglib uri="/struts-tags" prefix="s"%> Error Page

User Name or Password is wrong

``` This is a simple JSP page where we are adding error message and including login page in response. ### Struts Tutorial - Action Classes Our application has only one Action class where we are implementing Struts 2 Action interface. `LoginAction.java` ``` package com.journaldev.struts2.action; import com.opensymphony.xwork2.Action; public class LoginAction implements Action { @Override public String execute() throws Exception { if("pankaj".equals(getName()) && "admin".equals(getPwd())) return "SUCCESS"; else return "ERROR"; } //Java Bean to hold the form parameters private String name; private String pwd; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } } ``` Notice the action class is also a java bean with same variables as login.jsp and their getter and setter methods. Struts will take care of mapping the request parameters to the action class variables. ### Struts Tutorial - Configuration File Since we are using XML based configuration for wiring our application, we need to create Struts configuration file that should be named as **struts.xml** and inside **WEB-INF/classes** directory. `struts.xml` ``` /login.jsp /welcome.jsp /error.jsp ``` For action "home", there is no Action class and only one result, so request will be forwarded to the login.jsp page. For action "login", LoginAction is the action class and if execute() method returns "SUCCESS" the request will be processed by welcome.jsp and for "ERROR" it will be forwarded to error.jsp page. namespace="/User" is important and used in URL to access the action classes, it's provided to create different modules. So we can access our application with URL `https://localhost:8080/Struts2XMLHelloWorld/User/home.action`. Notice that URL is ending with **.action** that is the default suffix for Struts 2 action like it is **.do** for Struts 1. ### Struts Tutorial - Struts 2 Hello World Test When we run our application, we get following response pages. [![Struts tutorial Hello World XML login](https://journaldev.nyc3.digitaloceanspaces.com/2013/09/Struts-Hello-World-XML-login-450x198.png)](https://journaldev.nyc3.digitaloceanspaces.com/2013/09/Struts-Hello-World-XML-login.png) [![Struts tutorial Hello World XML Home](https://journaldev.nyc3.digitaloceanspaces.com/2013/09/Struts-Hello-World-XML-Home-450x136.png)](https://journaldev.nyc3.digitaloceanspaces.com/2013/09/Struts-Hello-World-XML-Home.png) [![Struts 2 tutorial Hello World XML Error](https://journaldev.nyc3.digitaloceanspaces.com/2013/09/Struts-Hello-World-XML-Error-450x235.png)](https://journaldev.nyc3.digitaloceanspaces.com/2013/09/Struts-Hello-World-XML-Error.png) [Download Struts2 Hello World Example Project](https://journaldev.nyc3.digitaloceanspaces.com/struts2/Struts2XMLHelloWorld.zip) Thats all for Struts 2 beginners tutorial, check out next article we are using annotations to create [Struts 2 Web Application](/community/tutorials/struts-2-hello-world-example-with-annotations-and-without-struts-xml-file "Struts 2 Hello World Example with Annotations and without struts.xml file") without using struts.xml configuration file.

Источник: DigitalOcean Community Tutorials

Наш сайт является информационным посредником. Сообщить о нарушении авторских прав.