Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 225
user1900662 Avatar asked Dec 13 '12 10:12

user1900662


2 Answers

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

like image 84
OCJP Avatar answered Nov 15 '22 18:11

OCJP


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

like image 37
Sergio Nakanishi Avatar answered Nov 15 '22 18:11

Sergio Nakanishi