Request Processor is a simple object of org.apache.struts.action.RequestProcessor class which handles the HTTP specific request and response after getting the control from the ActionServlet by calling process().

Steps of Struts Request Processing flow :

1. Clicking on submit button from JSP page, container invokes the doPost() or doGet() method based on the type of action performed. 

2. Control go to the ActionServlet which delegates the request to the Request Processor by invoking process() method.

3.  Request Processor will check for the requested resource. 

4. If request resource in not available then give the error with HTTP Status code : 404 saying  "Requested Resource is not available ".

5. If available then Request Processor checks whether that resource contain any < html : form > tag or not. 

6. If that resource doesn't contain any < html : from > tag then corresponding resource i.e JSP will be displayed .

7. If it contains < html : form > tag with form elements then Request Processor takes the reqested URI mentioned in the action attribute of the < from > tag in JSP.

8. Request Processor checks whether any < action > tag is present in the struts-config file. If present then check for the URI is available in the path attribute of the < action > tag in the struts-config file.  

9. If no matching action is found then error message will be displayed with Http Status code: 500 saying cannot retrieve mapping for the following action . 

10. And if matching action found then Request Processor gets the value of the name attribute of the < action > tag .

11. Request Processor check for the name attribute of the < form-beam > tag contains the same value as the name attribute of the < action > tag.

12. If no matching action is found then error message will be displayed with HTTP Status code: 500 saying " cannot retrieve defination for the following form bean ".

13. If the matching form bean found then Request Processor get the form bean  type and do the following tasks:

       a) Loads the respective class.
       b) Create the object of the form bean class by calling the default constructor.
       c) Store the  object in the default scope i.e session using the setAttribute() .
       d) calls the reset() method.
       e) Collect the data from the form bean object and populate in the JSP field.   

14. Invokes the execute() method with the HTTP specific request and response. 

15. If it fails to execute successfully then Exception may be throw and must be handled by the Request Processor. 

16. If executed successfully then control will get back to the Request Processor by returning ActionForward object which is preformed by calling the findForward() method with the ActionMapping instance.

17. Request Processor identifies the JSP related to the ActionForward object returned by calling the findForward() or exception throws by the execute() method. 

18. And hence identified resource ( JSP ) will be displayed to the client. 


Note : Either returned ActionForward object or Exception any one can be handles by the Request Processor for the same action performed at a time. 




Action class must be configured in the struts-config.xml file so that container must have the information for which action it has to forward to which Action class. That's is why we are configuring the Action classes. For each action from the JSP page we are writing each Action class, previously in servlet we were writing Servlet class for each action performed but in Struts we are writing simple Action class but capable of handling HttpServletRequest and HttpServletResponse because of overriding execute() method.

We are writing each action in < action > tag under the < action-mapping > tag .

struts-config.xml 

<form-beans>

   <form-bean name="loginForm" type="com.def.Struts.LoginForm">
   </form-bean>

<form-beans>

<action-mappings>
  
      <action path="/loginSubmit"
  name="loginForm"
  type="com.def.Struts.LoginAction"
  input="/login.jsp"> 
    
         <forward name="success" path="/home.jsp"></forward> 
         <forward name="failed" path="/login.jsp"></forward>

     </action>
<action-mappings>

Each Action is configured with each < action > tag but under < action-mapping > tag . So we can have multiple action tag in a single < action-mapping > tag , depending upon the action configured.

< action > tag

There are total 12 attributes of < action > tag but we are discussing of only 4 attributes. They are :
1. path
2. name
3. type
4. input

path : It represents the relative-path of the submitted request and it must be unique , must starts with  / . It also must be same as we write in the action attribute under the < from > tag .

name : It is the logical name which is used t identifies the name of the form bean which is coupled with the action performed.

type : It contains the fully qualified name of the Action class which is used to perform the respective action of the relative-path mentioned in the path attribute.

input : It represents the relative-path of the input form to which control must be returned if validation error is encountered.

< form-bean > tag

Form-bean tag has two attribute i.e name and type .

name : Name attribute contains the same name as we write in the name attribute of the action tag so that form bean must be coupled with the action performed.

type : In the type attribute , there must be full qualified name of the form bean.



As ActionServlet is simple Servlet class only but designed using the Front Controller Design Patern so it must be configured in the web.xml file at the container itself only, so that every request must be followed by ActionServlet.

Web.xml file

<servlet>

  <servlet-name>login</servlet-name>

  <servlet-class>
     org.apache.struts.action.ActionServlet
  </servlet-class>
   
  <init-param>

   <param-name>config</param-name>
   <param-value>WEB-INF/struts-config.xml</param-value>

  </init-param>

  <load-on-startup>1</load-on-startup>

</servlet>
  
  <servlet-mapping>

   <servlet-name>login</servlet-name>
   <url-pattern>*.do</url-pattern>
  
  </servlet-mapping>

Here we have configured the ActionServlet class of org.apache.struts.action package under the servlet tag.

Why we are configuring ActionServlet at the container start-up ?

It is because first request handled by this servlet only then control will go to the RequestProcessor and then to our own Action class, so that we need not to design as many Servlet class for as many Actions. In Front Controller Design Pattern all the request get handled by only one servlet and once ActionServlet get initialized it is able to handle all the incoming request from the client machine. 

This is the also reason why we are mentioned load-on-startup value as 1 because it get initialized at the container start-up only. 

Why we hard-coded the "config" in the init-param tag ?

It is because config is also hard-coded in the init() method of the ActionServlet so that it can be able to get the name of the struts-config.xml file and able to parse and load to the main memory.   

Is struts-config.xml is fixed file name ?

No it in not a fixed name, we can have any name but need to configure in the param-value tag in the web.xml file. 

Why we have written *.do in the url-pattern ?

*.do indicate that for all the incoming request there is only servlet class i.e ActionServlet class. But we can have any suffix instead of .do .


We can write our own Action class using Struts framework but need to extends Action class of org.apache.struts.action package and need to override execute() method which return the ActionForward class object and which must be return by calling the findForward() method with ActionMapping reference and hence control will transfer to the caller i.e RequestProcessor.

Description about execute()

public ActionForward execute(ActionMapping mapping, ActionForm form,HttpServletRequest request, 
 HttpServletResponse response)throws Exception { 

    return mapping.findForward(result);

}

Caller of the execute() is RequestProcessor and return will also go the RequestProcessor. So by this we can confirm that after calling process() method by the RequestProcessor , now its the responsibility of the RespectProcessor to handle all the request of the client by calling execute() method.

execute() method is parametrized with ActionMapping , ActionForm , HttpServletRequest, HttpServletResponse reference.

Why ActionMapping ?

It is because findForward() method is implemented in the  ActionMapping class only and return ActionForward object.

Why ActionForm ?

It is because because before control comes to Action class it check the form bean class and hence its object has all the required value of the HTML form elements ( text field, checkboxes, drop down etc ).

Why HttpServletRequest ?

It is because to handle and process the request by the clients.

Why HttpServletResponse ?

It is because to send the response to the client after processing the request.

Note: Each Action class must be mapped in the struts-config file within action-mapping tag and hence need to also configure its from bean class.




All the Request by the client are get processed by the ActionServlet only then get forwarded to the Request Processor.
ActionServlet is a single Servlet designed by the Apache using Front Controller Design Pattern. It follows the life cycle of the Servlet  by calling init() method then doPost() or doGet() and finally destroy().

Internal Implementation of the ActionServlet
  
public class ActionServlet extends HttpServlet {

   RequestProcessor rp = null;

   public void init(ServletConfig sc){

init() method is parameterized with ServletConfig object which is used to collect the data mentioned in the xml file under the init-param tag.

   String file_name= sc.getInitParameter("config");

Hence we hard-code the value " config " in the xml file because it is hard-coded in the ActionServlet class as well. And by this it will get the name of the struts-config xml file.

Start parsing or reading the data from the struts-config xml file by using the SAX Parser and store the information in the main memory.

    rp= new RequestProcessor(); 

}

After initializing the ServletConfig object RequestProcessor get initialized and store the data parsed from the struts-config file into the RequestProcessor object.

public void doPost(HttpServletRequest,HttpServletResponse) {

   rp.process(request,response);

}

or

public void doGet(HttpServletRequest,HttpServletResponse) {

   rp.process(request,response);

}

Then doPost() or doGet() method will be called by passing the request and response object and in this method a process() method will be called by the RequestProcessor object by passing HttpServletRequest and HttpServletResponse so that the request will be processed by the RequestProcessor object only.


public void destroy(){

   }
}

Finally destroy method will be called.

Note: Once the ActionServlet class is initialized then it will be eligible to handle any request with the url-pattern mentioned as *.do or any thing . 

This is the reason why we are writhing like *.do means any request will be handled by the ActionServlet only. This is also called as Front Controller Design Pattern that means a single Servlet is responsible to handle all the incoming request. 





Following task are performed at the Container start-up in Struts based Application.
They are :

1. Container make sure about the web configuration file i.e web.xml whether is available or not.

2. If not available then Container will not be initialized and hence fails to start.

3. If available then Container will parse/read the web.xml file and store the required information in the main memory.

4. Then Container will create the ServletContext Object and initialized with the ServletContext parameter specified in the web.xml.

5.Thread Pool will be created which is responsible for threading the request by the clients. Each request is handled by each thread and after finishing back to the pool.

6. Configured ActionServlet will be initialized at the container start-up only with load-on-startup value as 1.

7. Then all the filters as initialized.

8. Finally all the Listeners will be initialized.



Note : org.apache.struts.action.ActionServlet are initialized at the container start-up only. It is implemented internally using the Front Controller Design Pattern. That means every request must followed through ActionServlet then to the respective designed Action class by the developers.







Steps to follow for developing Struts Application using Eclipse :-

We must have to follow some of the basic steps to develop any struts application using the Eclipse IDE.

1. Create Dynamic Web Project.

2. Copy all the 10 jars provided by the struts vendor to the WEB-INF/lib folder + 1 servlet-api.jar.

3. Copy all the 6 tld files to the WEB-INF folder ( not necessary )
    (Only when if developer want to use some pre-defined tags given by struts vendor in JSP page )

4. Copy struts-config.xml file to WEB-INF Folder. (struts-config is the default name,
                                                                                if we want we can change also ) .

5. Configure web.xml with "ActionServlet" class and init-param-value with " config "  and
     init-param-name with  " /WEB-INF/struts-config.xml " .

6. We need to create a form beam and a action class within a package named as " com.def.Struts ".

7. Now create a package  " com.def.Struts " under which place two java files.
     a) LoginForm.java ( Form bean class)       b) LoginAction.java (Action class )

8. Place one Properties file under " com.def.Struts " package which contain message regarding validation of        the form. ( message.properties  file ) --> Optional ( Only needed if validation is there ).

9. Mapping the struts-config file with action and form bean classes. How ?
    ( We will see in details later )

10. Now deploy the project and run successfully.

Files required for this simple Struts Project.

1. A Login jsp page ( login.jsp )
2. Login Success page ( home.jsp)
3. web.xml
4. struts-config.xml
5. LoginForm.java
6. LoginAction.java

login.jsp

<%@taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>

<html> 
<body>

<html:form action="/loginSubmit">

UserName: <html:text property="name"></html:text><br/>
Password: <html:password property="password"></html:password><br/><br/>
<html:submit>Login</html:submit>

</html:form>

</body>
</html>

home.jsp


<html>
<body>

    Logged in successfully and Welcome to your home page..!

</body>
</html>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns="http://java.sun.com/xml/ns/javaee" 
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
xsi:schemaLocation="http://java.sun.com/xml/ns/
javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
id="WebApp_ID" version="2.5">

  <display-name>Struts1</display-name>
 
<servlet>
  
  <servlet-name>login</servlet-name>
  <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
  <init-param>
   <param-name>config</param-name>
   <param-value>/WEB-INF/struts-config.xml</param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>

</servlet>
  
<servlet-mapping>

 <servlet-name>login</servlet-name>
   <url-pattern>*.do</url-pattern>

</servlet-mapping>
  
</web-app>


struts-config.xml


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//
DTD Struts Configuration 1.1//EN" "http://jakarta.apache.org/
struts/dtds/struts-config_1_1.dtd">

<struts-config>
    <form-beans>
 <form-bean name="loginForm" type="com.def.Struts.LoginForm"/>              </form-beans>
 
<action-mappings>
 <action path="/loginSubmit" 
  name="loginForm" 
  type="com.def.Struts.LoginAction" 
  input="/login.jsp">
    
 <forward name="success" path="/home.jsp"></forward>
 <forward name="failed" path="/login.jsp"></forward>
 </action>
 
</action-mappings>
    
</struts-config>

LoginForm.java

package com.def.Struts;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;

public class LoginForm extends ActionForm{
 
 private String name;
 private String password;
 
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public String getPassword() {
  return password;
 }
 public void setPassword(String password) {
  this.password = password;
 }
 
 
     public void reset(ActionMapping mp, HttpServletRequest req){
  
  this.name="java";
  this.password=null;
  
 }
}

LoginAction.java

package com.def.Struts;

import org.apache.struts.action.*;

import javax.servlet.http.*;

public class LoginAction extends Action{

 
public ActionForward execute(ActionMapping mp, ActionForm af,
  HttpServletRequest req, HttpServletResponse res)
   throws Exception {
  
 LoginForm lf=(LoginForm)af;
 String name=lf.getName();
 String pass=lf.getPassword();
 String result="";
 if(name.equals("sushant") && pass.equals("sushant")){
  result="success";
 }else{
  result="failed";
 }
    return mp.findForward(result);
  
 }
}





Most importantly Struts 1 is a web framework which is internally implemented using Servlet and JSP technologies.

This web framework is designed by Apache Software Foundation in 2001 keeping in view to reduce the task of the developer and maintenance issue which was much in Servlet.

Struts framework is implemented based
     -> MVC Architecture
     -> Front Controller Design Pattern
     -> Servlet & JSP.

Struts cover up the Controller and Presentation layer. In Controller layer internally Servlet is implemented using the Front Controller design pattern and for Presentation layer internally JSP is implemented with some tld files, by which developer can use some pre-implemented tags instead of writing java code in jsp page and hence reduce the java codes in jsp pages at the result enhance the maintenance issues. 

Struts Version

There are two versions released by Apache i.e
1. Struts 1.x  ( x = 0, 1, 2, 3)
2. Struts 2.0

Required jars of Struts 1 

There are 10 jars implemented by the Apache . They are :-

1.  commons-beanutils
2.  commons-collections
3.  commons-digester
4.  commons-fileupload
5.  commons-lang
6.  commons-logging
7.  commons-validator
8.  jakarta-oro
9.  struts
10. struts-legacy

And one more java we need to of servlet-api jar implemented by the web server vendors i.e
servlet-api .

Required Xml Files 

1. web.xml
2. struts-config.xml

Note: In struts-config.xml we are configuring form beans and action classes using form-beans and action-mapping tags respectively. 

In we.xml we are configuring the ActionServlet class which is implemented using the Front-controller design at the start-up of server and configuring struts-config.xml as the inti-param with the fixed inti-param name i.e config

* ActionServlet class is implemented by the Apache which is available in the org.apache.struts.action package.
Hibernate Transaction is associated with each operation we are performing within a session. We have to use org.hibernate.Transaction class to perform transaction in hibernate.

How Transaction object get initialized ?

As we know translation is associated with the session , so we can initialize Transaction using the beginTransaction() method which is a abstract method in Session interface and returns the Transaction object. 
After getting session object we need to call beginTransation()--->

Transaction tx = session.beginTransaction();

And after performing the operation using the session object in the database it needs to committed but in hibernate auto-commit is disable so we need to explicity commit the transation by using the following syntax,

tx.commit();

 Note: Transaction commit should be done before closing the session, otherwise it fails to commit. So commit must be done after performing any operation and before closing the session.

Important points regarding Transaction Object

1. It is not thread -safe that means any thread can access this object. So its better to close session after finishing the operation.

2. We can have single commit for multiple operation within a single session. So no need to create multiple Transaction object for each operation within a session. 

3. Must commit the database operation otherwise the operation doesn't reflect the changes in the database table and hence hibernate unable to perform the operation. 
In case of JDBC we the developer are responsible for establishing and terminating the database connection but in case of Hibernate, it is only responsible for establishing and terminating database Connectivity , we only need to indicate by simply calling some pre-defined method by the hibernate session. For ex-

After getting the SessionFactory which holds all the information about the database by reading the hibernate Configuration file, need to call the openSession() of SessionFactory interface which an abstract method and returns the Session instance.

Initializing Session instance creating the database Connection and opening the session which involves the database activity like insert,delete, update etc.

In hibernate
1 . Insert can be performed by calling save() method.
2.  Select can be performed by calling load() method. etc

How to create session In hibernate

1. Creating the SessionFactory instance.

SessionFactory factory=null;

Configuration cfg=new Configuration();

cfg=cfg.Configure();

factory=cfg.buildSessionfactory();

2. After creating Sessionfactory call openSession() method which returns the Session instance. Like this

Session session = factory.openSession();

By calling openSession() a session will be created and a session is responsible for performing a database operation. For multiple database operation we must have that much Session instance.

Note: Session is not a thread -safe that means as long as it is open it is in risk of accessible by other thread also so it must be closed after operation is over.

How to close session?
It can be simply closed by calling close() with Session instance. Like this

session.close(); 

States of Session Instance.

There are three states of instance of Session which behaves according to the persistence object creation. 

1. Transient: It is the initial state which represents that persistent class instance is not associated with any of the Session. That means it doesn't involve with any activity/operation with the database.

2. Persistent: It is the state of Session which represents that persistent class instance is associated with the Session and it has representation in the database and hence will be involved with the database activity/operation.

3. Detached: It is the final state of Session which represents that the Session is closed and hence persistent class instance get detached. 

Note: After Session creation Transaction creation is mandatory because we need to commit every operation/activity we are performing within the session. Otherwise changes will not reflect in the database. And by default auto-commit is disable or de-active so we need to commit explicitly for that we need to create transaction for each database operation. 

For details about Hibernate Transaction click here Hibernate Transaction .




Ads 468x60px

.

Ads

.

Featured Posts

Popular Posts

Like Us On FaceBook

Total Pageviews

Online Members

Live Traffic