Struts 2.x : [A Framework from ASF] :: Struts 2.x with HelloWorld Example
Struts with HelloWorld |
Here i have tried to create one index page that contains one input field where user can enter name and if this name match with the name that i have checked in action class; will return welcome.jsp else it will return failure.jsp.
Example |
Struts 2.x HelloWorld Application Example
Project Structure
Customer.java
package com.javaskool;
public class Customer {
String cname;
public String getCname() {
return cname;
}
public void setCname(String cname) {
this.cname = cname;
}
public String execute()
{
if(cname.equals("james"))
{
return "success";
}
else
{
return "failure";
}
}
}
index.jsp
<%@ taglib prefix="s" uri="/struts-tags" %>
<h1>Welcome to Struts 2.3</h1>
<s:form action="xyz">
<s:textfield name="cname" label="Enter Name :"></s:textfield>
<s:submit value="Click Here" />
</s:form>
welcome.jsp
<%@ taglib prefix="s" uri="/struts-tags" %>
Welcome Mr. <s:property value="cname"/>
failure.jsp
<%@ taglib prefix="s" uri="/struts-tags" %>
Hi Mr. <s:property value="cname"/> , Your name doesn't match with our records.
struts.xml
<?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>
<package name="x" extends="struts-default">
<action name="xyz" class="com.javaskool.Customer" method="execute">
<result name="success">/welcome.jsp</result>
<result name="failure">/failure.jsp</result>
</action>
</package>
</struts>
jar files required in lib folder
Note: List of jar files differ as per project
commons-fileupload-1.2.2
commons-io-2.0.1
commons-lang-2.4
commons-lang3-3.1
commons-logging-1.1.1
commons-logging-api-1.1
freemarker-2.3.19
javassist-3.11.0.GA
ognl-3.0.5
struts2-core-2.3.4
xwork-core-2.3.4
Click Here to download all jar files required for basic Struts 2.x Application
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" 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>02_FirstStruts2WebAppl</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>f3</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>f3</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
Output
If you enter any other name than “tom”, will return below screen.
Click here to download complete code with jar files [3.8 MB]
Recent Comments