Wednesday 21 August 2013

Top Most Struts1 vs. Struts2 – Difference between Struts1 and Struts2


What is the difference between Struts1 and Struts2?
I believe its very important to understand the difference, even if you are not working on Struts.
Struts2 architecture, design, and flow is probably the best among all web application frameworks today.
You might work for few years and then design an excellent framework, and most probably it would be Struts, or if much better than it would be Struts2.
I am going to continue explore the Struts and Struts2 within few posts.
but starting with some very basic difference between Struts1 and Struts2. Because those who are familiar with Struts1, must know these basic difference, which is big difference in architecture and framework.
Web.xml configuration changes.                                                                   
 Struts1.                                       ActionServlet was the concrete controller for an application.The Controller was responsible for intercepting and translating the User Input into Actions to be performed by the model.                  
 Struts2                                       FilterDispatcher executes action by consulting the ActionMapper and determining if the requested URI should invoke action. If mapper indicates proper action is invoked.      Filter also serves common static content.                           
  Configuration file Changes:                                                               
  Struts1                                                There was struts-config.xml.Configuration file is listed as initialization parameter to the action servlet in web.xml.  Parameter can be extended to specify multiple config initialization parameter.                                                               
 Struts2                                                     We have struts.xml.There is no initialization parameter for struts.xml. struts.xml needs to be in the class path. Struts.xml has file inclusion facility.                                                 
Namespace separation between Struts Action                                                                
Struts1                                                                   .do                                                                
Struts2                                                                .action.
A difference in the action, also means that Strusts1 and Struts2 can both co extst within the same application.  Which also means actions are the good point to strat the migration from Struts1 to Struts2.
Now, those who have worked over Struts, and those who are aware of the Action classes in Struts, for them there is a big diff. between Struts1 action and Struts2 action:

Struts1
All Actions have to extend the Action class. Single Action instance is created. So, all actions have to thread safe. Action has to be thread safe, so all objects are passed as parameter.The name of the first method that is invoked for the processing of action, must be execute(), however DispatchAction class can be used to re-route the action to different method within the same action.Return of the execute() method is ActionForward, generated using the methods of the ActionMapping class.                                                                         
Struts2
Action class doesn’t need to extend any class or interface.An action instance is created for each request. Its not shared and its discarded after the request has been completed.Its not mandatory to have the method name as execute(). Any method with proper signature can be invoked through configuration.No objects as parameters are passed to the method. Objects are available to the method using Dependency Injection.Return object of the method is String. Helper interface Action is available for String constants like: “success”, “error”, etc.
The difference in the Action classes also leads to one confusion, of how is the HttpServletRequest, request parameters, Mappings, etc. available to the Action class in the Struts2.
A sample Action class in Struts1 was something like:
public class RemoveEntryAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
Service service = new Service();
String id = request.getParameter(“id”);
service.delete(Integer.parseInt(id));
return (mapping.findForward(“success”));
}
}
As we can see that id is fetched from the request. Service is a Service class or it can be a facade.
RemoveEntry is one action, Similarly we would have multiple Action classes for different actions.
Actions like making new entry, updating entries, finding entries, etc.
And all the action classes related the Entry would be similar, in the sense, all would retrieve id from the HttpServletRequest, instantiate Service, and call some method of the Service class.
This is how things were in Struts1.
In Struts2, since a new object would be created for each request, we can have class level variables, we can have some setter methods, and above all we can write all the actions within the same class.
So, we can have a class level variable like Service( for Service class), and id( for id retrieved from HttpServletRequest), we can have setter methods for these class level variables.
Assume, we want to write the Action class like this:
public class EntryAction {
private int id;
private Entry entry;
private Service service = new Service();
private HttpServletRequest request;
public void setServletRequest(HttpServletRequest httpServletRequest) {
this.request = httpServletRequest;
}
public void setId(int id) { this.id = id; }
public void prepare() throws Exception {
if( id==0 ) { entry = new Entry(); }
else { entry = service.findById(id); }
}
public Object getModel() { return entry; }
public String save() { service.create(entry); return SUCCESS; }
public String update() {
service.update(entry);
request.setAttribute(“entry”,entry);
return SUCCESS;
}
public String remove() {
service.delete(id); return SUCCESS;
}
public String execute() {
request.setAttribute(“entry”,entry);
return SUCCESS; }
}
But the whole idea would be defeated, and we wont be achieving anything if we are going to call the setters.
When new instance should be created for each request, then variables should be set automatically, possibly by the container. And this is how it should be. And this is how it is done.
And this is where Dependency Injection comes in.
To use dependency injection, we need to implement several interfaces.
In fact, what all features we need, we need to implement corresponding interfaces.
To make our Action class to be HttpServletRequest aware, we need to implement and Interface “ServletRequestAware”.
Next, if we have something like init, or postContsruct thing, we can have a prepare() method.
prepare() method would be executed before the execute(or any action method).
We need to implement “Prepeable” interface for that.
We need to apply changes to the model object, and for that we need to implement “ModelDriven”.
And implement getModel() method.
Instance variable in the Action classes is matched with request parameter, and if there is any match, then instance variable is set automatically. So, if the HttpServletRequest contains a parameter named “id”, and Action class has a variable names id, then when the Action class would be instantiated, its id variable would be populated with value of the id in request parameter. Now, remember this is a optional feature, and its not happens by default. Dependency needs to be injected.
We must inform the container that we need this feature. And there should be an interceptor, who is going to do this work.“ParametersInterceptor” is going to do this work
public class EntryAction implements ModelDriven, Preparable, ServletRequestAware {
}


LinkWithin

Related Posts Plugin for WordPress, Blogger...

Labels

Core Java programming core java interview question Core Java Faq's Servlets coding database jsp-servlet spring Java linux unix interview questions java investment bank Web Services Interview investment bank mysql Senior java developer interviews best practices java collection tutorial RMI SQL Eclipse FIX protocol tutorial tibco J2EE groovy java questions SCJP grails java 5 tutorial jdbc beginner error and exception Design Patterns Java Programming Tutorials fundamentals general object oriented programming xml Java Programs Hibernate Examples Flex JAMon Java xml tutorial logging Jsp Struts 2.0 Sybase and SQL Server debugging java interviews performance FIX Protocol interview questions JUnit testing WebSphere date and time tutorial experienced java IO tutorial java concurrency thread Ejb Freshers Papers IT Management Java Exapmle Java Script SQL and database tutorial examples Scwcd ant tutorials concurrency example and tutorial future state homework java changes java threading tricky Agile Business of IT Development JSTL Java JSON tutorial Java multithreading Tutorials PM Scrum data structure and algorithm java puzzles java tips testing tips windows 8 5 way to create Singleton Object Architect Interview Questions and Answers Architecture Architecure Bluetooth server as swing application that searches bluetooth device in 10 meter circle and show all devices. You can send file to any bluetooth device. C Programming CIO Callable Statement in Java Circular dependency of Objects in Java Comparable Example in Collection Custom annotation in Java Developer Interview Divide and rule example in java Drupal Example of Singleton Pattern FIX protocol ForkJoin Example in Java 7 Get data from dynamic table with Java Script Git HTML and JavaScript Health Hello World TCP Client Server Networking Program Hibernate Basics Hibernate Interview Question Answer J2EE Interview Question And Answers J2ME GUI Program JEE Interview QA JMS interview question Java J2EE Hibernate Spring Struts Interview Question Java System Property Java Threads Manager Portlets Provident Fund Read data from any file in same location and give the required result. Reading Properties File in Java Redpoint Rest WebService Client Rest Webservice Test SAL join with ven diagram SCP UNIX COMMAND SSL Singleton Pattern in Java Spring Bean Initialization methods and their order Spring Interview Questions Struts Struts 2.0 Basics Struts 2.0 Design Pattern Submit Html Form With Java Script On The Fly Unix executable For Java Program XOM DOM SAX XP books computers core java; core java; object oriented programming data structure; java investment bank; design pattern dtd duplicate rows in table get browser name with jquery grails podcast inner class java beginners tutorial java cache java networking tutorial java spring java util; java collections; java questions java.java1.5 linked list mailto function with all browser oracle database oracle duplicate rows orm schema social spring mvc questions struts transaction tricks tweet windows xslt