Why do we need global-forwards and global-exceptions in struts?

user1900662 picture user1900662 · Dec 13, 2012 · Viewed 21.2k times · Source

I have a basic question in struts why do we need to have <global-forwards>and <global-exceptions> in struts-config.xml. If we can achieve the same things with <action-mappings> itself.

Answer

OCJP picture OCJP · Dec 13, 2012
<global-forwards>

Consider you are validating the username password for different urls like update.do, insert.do delete.do etc. If it is a valid user you need to proceed the neccesary action.if not forward to the login page.See the mappings below

<action-mappings>        
    <action path="/insert" type="controller.Insert">
        <forward name="success"  path="/insert.jsp"/>
        <forward name="failure"  path="/login.jsp"/>
    </action>     
    <action path="/update" type="controller.Update">
        <forward name="success"  path="/update.jsp"/>
        <forward name="failure"  path="/login.jsp"/>
    </action>
    <action path="/delete" type="controller.Delete">
        <forward name="success"  path="/delete.jsp"/>
        <forward name="failure"  path="/login.jsp"/>
    </action>        
</action-mappings>

Instead of repeating the <forward name="failure" path="/login.jsp"/> you can declare this in <global-forwards> like below

 <global-forwards>
   <forward name="failure"  path="/login.jsp"/>
</global-forwards>

Now you can remove the <forward name="failure" path="/login.jsp"/> in the action mappings.


<global-exceptions>

If you receive java.Io exception instead of handling manually for each you can declare globally as below.

<global-exceptions>
    <exception type="java.io.IOException" path="/pages/error.jsp"/>
</global-exceptions>

I hope this clarifies your problem.