Hi in this tutorial we will discuss about the Hello World Struts 2 Application, there are the following minimum technical requirements for this Hello World Application.
Before we starts with our first Hello World Struts 2 Example, we will need few tools.
Following are the list of JAR files required for this application.
Note that depending on the current version of Struts2, the version number of above jar files may change.
Here we want 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 “Hello Welcome , <username>…! Dineshonjava.com“. If user is not authenticated, she will be redirected back to the login page.
In the previous chapter we already set up the struts 2 in the eclipse or STS Now lets review the final project structure of this tutorial, in case you get lost in later steps.
As discussed in the previous article, 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.
web.xml
<?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>Struts2MyFirstApp</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.
Action class is the key to Struts 2 application and we implement most of the business logic in action class. So let us create a java file LoginAction.java under Java Resources > src with a package name com.dineshonjava.struts2.login with the contents given below.
The Action class responds to a user action when user clicks a URL. One or more of the Action class’s methods are executed and a String result is returned. Based on the value of the result, a specific JSP page is rendered.
LoginAction.java
package com.dineshonjava.struts2.login; import com.opensymphony.xwork2.ActionSupport; /** * @author Dinesh Rajput * */ @SuppressWarnings("serial") public class LoginAction extends ActionSupport{ private String username; private String password; public String execute() { if (this.username.equals("dinesh") && this.password.equals("sweety")) { 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; } }
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 “dinesh” and password is “sweety“.
Also note that unlike Action class in Struts1, Struts2 action class is a simple POJO class with required attributes and method.
Note: 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 doAuthenticate() instead.
We need a JSP to present the final message, this page will be called by Struts 2 framework when a predefined action will happen and this mapping will be defined in struts.xml file. So let us create the below jsp file Login.jsp and Welcome.jsp in the WebRoot folder in your eclipse project. To do this, right click on the WebRoot folder in the project explorer and select New >JSP File.
Login.jsp
<%@ page contentType="text/html; charset=UTF-8"%> <%@ 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> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Struts 2 - Login Application | dineshonjava.com</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"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Welcome</title> </head> <body> <h2>Hello Welcome , <s:property value="username" />...! Dineshonjava.com</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.
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 myapp.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 myapp.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.
myapp.properties
label.username= Username label.password= Password label.login= Login error.login= Invalid Username/Password. Please try again.
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 myapp.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.
We need a mapping to tie the URL, the LoginAction class (Model), and the Login.jsp (the view) together. The mapping tells the Struts 2 framework which class will respond to the user’s action (the URL), which method of that class will be executed, and what view to render based on the String result that method returns.
So let us create a file called struts.xml. Since Struts 2 requires struts.xml to be present in classes folder. So create struts.xml file under the WebRoot/WEB-INF/classes folder. Eclipse or STS does not create the “classes” folder by default, so you need to do this yourself. To do this, right click on the WEB-INF folder in the project explorer and select New > Folder.
Your struts.xml should look like:
<?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="myapp" /> <package name="default" extends="struts-default" namespace="/"> <action name="login" class="com.dineshonjava.struts2.login.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 (myapp 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. doAuthenticate(); then we should specify the method name in <action> tag.
<action name="login" method="doAuthenticate" class="com.dineshonjava.struts2.login.LoginAction"> <result name="success">Welcome.jsp</result> <result name="error">Login.jsp</result> </action>
Right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat’s webapps directory. Finally, start Tomcat server and try to access URL
http://localhost:8080/doj/Login.jsp. This will give you following screen:
Fill username “dinesh” and password “sweety” and submit then go to welcome page.
http://localhost:8080/doj/login.action
If you put wrong username and password then return error login page with validation message.
Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…
Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…
Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…
Technology has emerged a lot in the last decade, and now we have artificial intelligence;…
Managing a database is becoming increasingly complex now due to the vast amount of data…
Overview In this article, we will explore Spring Scheduler how we could use it by…