As we discussed in earlier tutorials that any POJO class can be used as action class in struts 2. Only requirement is that it must have one no-argument method that returns a String or Result object. The execute() method is used by default if no-argument method is not there.
Example:
login.jsp
<%@ taglib uri="/struts-tags" prefix="s"%> <html> <head> <title>Struts 2 action example using POJO class.</title> </head> <body> <h3>This is an action example using POJO class.</h3> <s:property value="message" /> <br/> <s:form action="Login"> <s:textfield name="userName" label="UserName" /> <s:password name="password" label="Password" /> <s:submit value="login" align="center"/> </s:form> </body> </html> |
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <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> <welcome-file-list> <welcome-file>login.jsp</welcome-file> </welcome-file-list> </web-app> |
struts.xml
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <package name="user" extends="struts-default"> <action name="Login" class="com.w3schools.action.Login"> <result name="success">/welcome.jsp</result> <result name="error">/login.jsp</result> </action> </package> </struts> |
Login.java
/** * This class is used as an action class. * @author w3schools */ public class Login { //data members private String userName; private String password; private String message; //business logic public String execute(){ if(userName.equals("jai") && password.equals("1234")){ setMessage("Hello " +userName + "," + " You are successfully logged in."); return "success"; }else{ setMessage("Invalid username or password."); return "error"; } } //getter setters 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; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } } |
welcome.jsp
<%@ taglib uri="/struts-tags" prefix="s"%> <html> <head> <title>Struts 2 action example using POJO class.</title> </head> <body> <h3>This is an action example using POJO class.</h3> <s:property value="message" /> </body> </html> |
Output:
Enter UserName: jai , Password: 1234
Click on login button.
Download this example.
Next Topic: Action in struts 2 by implementing Action interface with example.
Previous Topic: Action in struts 2.