<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Struts2 Application</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>
Code language: HTML, XML (xml)
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. Note: The FilterDispatcher
filter is deprecated since Struts version 2.1.3. If you are using latest version of Struts2 ( > 2.1.3) use StrutsPrepareAndExecuteFilter
class instead. <filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Code language: HTML, XML (xml)
package net.viralpatel.struts2;
public class LoginAction {
private String username;
private String password;
public String execute() {
if (this.username.equals("admin")
&& this.password.equals("admin123")) {
return "success";
} else {
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;
}
}
Code language: Java (java)
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 admin and password is admin123. Also note that unlike Action class in Struts1, Struts2 action class is a simple POJO class with required attributes and method. 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 authenticate() instead. Code language: HTML, XML (xml)label.username= Username label.password= Password label.login= Login
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Struts 2 - Login Application | ViralPatel.net</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>
Code language: HTML, XML (xml)
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Welcome</title>
</head>
<body>
<h2>Howdy, <s:property value="username" />...!</h2>
</body>
</html>
Code language: HTML, XML (xml)
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. <?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="ApplicationResources" />
<package name="default" extends="struts-default" namespace="/">
<action name="login"
class="net.viralpatel.struts2.LoginAction">
<result name="success">Welcome.jsp</result>
<result name="error">Login.jsp</result>
</action>
</package>
</struts>
Code language: HTML, XML (xml)
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 (ApplicationResources 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. authenticate(); then we should specify the method name in <action>
tag. <action name="login" method="authenticate"
class="net.viralpatel.struts2.LoginAction">
Code language: HTML, XML (xml)
Also 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 ApplicationResources.properties file. We must specify key error.login in LoginAction and the message should be displayed on JSP page. For this we must implementCode language: HTML, XML (xml)label.username= Username label.password= Password label.login= Login error.login= Invalid Username/Password. Please try again.
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. The final code in LoginAction must look like: package net.viralpatel.struts2;
import com.opensymphony.xwork2.ActionSupport;
public class LoginAction extends ActionSupport {
private String username;
private String password;
public String execute() {
if (this.username.equals("admin")
&& this.password.equals("admin123")) {
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;
}
}
Code language: Java (java)
And that’s it. Our first Hello World Struts2 Application is now ready. Java URL Encoder/Decoder Example - In this tutorial we will see how to URL encode/decode…
Show Multiple Examples in OpenAPI - OpenAPI (aka Swagger) Specifications has become a defecto standard…
Local WordPress using Docker - Running a local WordPress development environment is crucial for testing…
1. JWT Token Overview JSON Web Token (JWT) is an open standard defines a compact…
GraphQL Subscription provides a great way of building real-time API. In this tutorial we will…
1. Overview Spring Boot Webflux DynamoDB Integration tests - In this tutorial we will see…
View Comments
Nice work dude .... keep it up... :) .. write some good post regarding PHP-MySQl also
Hi Gaurav, Thanks a lot for comment. I will sure try to write something on that too.
yes VIRal very good work nice approach followed.................
still there is one problem viral when i am running the application it is showing http 404 error
please reply dear
@atif, have you specified welcome file in your web.xml? Please specify Login.jsp as welcome file in web.xml.
ya i have given the welcome file as login.jsp and the problem has been sorted out when i used tomcat 6.X
thanks for the reply
hi i implemented all d codes given above but when i start the server it gives
HTTP Status 404 -
--------------------------------------------------------------------------------
type Status report
message
description The requested resource () is not available.
@jawahar - Can you check if following code is present in your web.xml file.
I too have the same problem and i have the \
Login.jsp
/ too .. @Viral Patel
Also check if there is an action class specified in your struts.xml
Fo eg
/index.jsp
Here index.jsp is the first page. Try this had an similar error. It got resolved by this
ya its there viral and don know why its not coming..........
ya i checked its there but its not coming yar......
ya viral its there but its not coming...........
@jawahar - I will suggest you to check the source code properly. Download the source code of above tutorial and try to run it and see if everything is working well.
i recreated the project again it run successfully ...........i think some were went wrong.........great work yarrrrrr.........keep.......up the tempo...........
i have one doubt viral the following code in Login.jsp .........
y we put login.action .....y i m asking this ? means in struts.xml we mentioned name as "login" only thats y.