Monday, 25 November 2013

What's the difference between a thread's start() and run() methods?


 The separate start() and run() methods in the Thread class provide two ways to create threaded programs. The start() method starts the execution of the new thread and calls the run() method. The start() method returns immediately and the new thread normally continues until the run() method returns.
The Thread class' run() method does nothing, so sub-classes should override the method with code to execute in the second thread. If a Thread is instantiated with a Runnable argument, the thread's run() method executes the run() method of the Runnable object in the new thread instead.

Depending on the nature of your threaded program, calling the Thread run() method directly can give the same output as calling via the start() method, but in the latter case the code is actually executed in a new thread.

ActionMapping Usage in Struts

 The ActionServlet needs some mechanism to determine how to route requests to Action classes. This is done using an ActionMapping class. 

The
 ActionMapping represents the information that the ActionServlet knows about the mapping of a particular request to an
instance of a particular
 Action class. 

The
 mapping is passed to the execute() method of the Action class, enabling access to this information directly. 

Example :
 Action Mappings are defined in the struts−config.xml file is
Code:
<action−mappings>
<action path="/search"
type="cdmanager.actions.SearchAction"
name="searchForm"
scope="request"
input="/search.jsp">
<forward name="success" path="/display.jsp"/>
</action>
</action−mappings>

The path property is the request URI path used to select this mapping. If extension mapping is used for the Controller Servlet, the extension will be stripped before comparisons against this value are made.

The
 type property specifies the fully qualified Java class name of the Action implementation used by this mapping.

The
 name property specifies the name of the Form Bean if there is one associated with this Action.

The
 scope property identifies the scope that can be Requested or the Session that the Form Bean (if there was one specified) creates. 

The
 input property is the Context-relative path of the input form to which control should be returned if a validation error is encountered. For example, this property is used if we have an
input form
 that uses validation and one of the required fields is missing. The Controller needs to know what to do when such a validation error occurs and is returned from theActionForm. The input property tells the Controller where to proceed next.

The
 forward property provides Action-local names of logical ActionForward instances that can be returned by the Action to control what does the actual presentation. The action is still called. 

Note :
 It is possible to specify multiple forward declarations for each action.

Struts MVC Architecture

The model contains the business logic and interact with the persistance storage to store, retrive and manipulate data.
The view is responsible for dispalying the results back to the user. In Struts the view layer is implemented using JSP.
The controller handles all the request from the user and selects the appropriate view to return. In Sruts the controller's job is done by the ActionServlet


·         The ActionServlet receives the request.
·         The struts-config.xml file contains the details regarding the Actions, ActionForms, ActionMappingsand ActionForwards.
·         During the startup the ActionServelet reads the struts-config.xml file and creates a database of configuration objects. Later while processing the request the ActionServlet makes decision by refering to this object.
When the ActionServlet receives the request it does the following tasks.
·         Bundles all the request values into a JavaBean class which extends Struts ActionForm class.
·         Decides which action class to invoke to process the request.
·         Validate the data entered by the user.
·         The action class process the request with the help of the model component. The model interacts with the database and process the request.
·         After completing the request processing the Action class returns an ActionForward to the controller.
·         Based on the ActionForward the controller will invoke the appropriate view.

·         The HTTP response is rendered back to the user by the view component.

SortingBasedOnValues In HashMap

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Set;
import java.util.TreeMap;

public class Test {
public static void main(String[] args) {
HashMap passedMap=new HashMap();
passedMap.put("key1", "ram");
passedMap.put("key2", "abc");
passedMap.put("key3", "sai");
passedMap.put("key4", "bangalore");

System.out.println(passedMap);

   List mapKeys = new ArrayList(passedMap.keySet());
   List mapValues = new ArrayList(passedMap.values());
 
   Collections.sort(mapValues);
   Collections.sort(mapKeys);
 
   LinkedHashMap sortedMap = new LinkedHashMap();

   Iterator valueIt = mapValues.iterator();
 
  while (valueIt.hasNext())
  {
      Object val = valueIt.next();
      Iterator keyIt = mapKeys.iterator();

      while (keyIt.hasNext())
      {
          Object key = keyIt.next();
          String comp1 = passedMap.get(key).toString();
          String comp2 = val.toString();

          if (comp1.equals(comp2))
          {
              passedMap.remove(key);
              mapKeys.remove(key);
              sortedMap.put((String)key, (String)val);
              break;
          }

      }

  }
  System.out.println(sortedMap);
}
}

JSP Vs Servlets

JSPServlets
JSP is a webpage scripting language that can generate dynamic content.Servlets are Java programs that are already compiled which also creates dynamic web content.
Servlets run faster compared to JSP.JSP run slower compared to Servlet. JSP compiles into Java Servlets.
It’s easier to code in JSP than in Java Servlets.Its little much code to write here.
In MVC, jsp act as a view.In MVC, servlet act as a controller.
JSP are generally preferred when there is not much processing of data required.servlets are best for use when there is more processing and manipulation involved.
The advantage of JSP programming over servlets is that we can build custom tags which can directly call Java beans.There is no such facility in servlets.
We can achieve functionality of JSP at client side by running JavaScript at client side.There are no such methods for servlets.

Saturday, 16 November 2013

Struts-Spring Integration

There are two ways to configuring spring in struts.

1. Using org.springframework.web.struts.ActionSupportAction class.
2. Using org.springframework.web.struts.DelegatingActionProxy.

Lets check second method:-2. Using org.springframework.web.struts.DelegatingActionProxy.
DelegatingActionProxy is a proxy class for appropriate Action.
Here we extends strut’s Action class to write action class.
But we dont mention this action class in struts-config.xml file.
Instead of our action class we use DelegatingActionProxy.

1. Modify struts-config.xml to load spring’s context loder plugin.

Add following entries in struts-xml

<plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">
 <set-property property="contextConfigLocation" value="/WEB-INF/ApplicationContext.xml"/>
</plug-in>
Here we are defining the context file to read. This plugging in loaded when server starts and it  reads the configuration file(here its placed at /WEB-INF/ApplicationContext.xml).
2. Modify struts-config.xml file and change action mapping as:-
<action
path="/loginAction"
type="org.springframework.web.struts.DelegatingActionProxy"
name="loginForm"
scope="request"
validate="true"
input="/WEB-INF/pages/login.jsp">
<forward name="success" path="/homePage.do"/>
<forward name="failure" path="/login.do"/>
</action>
Here we are using DelegatingActionProxy instead of LoginAction. All requests goes to DelegatingActionProxy it is the responsibility of this class to call appropriate action class.
2. Define bean definitions in WEB-INF/ApplicationContext.xml.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
 <bean id="businessDelegateBean" class="my.login.action.BusinessDelegate">
 </bean>
<bean name="/loginAction" class="my.login.action.LoginAction">
<property name="businessDelegate">
<ref bean="businessDelegateBean"/>
</property>
 </bean>
</beans>
Here i defined a bean with id “businessDelegateBean” and map url pattern to actual action class. DelegatingActionProxy class read this file and see that /loginAction is mapped to LoginAction and it forward request to LoginAction, before that it inject businessDelegate.
3. Define BusinessDelegate class.
package my.login.action;
public class BusinessDelegate {
 public String validateUser(String userName, String password) {
 if(userName.equals("vivek") && password.equals("kumar")) {
 return "success";
 }
 return "failure";
 }
}
4. Modify action class.
package my.login.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import my.login.form.LoginForm;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.web.struts.ActionSupport;
public class LoginAction extends ActionSupport {
 private BusinessDelegate businessDelegate;
 public BusinessDelegate getBusinessDelegate() {
 return businessDelegate;
 }
 public void setBusinessDelegate(BusinessDelegate businessDelegate) {
 this.businessDelegate = businessDelegate;
 }
 @Override
 public ActionForward execute(ActionMapping mapping, ActionForm form,
 HttpServletRequest request, HttpServletResponse response)
 throws Exception {
 LoginForm loginForm =(LoginForm) form;
 String target = businessDelegate.validateUser(loginForm.getUserName(),
    loginForm.getPassword());
 if("failure".equalsIgnoreCase(target))
 {
 ActionErrors  errors = new ActionErrors();
 errors.add("loginError", new ActionError("login.failure.message"));
 saveErrors(request,errors);
 }
 return mapping.findForward(target);
 }
}


spring web mvc interview questions

Question: Explain Spring MVC framework with an example ?
Ans: Explain Spring MVC architecture with an example ? The MVC is a standard software architecture that aims to separate business logic from presentation logic, enabling the development, testing and maintenance of both isolated . (1) The user triggers an event through the UI (click a button on the page or something).
(2) The controller receives the event and coordinates how things will happen on the server side, i.e. the flow goes to the objects required to perform the business rule.
To see Spring MVC hello world example
Question: What are the advantages of Spring MVC over Struts MVC ?
Ans: 1. There is clear separation between models, views and controllers in Spring.
2. Spring’s MVC is very versatile and flexible based on interfaces but Struts forces Actions and Form object into concrete inheritance.
3. Spring provides both interceptors and controllers..
To see Spring MVC hello world example 
Question: What is Controller in Spring MVC framework?
Ans: In a general way, Controller (‘c’ in mvc ) delivers access to the behavior of application which is usually defined by a service interface and acts as glue between core application and the web. It processes/interprets client data and.. 
Question: What is a front controller in Spring MVC ?
Ans: A front controller is defined as “a controller which handles all requests for a Web Application.” DispatcherServlet (actually a servlet) is the front controller in Spring MVC that intercepts every request and then dispatches/forwards requests to an appropriate controller.. 
Question: What is SimpleFormController in Spring MVC and how to use it in your web application ?
Ans:It offers you form submission support. This can help in modeling forms and populating them with model/command object returned by the controller. After filling the form, it binds the fields, validates the model/command object, and passes the object back to the controller so that the controller can take appropriate action.. 
Question: What is AbstractController in Spring MVC ?
Ans:AbstractController : It provides a basic infrastructure and all of Spring’s Controller inherit from AbstractController. It offers caching support, setting of the mimetype etc. It has an abstract method ‘handleRequestInternal(HttpServletRequest, HttpServletResponse)’ which should be overridden by subclass.. 
Question: What is ParameterizableViewController in Spring MVC ?
Ans:ParameterizableViewController : ParameterizableViewController is one of the concrete Spring’s Controller. This controller returns a view name specified in Spring configuration xml file thus eliminates the need of hard coding view name in the controller class as in case of AbstractController..
Question: Why to override formBackingObject(HttpServletRequest request) method in Spring MVC?
Ans:You should override formBackingObject(HttpServletRequest request) if you want to provide view with model object data so that view can be initialized with some default values e.g. Consider in your form view..
Question: What is the use of overriding referenceData(HttpServletReques) in Spring MVC ?
Ans: Overridden referenceData() method is used to provide some additional information to the formView (fillForm.jsp) to construct and display the view e.g.
In your form view you want to give various options to user say in the form of checkboxes and user can select multiple options. For this You can create multiple checkboxes in your view and corresponding multiple instance variables in your command/model object.
Question: When and how to use MultiActionController in Spring MVC ?
Ans: MultiActionController supports the aggregation of multiple request-handling methods into one controller, so allows you to group related functionality together. It is capable of mapping requests to method names and then invoking the correct method to handle a particular request… 
Question: Which are the different method name resolvers in MultiActionController ?
Ans: MultiActionController needs some way to resolve which method to call when handling an incoming http request. Spring provides MethodNameResolver interface to achieve this. The MultiActionController class provides a property named ‘methodNameResolver’ so that you can inject a MethodNameResolver… 

Friday, 15 November 2013

What's the purpose of Object Oriented Programming?

look
when object oriented programming was not invented then programmers used procedural programming methods
i.e. whole program was just one part and the sequential flow of the program was there
the programs were not so much readable and if there was some big problem to solve then programmers needed to code in a hectic way as no grouping facilities were there.
 
In object oriented programming, we can form groups of code for specific purpose, those are called as methods
 
and we can create the objects those are instances of the classes we have created. These objects can call the methods of respective classes
 
also
 
the object oriented programming concepts allow us to use some features like data encapsulation which allows us to protect our data from outer methods, concept of polymorphism which allows us to use same method name for different purposes and many features


http://en.wikipedia.org/wiki/Object-oriented_programming