Powered By Blogger

Monday, December 19, 2016

Spring - When problem is solved with maturity!

Key points - 
----------------------------------------------------------------------------------------------------------------

1. Spring is an open-source framework with main intention to achieve loose-coupling.

2. Spring uses layered approach which means user/developer has a choice to use functionality if needed.      
    Example -
    Developer can choose AOP functionality to implement
    Developer can choose to design appication with Spring MVC.
    Developer can choose to integrate with ORM (Hibernate).

3. Spring core module is based on IOC container ( also known as Dependency Injection).

4. org.springframework.beans and org.springframework.context packages are used for DI.

5. BeanFactory interface points -

a. Creates an object of the bean when bean name is specified in getBean() method of BeanFactory interface.

b. "Factory" - this term means creation of objects at one place and user does not have to worry object creation.
Resource res = new FileSystemResource("beans.xml");
XmlBeanFactory factory = new XmlBeanFactory(res);

or

ClassPathResource res = new ClassPathResource("beans.xml");
XmlBeanFactory factory = new XmlBeanFactory(res);

or

ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext(
new String[] {"applicationContext.xml", "applicationContext-part2.xml"});  

// of course, an ApplicationContext is just a BeanFactory
BeanFactory factory = (BeanFactory) appContext;

6. ApplicationContext interface points-

a. Creates an object of the bean when bean name is specified in getBean() method.

b. Provides internationalization support - means same application can be translated into different languages based on the location.

c. Publishes event to the registered beans as listeners. 

Spring MVC (Model View Controller) -

Key Points - 
-----------------------------------------------------------------------------------------------------------------------

MVC is a design pattern where an application is can be divided into 3 layers so that each layer has exactly one responsibility and does not know much about other layers.

Model        - Looks into application's business logic and interactions with database.

View           - Looks into presentation part on how to display. Also, view technologies can be changed easily or upgraded as view is not dependent on other layers.

Controller - Acts as a middleman in which additional logic can be added for controlling role based access (example). Also, takes command from View layer ( add data, edit data, delete data, etc) and gets the work done from Model layer.(request/response)
------------------------------------------------------------------------------------------------------------------------

Dispatcher Servlet -

1. Web application works with client-server architecture. Client sends a request for some resource and server responds with a resource.

2. We need a servlet which process request with the help of other classes (data + business logic) and send response.

3. DispatcherServlet handles all requests in a central place and sends request to the controller which in turn processes (store/load) data based on the business rules.

4. DispatcherServlet uses FrontController design pattern which means handling of an application will be done at a central place.

5. Example web.xml

    <web-app>
     <servlet>
          <servlet-name>example</servlet-name>
         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
         <load-on-startup>1</load-on-startup>
     </servlet>

     <servlet-mapping>
         <servlet-name>example</servlet-name>
         <url-pattern>*.form</url-pattern>
     </servlet-mapping>
    </web-app>
    (Taken from http://docs.spring.io/spring-framework/docs/2.0.x/reference/mvc.html)

6. URLs ending with .form will be handled by example dispatcher servlet.

7. Spring framework looks for a file named [servlet-name]-servlet.xml in the WEB-INF directory of web application. Also, creates beans defined in this xml file.
    As per above point 5 - file name will be example-servlet.xml

   <context:component-scan base-package="com.xyz.xyz" />
 
   <!-- Configuration defining views files -->
 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
          <property name="prefix">
              <value>/WEB-INF/views/</value>
          </property>
          <property name="suffix">
              <value>.jsp</value>
         </property>
 </bean>

8. If you want to give different servlet name or different location (other than default location i.e.,WEB-INF directory, then add following details in the web.xml file

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/spring/example-servlet.xml          
        </param-value>
    </context-param>

Tuesday, December 13, 2016

EXCEPTION - VERY USEFUL WHEN THINGS GO UNEXPECTED!

---------------------------------------------------------------------------------------------------------------
Description -
Exception is a condition where a block of code behaves unexpectedly due to unexpected input from the user or due to programmer's irresponsible code.
---------------------------------------------------------------------------------------------------------------

Key Points-

1. One should handle checked exception in code (either in try/catch block or throws keyword).
   Illustration -
main(){                // you can also declare main() using throws keyword main() throws InsufficientFundsException 

     B b = new B();
     
 try{
 b.myMethod();                             // compiler forces you to handle exception
 }catch(InsufficientFundsException ex){
         ex.printstackTrace();
     }
   }

   public class B{
         public void myMethod() throws InsufficientFundsException{   // Custom exception defined by you. You can throw multiple exceptions.
            if(balance <=0)
               throw new InsufficientFundsException();
         }
   }
 
2. Checked exception is good in some situations as compiler forces programmer to handle checked exception and hence application not breaks.

3. Throw your own exception from catch block when an exception is caught. This helps you to maintain discipline as you handle exceptions in one place.
Illustration -
class A{

   try{
      myMethod();
   }catch(BaseException ex){
     ex.printstackTrace();
   }
   }
    
   public class B{
         public void myMethod() throws BaseException{   // Custom exception defined by you. You can throw multiple exceptions.
   
   try{
     // some database code
     // application logic
   }catch(SQLException ex){
      ex.printstackTrace();
      throw new BaseException("exception occurred while processing myMethod()");
   }
               
         }
   }

4. Runtime exceptions should not be handled in catch block or thrown from a method. Because, these exceptions can be avoided through
   programmer and client can't do anything from this exception. So, these are called unchecked exceptions.
   Ex :- ArithmeticException, ArrayIndexOutOfBoundsException, IllegalArgumentException etc.

5. Use checked exceptions when user can change the input based on the message given by exception.

6. finally block should be used when you are dealing with resources. You have to close resources irrespective of exception.
------------------------------------------------------------------------------------------------------------------