Simple Hello world example to show how to run a struts 2 application in eclipse and tomcat
Step 1:
Create an html file and design a simple form using struts tag lib
<%@ taglib prefix="s" uri="/struts-tags"%> <html> <body> <h4> <u>Struts2 Hello World Example</u> </h4> <s:form action="hello" > <s:textfield name="uname" label="Enter Username"/> <br> <s:password name="pass" label="Enter Password" /> <br> <s:submit value="Sign In" align="center" /> </s:form> <br> </body> </html>
Step 2:
Configure your web.xml file to map all request to Struts built in filter StrutsPrepareAndExecuteFilter
<?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_2_5.xsd" id="WebApp_ID" version="2.5"> <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> </web-app>
Step 3:
Create struts.xml file in src directory(default location to keep your struts configuration file)
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <package name="default" extends="struts-default"> <action name="hello" class="com.candidjava.controller.HelloWorld"> <result name="success">/success.jsp</result> </action> </package> </struts>
Step 4:
Create an Controller class that extends ActionSupport and override execute method init.
package com.candidjava.controller;
import com.opensymphony.xwork2.ActionSupport;
public class HelloWorld extends ActionSupport{
private static final long serialVersionUID = 1L;
private String uname;
private String pass;
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
public String execute()
{
System.out.println(uname);
System.out.println(pass);
return "success";
}
}
<%@ taglib prefix="a" uri="/struts-tags" %> Properties binded in Struts controller can be retrived in view pages. <br> Welcome <b><a:property value="uname"/>,</b><br/> Thanks for visiting candidjava.com...
Screenshot
Download
Struts 2 hello world example war
Struts 2 hello world example maven zip