Friday 5 December 2014

global-results element


If action method returns a value, which is not matched to any result element names, then struts tries to find the result under <global-results> element. If any result name matches under <global-results> element, then specific page is displayed to client, else exception thrown.

Let’s say I updated the NumberCheckAction class by checking, if user enters zero, then it return string “zero”.

public class NumberCheckAction {
    private int number;
    private static String SUCCESS = "success";
    private static String FAILURE = "failure";
    private static String ZERO = "zero";

    public int getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
    }

    public String execute(){
        if(getNumber() == 0)
            return ZERO;
        if(getNumber() %2 == 0){
            return SUCCESS;
        }
        else{
            return FAILURE;
        }
    }
}

zero.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>zero</title>
    </head>
    <body>
        <h1>You entered zero, which is neither even nor odd</h1>
    </body>
</html>


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="default" extends="struts-default">

        <global-results>
            <result name="zero">zero.jsp</result>
            <result name="error">error.jsp</result>
        </global-results>
            
            
        <action name="numberCheck" class="NumberCheckAction">
            <result name="success">/success.jsp</result>
            <result name="failure">/failure.jsp</result>
        </action>

    </package>
</struts>



<global-results>
            <result name="zero">zero.jsp</result>
            <result name="error">error.jsp</result>
</global-results>

If the return string returned by action method is “zero”, then zero.jsp will be displayed to the client.





Prevoius                                                 Next                                                 Home

No comments:

Post a Comment