Moving on to struts2 Action classes.
The Greeting Application.
When a request comes to the container, it checks web.xml to decide how it should be dispatched. Here is the web.xml for our “Greeting” Application
Struts2 Test
struts2
org.apache.struts2.dispatcher.FilterDispatcher
struts2
/*
index.html
On line numbers 3-6 , we are enabling struts2 filter. We map this filter to all urls on line numbers 7 through 10.ie all requests are passed through struts2 FilterDispatcher. The dispatcher looks in to the struts2.xml file for any matching mappings. Here is our struts2.xml.
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
helloWorld.jsp
/greet.jsp
line # 6-8 creates the HelloWorld Action (HelloWorld.action), that we used in the previous example. But we didn't give any class attribute to the action tag. if no class is defined for an action, struts assumes the action returns “SUCCESS”. We 'll discuss about the return values later. The Greeting action (Greet.action) is configured on line # 9 through 11. In this case we are giving a class attribute, meaning , we are going to create our own class for this action.
Now Let's try creating a struts2 Action class. Usually we sub class ActionSupport for creating our own Action class. Here is the code.
package org.techienet.tutorials.struts2.helloworld;
import com.opensymphony.xwork2.ActionSupport;
@SuppressWarnings("serial")
public class Greet extends ActionSupport {
private String message =null;
public String execute() throws Exception {
setMessage("Welcome to Struts2 Actions !");
return "greet";
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
When struts finds “class” attribute for an action mapping, it create an instance of the class, and invokes it's execute method. In our action class we have one property apart from the execute method. In the execute method we are setting this property, to the greeting message. We can access this property from the jsp file using the tag library suplied by the struts2 package.
Note the value that we are returning from the execute method. it's the string "greet" !!!. On line number 10 of the struts2.xml we are configuring a result with the same name. that's what is telling struts to pick up the file "/greet.jsp" and merge it to the response.
Pretty Simple , Eh ?
Here is our "/greet.jsp".
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
Insert title here
Hello World ! , through Action ...
manning
action class