12

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.

user1900662
  • 299
  • 1
  • 7
  • 26

2 Answers2

39

<global-forwards>

Consider you are validating the username password for different urls like

  • update.do
  • insert.do
  • delete.do

If it is a valid user, you need to proceed the necessary action. If not, you need to forward to the login page. Without a global forward, you must add a login form mapping form to every action:

<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>

When 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.

Ian Boyd
  • 246,734
  • 253
  • 869
  • 1,219
OCJP
  • 1,033
  • 1
  • 10
  • 17
  • thanks for the explanation, let say if there is HTTP 500 error page and need to forward back to login page, , how this can be done, thanks – Apache Jun 17 '13 at 10:14
  • 9
    I have to disagree with user1900662 - this is the perfect length, imo. It answered my question exactly (and was the first result in google so I imagine i'm not the only one...) – corsiKa Dec 30 '13 at 16:13
4

If you are talking about Struts 1, global-exceptions are ExceptionHandlers that deals with some Exception for all the actions, so you don't have to declare it per action and avoid duplication.

Global-forwards have the same idea. If you have forwards with the same path in different actions, you can avoid duplication by declaring just one global-forward and all the actions can use it. With global-forwards you can also avoid hard-coded URLs in your jsps, eg, you could declare a global-forward like <forward name="loginLink" path="/login" /> and then in your jsp <html:link forward="loginLink">Login</html:link>.

Pablo Lozano
  • 10,122
  • 2
  • 38
  • 59