Sunday, November 27, 2016

Jquery Selectors

* $("*") All elements
#id $("#lastname") The element with id="lastname"
.class $(".intro") All elements with class="intro"
.class,.class $(".intro,.demo") All elements with the class "intro" or "demo"
element $("p") All elements
el1,el2,el3 $("h1,div,p") All

,
and elements
 
:first $("p:first") The first element
:last $("p:last") The last element
:even $("tr:even") All even elements
:odd $("tr:odd") All odd elements
 
:first-child $("p:first-child") All elements that are the first child of their parent
:first-of-type $("p:first-of-type") All elements that are the first element of their parent
:last-child $("p:last-child") All elements that are the last child of their parent
:last-of-type $("p:last-of-type") All elements that are the last element of their parent
:nth-child(n) $("p:nth-child(2)") All elements that are the 2nd child of their parent
:nth-last-child(n) $("p:nth-last-child(2)") All elements that are the 2nd child of their parent, counting from the last child
:nth-of-type(n) $("p:nth-of-type(2)") All elements that are the 2nd element of their parent
:nth-last-of-type(n) $("p:nth-last-of-type(2)") All elements that are the 2nd element of their parent, counting from the last child
:only-child $("p:only-child") All elements that are the only child of their parent
:only-of-type $("p:only-of-type") All elements that are the only child, of its type, of their parent
 
parent > child $("div > p") All elements that are a direct child of a
element

parent descendant $("div p") All elements that are descendants of a
element

element + next $("div + p") The element that are next to each
elements

element ~ siblings $("div ~ p") All elements that are siblings of a
element

 
:eq(index) $("ul li:eq(3)") The fourth element in a list (index starts at 0)
:gt(no) $("ul li:gt(3)") List elements with an index greater than 3
:lt(no) $("ul li:lt(3)") List elements with an index less than 3
:not(selector) $("input:not(:empty)") All input elements that are not empty
 
:header $(":header") All header elements

,

...


:animated $(":animated") All animated elements
:focus $(":focus") The element that currently has focus
:contains(text) $(":contains('Hello')") All elements which contains the text "Hello"
:has(selector) $("div:has(p)") All
elements that have a element
:empty $(":empty") All elements that are empty
:parent $(":parent") All elements that are a parent of another element
:hidden $("p:hidden") All hidden elements
:visible $("table:visible") All visible tables
:root $(":root") The document's root element
:lang(language) $("p:lang(de)") All elements with a lang attribute value starting with "de"
 
[attribute] $("[href]") All elements with a href attribute
[attribute=value] $("[href='default.htm']") All elements with a href attribute value equal to "default.htm"
[attribute!=value] $("[href!='default.htm']") All elements with a href attribute value not equal to "default.htm"
[attribute$=value] $("[href$='.jpg']") All elements with a href attribute value ending with ".jpg"
[attribute|=value] $("[title|='Tomorrow']") All elements with a title attribute value equal to 'Tomorrow', or starting with 'Tomorrow' followed by a hyphen
[attribute^=value] $("[title^='Tom']") All elements with a title attribute value starting with "Tom"
[attribute~=value] $("[title~='hello']") All elements with a title attribute value containing the specific word "hello"
[attribute*=value] $("[title*='hello']") All elements with a title attribute value containing the word "hello"
 
:input $(":input") All input elements
:text $(":text") All input elements with type="text"
:password $(":password") All input elements with type="password"
:radio $(":radio") All input elements with type="radio"
:checkbox $(":checkbox") All input elements with type="checkbox"
:submit $(":submit") All input elements with type="submit"
:reset $(":reset") All input elements with type="reset"
:button $(":button") All input elements with type="button"
:image $(":image") All input elements with type="image"
:file $(":file") All input elements with type="file"
:enabled $(":enabled") All enabled input elements
:disabled $(":disabled") All disabled input elements
:selected $(":selected") All selected input elements
:checked $(":checked") All checked input elements

@ModelAttribute on a Method Argument

@ModelAttribute refers to a property of the Model object (the M in MVC ;) so let's say we have a form with a form backing object that is called "Person" Then you can have Spring MVC supply this object to a Controller method by using the @ModelAttribute annotation:

public String processForm(@ModelAttribute("person") Person person){
    person.getStuff();
}

Context Loader Listener- Shared Bean all Servlet

(!-- The definition of the Root Spring Container shared by all Servlets and Filters --)
(context-param)
(param-name)contextConfigLocation(/param-name)
(param-value)/WEB-INF/spring/root-context.xml(/param-value)
(/context-param)

(!-- Creates the Spring Container shared by all Servlets and Filters --)
(listener)
(listener-class)org.springframework.web.context.ContextLoaderListener(/listener-class)
(/listener)

Log4J.xml

(?xml version="1.0" encoding="UTF-8"?)

(!DOCTYPE configuration SYSTEM "log4j.dtd" PUBLIC "-//APACHE//DTD LOG4J 1.2//EN")

-(log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/")

(!-- Appenders --)



-(appender class="org.apache.log4j.ConsoleAppender" name="console")

(param name="Target" value="System.out"/)


-(layout class="org.apache.log4j.PatternLayout")

(param name="ConversionPattern" value="%-5p: %c - %m%n"/)

(/layout)

(/appender)

(!-- Application Loggers --)



-(logger name="com.journaldev.spring")

(level value="info"/)

(/logger)

(!-- 3rdparty Loggers --)



-(logger name="org.springframework.core")

(level value="info"/)

(/logger)


-(logger name="org.springframework.beans")

(level value="info"/)

(/logger)


-(logger name="org.springframework.context")

(level value="info"/)

(/logger)


-(logger name="org.springframework.web")

(level value="info"/)

(/logger)

(!-- Root Logger --)



-(root)

(priority value="warn"/)

(appender-ref ref="console"/)

(/root)

(/log4j:configuration)

Iterate HashMap


HashMap loans = new HashMap();
loans.put("home loan", "citibank");
loans.put("personal loan", "Wells Fargo");
for (String key : loans.keySet()) {
   System.out.println("------------------------------------------------");
   System.out.println("Iterating or looping map using java5 foreach loop");
   System.out.println("key: " + key + " value: " + loans.get(key));
}



Set keySet = loans.keySet();
Iterator keySetIterator = keySet.iterator();
while (keySetIterator.hasNext()) {
   System.out.println("------------------------------------------------");
   System.out.println("Iterating Map in Java using KeySet Iterator");
   String key = keySetIterator.next();
   System.out.println("key: " + key + " value: " + loans.get(key));
}



Set> entrySet = loans.entrySet();
for (Entry entry : entrySet) {
   System.out.println("------------------------------------------------");
   System.out.println("looping HashMap in Java using EntrySet and java5 for loop");
   System.out.println("key: " + entry.getKey() + " value: " + entry.getValue());
}



Set> entrySet1 = loans.entrySet();
Iterator> entrySetIterator = entrySet1.iterator();
while (entrySetIterator.hasNext()) {
   System.out.println("------------------------------------------------");
   System.out.println("Iterating HashMap in Java using EntrySet and Java iterator");
   Entry entry = entrySetIterator.next();
   System.out.println("key: " + entry.getKey() + " value: " + entry.getValue());
}


Difference between Jenkin and Maven

Maven is a build tool, in short a successor of ant. It helps in build and version control.
However Jenkins is continuous integration system, where in maven is used for build. Jenkins can be used to automate the deployment process. When ever the new code is committed, automatically run all Junit test cases and if they're passed, package and deploy the project to the specific location.

Maven came after ANT and offers much more than a build tool. Main difference between ANT and Maven is that In ANT you need to define every thing i.e. source directory, build directory, target directory etc while Maven adopts principle of Convention over configuration. Which means Maven has predefined project structure i.e. standard directory for source files, test files and resources. On the other hand, Jenkins and Hudson are Continues Integration tool, which gives you power to automate your build and deployment process. By using Jenkins or Hudson you can trigger build whenever developer commit code, to see if project is compiling fine, to run unit tests, to create build or even deploy in QA or production environment. Similarly you can have daily build, nightly build or weekly build process established in Jenkins or Hudson.


Jersy 2.x Restful Service

package com.javatpoint.rest;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;


@Path("/ws")
public class ProductService {

 @GET
 @Path("/hellostring")
 @Produces(MediaType.TEXT_PLAIN)
 public String sayPlainTextHello() {
  return "Hello Jersey";
 }

 @GET
 @Path("/hellostring1")
 @Produces("text/plain")
 public String hello() {
  return "Hello World!!! dineshonjava";
 }


 @GET
 @Path("/hellohtml")
 @Produces(MediaType.TEXT_HTML)
 public String sayHtmlHello() {
  return "html " + "title" + "Hello Jersey" + "/title" + "bodyh1" + "Hello Jersey" + "/body/h1" + "/html ";
 }

 @GET
 @Path("/helloxml")
 @Produces(MediaType.TEXT_XML)
 public String sayXMLHello() {
  return "?xml version=\"1.0\"?" + "hello Hello Jersey" + "/hello";
 }


 @GET
 @Path("/test/{cusNo}")
 @Produces(MediaType.APPLICATION_JSON)
 public Customer produceCustomerDetailsinJSON(@PathParam("cusNo") int no) {
  Customer cust = new Customer();
  cust.setCustNo(no);
  cust.setCustName("Java4s");
  cust.setCustCountry("India");
  return cust;
 }

 @GET
 @Path("/employees")
 @Produces({
  MediaType.APPLICATION_XML,
  MediaType.APPLICATION_JSON
 })
 public List  Employee  listEmployees() {
//accept header value application/xml - return xml value
//accept header value application/json - return xml value
  return new ArrayList  Employee  (employees.values());
 }


 @GET
 @Path("/json/employees/")
 @Produces(MediaType.APPLICATION_JSON)
 public List  Employee  listEmployeesJSON() {
  return new ArrayList  Employee  (employees.values());
 }


 @Path("{word}")
 @GET
 @Produces("application/json")
 public Response reverser(@PathParam("word") String word) {
  StringBuilder sb = new StringBuilder();
  sb.append(word);
  ObjectMapper mapper = new ObjectMapper();
  ArrayNode arrayNode = mapper.createArrayNode();
  com.fasterxml.jackson.databind.node.ObjectNode node1 = mapper.createObjectNode();
  node1.put("original", sb.toString());
  node1.put("reversed", sb.reverse().toString());
  arrayNode.add(node1);
  return Response.status(200).entity(arrayNode.toString()).build();
 }

 @GET
 @Path("/hellojson")
 @Produces(MediaType.APPLICATION_JSON)
 public String sayJSONHello() {
  return "{\"Hello Jersey\":\"\"}";
 }

 @GET
 @Path("/get")
 @Produces(MediaType.APPLICATION_JSON)
 public Track getTrackInJSON() {
  Track track = new Track();
  track.setTitle("Enter Sandman");
  track.setSinger("Metallica");
  return track;
 }

 @GET
 @Path("/employee/{employeeid}")
 @Produces("application/xml")
 public Employee getEmployee(@PathParam("employeeid") String employeeId) {
  return employees.get(employeeId);
 }


 @GET
 @Path("/json/employee/{employeeid}")
 @Produces("application/json")
 public Employee getEmployeeJSON(@PathParam("employeeid") String employeeId) {
  return employees.get(employeeId);
 }

 @POST
 @Path("/post")
 @Consumes(MediaType.APPLICATION_JSON)// content-type must ne application/json
 public Response createTrackInJSON(Track track) {
  String result = "Track saved : " + track;
  System.out.println(result);
  return Response.status(201).entity(result).build();
 }

 @POST
 @Path("/add")
 public Response addUser(
  @FormParam("id") int id,
  @FormParam("name") String name,
  @FormParam("price") float price) {

  return Response.status(200)
   .entity(" Product added successfuly!br Id: " + id + "br Name: " + name + "br Price: " + price)
   .build();
 }


 private static Map  String, Employee  employees = new HashMap  String, Employee  ();

 static {

  Employee employee1 = new Employee();
  employee1.setEmployeeId("0");
  employee1.setEmployeeName("Dineh Rajput");
  employee1.setJobType("Sr.Software Engineer");
  employee1.setSalary(70000L);
  employee1.setAddress("Noida");
  employees.put(employee1.getEmployeeId(), employee1);

  Employee employee2 = new Employee();
  employee2.setEmployeeId("2");
  employee2.setEmployeeName("Abhishek");
  employee2.setJobType("Marketing");
  employee2.setSalary(50000L);
  employee2.setAddress("New Delhi");
  employees.put(employee2.getEmployeeId(), employee2);

 }


}


    $(document).ready(function(){
    // click on button submit
    $("#submit").on('click', function(){
    //var formData = JSON.stringify($("#myForm").serialize());
    var formData =JSON.stringify(QueryStringToJSON($("#myForm").serialize()));
    alert(formData);;
        // send ajax
    $.ajax({
     type: "POST",
     url: "http://localhost:8080/restfuljerseyformparam/rest/ws/post",
     data: formData,
     success: function(result){console.log(result);alert(result);},
     dataType: "json",
     contentType : "application/json"
    });
});
      });    
     
      function QueryStringToJSON(str) {          
       var pairs = str.split('&');
       var result = {};
       pairs.forEach(function(pair) {
           pair = pair.split('=');
           var name = pair[0]
           var value = pair[1]
           if( name.length )
               if (result[name] !== undefined) {
                   if (!result[name].push) {
                       result[name] = [result[name]];
                   }
               result[name].push(value || '');
               } else {
                   result[name] = value || '';
               }
       });
       return( result );
    }


    servlet-name  Jersey REST Service /servlet-name
    servlet-class  org.glassfish.jersey.servlet.ServletContainer /servlet-class
     init-param
        param-name  jersey.config.server.provider.packages  /param-name
        param-value  com.javatpoint.rest,com.fasterxml.jackson.jaxrs.json /param-value
    /init-param
    load-on-startup  1  /load-on-startup
  /servlet
  servlet-mapping
    servlet-name  Jersey REST Service  /servlet-name
    url-pattern  /rest/*  /url-pattern
  /servlet-mapping


Spring Restful Service

package net.javaonline.spring.restful.controller;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/hello")
public class HelloWorldService {

@RequestMapping
    public String helloMethod1(@RequestParam(value="name", defaultValue="World") String name) {
     
     return   "Hello  "+ name;
    }
 
@RequestMapping(value = "/{firstName}/{lastName}", method = RequestMethod.GET)
    public String helloMethod2(@PathVariable String firstName, @PathVariable String lastName) {
    return "Hello "+ firstName + " " + lastName;
    }  
 
}


servlet
servlet-namerest/servlet-name
servlet-class
org.springframework.web.servlet.DispatcherServlet
/servlet-class
load-on-startup1/load-on-startup
/servlet

What is IOC?

The Inversion of Control pattern (also known as dependency injection) is that you do not create your objects but describe how they should be created. 

What is auto wiring?

The Spring container provides the functionality of connecting beans with each other automatically called autowiring . Rather we inject one bean into the other using ref attribute,  Spring can look into the BeanFactory and decide how to inject one bean into the other. So we don’t explicitly connect (wire) beans instead spring does this for us.



Autowiring helps to minimize  the need to specify properties or constructor arguments, thus saves a lot of typing . Autowiring is specific to individual beans, a bean may or may not use autowiring.


no – Default, no auto wiring, set it manually via “ref” attribute

byName – Auto wiring by property name. If the name of a bean is same as the name of other bean property, auto wire it.

byType – Auto wiring by property data type. If data type of a bean is compatible with the data type of other bean property, auto wire it.

constructor – byType mode in constructor argument.

autodetect – If a default constructor is found, use “autowired by constructor”; Otherwise, use “autowire by type”.

Types of Controller?

Controllers are components that are being called by the Dispatcher Servlet for doing any kind of Business Logic. Spring Distribution already comes with a variety of Controller Components each doing a specific purpose. All Controller Components in Spring implement the org.springframework.web.servlet.mvc.Controller interface.
SimpleFormController, AbstractController, AbstractCommandController, CancellableFormController, AbstractCommandController, MultiActionController, 
ParameterizableViewController, ServletForwardingController, ServletWrappingController, 
UrlFilenameViewController.

Spring Abstract Command Controller?

To process request parameters in the controller, then instead of using servlet classes to get request parametersin Abstract controller based controller, you can use AbstractCommandController which has the ability to auto populate request parameters to the data object which is also termed as command object in spring. This controller also offers feature to validate the request parameters. You set the name of the command class using setCommandClass() method in the constructor of the controller. This populated command object is passed to the method handle() which is called by the DispatcherServlet automatically.

Spring Abstract Controller ?

Abstract controller provides the basic support which can be used when you want to implement your own controller from scratch. It should be used for simple use like returning a resource (For example, any jsp page) to the client without checking request parameters. 
Abstract controller needs you to override the handleRequestInternal(HttpServletRequest, HttpServletResponse)method and write your logic inside it. This method should return ModelAndView object.

Spring Handler Mappings ?

When the Client Request reaches the Dispatcher Servlet, the Dispatcher Servlet tries to find the appropriate Handler Mapping Object to map between the Request and the Handling Object. A Handler Mapping provides an abstract way that tell how the Client’s Url has to be mapped to the Handlers.

What is Spring AOP?

Spring AOP (Aspect-oriented programming) framework is used to modularize cross-cutting concerns in aspects. Put it simple, it’s just an interceptor to intercept some processes, for example, when a method is execute, Spring AOP can hijack the executing method, and add extra functionality before or after the method execution.

1. Before advice (implements MethodBeforeAdvice)
2. After returning advice (implements  AfterReturningAdvice)
3. After throwing advice (implements ThrowsAdvice)
4. Around advice (implements MethodInterceptor)
5.joint point
6. pointcut

Dependency Injection

Dependency Injection (DI) is a design pattern that removes the dependency from the programming code so that it can be easy to manage and test the application. Dependency Injection makes our programming code loosely coupled.

Maven

Maven is a build automation tool used primarily for Java projects. Maven serves a similar purpose to the Apache Ant tool, but it is based on different concepts and works in a different manner.


 
  4.0.0

 

  com.mycompany.app
  my-app
  1.0

 

 
   

     

      junit
      junit
      3.8.1

     

      test

   
 


Apache Ant

Apache Ant is a software tool for automating software build processes. It is similar to Make but is implemented using the Java language, requires the Java platform, and is best suited to building Java projects.
The most immediately noticeable difference between Ant and Make is that Ant uses XML to describe the build process and its dependencies, whereas Make uses Makefile format. By default the XML file is named build.xml

Sample build.xml file

Below is listed a sample build.xml file for a simple Java "Hello, world" application. It defines four targets - cleanclobbercompile and jar, each of which has an associated description. The jar target lists the compile target as a dependency. This tells Ant that before it can start the jar target it must first complete the compile target.
 version="1.0"?>
name="Hello" default="compile">
name="clean" description="remove intermediate files">
dir="classes"/>
> name="clobber" depends="clean" description="remove all artifact files"> file="hello.jar"/> > name="compile" description="compile the Java source code to class files"> dir="classes"/> srcdir="." destdir="classes"/> > name="jar" depends="compile" description="create a Jar file for the application"> destfile="hello.jar"> dir="classes" includes="**/*.class"/> > name="Main-Class" value="HelloProgram"/> > > > >
Commands :

rm -rf classes/
rm is a Unix-specific command unavailable in some other environments. 

Microsoft Windows, for example, would use:
rmdir /S /Q classes

Code Review Checklist and Best practices

Find Bugs

Types of Handler Mapping

BeanNameUrl HandlerMapping, CommonsPathMap HandlerMapping, ControllerClassName HandlerMapping, SimpleUrl HandlerMapping.

BeanNameUrl : The simplest of the Handler Mapping and it is used to map the Url that comes from the Clients directly to the Bean Object. The Bean is nothing but a Controller object.

CommonsPathMap : This is a rarely used Handler Mapping in which case, the name of the Url to which the Controller has to be mapped is specified directly in the Source file of the Controller.

ControllerClassName : This Controller is taking directly from the Url itself with slight modifications.

SimpleUrl : The Simplest of all the Handler Mappings as it directly maps the Client Request to some Controller object. 

Types of view Resolver

    AbstractCachingViewResolver : Abstract view resolver that caches views. Often views need preparation before they can be used; extending this view resolver provides caching.

    XmlViewResolver : Implementation of ViewResolver that accepts a configuration file written in XML with the same DTD as Spring’s XML bean factories. The default configuration file is /WEB-INF/views.xml.

    ResourceBundleViewResolver : Implementation of ViewResolver that uses bean definitions in a ResourceBundle, specified by the bundle base name. Typically you define the bundle in a properties file, located in the classpath. The default file name is views.properties.

    UrlBasedViewResolver : Simple implementation of the ViewResolver interface that effects the direct resolution of logical view names to URLs, without an explicit mapping definition. This is appropriate if your logical names match the names of your view resources in a straightforward manner, without the need for arbitrary mappings.

    InternalResourceViewResolver :  Convenient subclass of UrlBasedViewResolver that supports InternalResourceView (in effect, Servlets and JSPs) and subclasses such as JstlView and TilesView. You can specify the view class for all views generated by this resolver by using setViewClass(..).

    VelocityViewResolver/FreeMarkerViewResolver : Convenient subclass of UrlBasedViewResolver that supports VelocityView (in effect, Velocity templates) or FreeMarkerView ,respectively, and custom subclasses of them.

    ContentNegotiatingViewResolver : Implementation of the ViewResolver interface that resolves a view based on the request file name or Accept header.

    Saturday, November 26, 2016

    Maven

    Maven is a powerful project management tool that is based on POM (project object model). It is used for projects build, dependency and documentation. It simplifies the build process like ANT. But it is too much advanced than ANT.

    Dependency management: Maven will resolve and manage your dependencies for you. Testing: the ability to run tests and integration tests as part of your project lifecycle. Plugins: there are thousands of plugins to carry out various tasks. These are simply configured in just by adding a reference into the POM.

    Importing Maven Project

    1. Open eclipse
    2. Click File > Import
    3. Type Maven in the search box under Select an import source:
    4. Select Existing Maven Projects
    5. Click Next
    6. Click Browse and select the folder that is the root of the Maven project (probably contains the pom.xml file)
    7. Click OK
    8. Under Projects: click the checkbox next to the pom.xml file
    9. Click Finis

    Jersy and Jax-rs


    Jersey just a interface to use JAX-rs in more easier way. JAX-RS don't provided servlet but Jersey does. Jersey provides a library to implement Restful webservices in a Java servlet container, Jersey provides a servlet implementation which scans predefined classes to identify RESTful resources. In your web.xml configuration file your register this servlet for your web application

    GET request to /api/user/ returns a list of users
    GET request to /api/user/1 returns the user with ID 1
    POST request to /api/user/ with a user object as JSON creates a new user
    PUT request to /api/user/3 with a user object as JSON updates the user with ID 3 //upload
    DELETE request to /api/user/4 deletes the user with ID 4
    DELETE request to /api/user/ deletes all the users

    Friday, November 25, 2016

    Different Controllers in Spring

    Different Controllers in Spring

    In Spring mvc, DispatcherServlet acts as controller and it will call the methods of controller classes that we have defined.

    Controller classes:

    these are the classes whose methods are called by  DispatcherServlet . A controller class is the one which provides the implementation of org.springframework.web.servlet.mvc.Controllerinterface directly or indirectly.

    In spring we have bunch of controller classes implementing org.springframework.web.servlet.mvc.Controller interface. You can go through the controller class hierarchy from the link.

    The DispatcherServlet always calls handleRequest() of Controller interface when ever we send request from the browser to the controller.

    Commonly used Controllers:

    Some of the controllers frequently used are :

    AbstractController,AbstractCommandController,AbstractFormController,  MultiActionController,SimpleFormController,AbstractWizardFormController... etc.

    All of these classes are implementing Controller interface. If we want to write our own controller we can extend any one of these classes , so that our class will become a controller class.

    Illustration:

    If our controller class is extending AbstractController then we need to implement  handleRequestInternal() of AbstractController.



    However, DispatcherServlet will call handleRequest() of Controller interface when ever we requested the controller. The handleRequest() internal code will call handleRequestInternal() of our AbstractController.

    This can be represented as..




    Now let us consider our class is extending AbstractCommandController, then we need to implement  handle() of AbstractCommandController.




    Similar to above illustration , DispatcherServlet always calls handleRequest() of Controller which will  call handleRequestInternal() and which will further call handle() of our controller.

    Suppose we have a form and we need to do some task after submitting the form then we will take the help of AbstractFormController.


    showForm() method will be called to show the view(form) and if any errors exists in the validation they will be added to exception object.

    Now whenever the form got submitted, DispatcherServlet will call handleRequest() which calls handleRequestInternal() which will further call processFormSubmission() of our controller.


    If our form has to do multiple tasks , let's say form has more than one button, then we prefer MultiActionController. 




    Here add() and delete() are the custom methods corresponding to multiple buttons (add,delete) in our form. 

    If we want to display a form to the user and display a success message after reading the data from the form then we need to take the help of SimpleFormController.




    We need to provide some basic information like CommandClass, Command name, Form view and Success view. Ofcourse we can set them in xml file also.

    Whenever user submit's the form if no errors exists the controller calls onSubmit() of our controller class and finally it will display the success view to the user.


    Now, if we want to get the information from user in multiple forms, then we need to go for AbstractWizardFormController. Incase of multiple form based applications our class should extend AbstractWizardFormController .




    Here, we need to provide command class, command name and the pages are the forms to be displayed one by one in order to get multiple form application.


    Which Controller is Best:

    Based on our need, we can chose any of the controllers mentioned above. If we are performing a task without any form then we can use any of AbstractController,AbstractCommandController. 

    If our application have forms, then we can use any of SimpleFormController,AbstractFormController, AbstractWizardFormController based on our requirement.


    Here we are using the term command class, command name.

    A command class is a noraml java bean with some properties relative to the corresponding form. If the form has three fields then our command class need to have three corresponding properties. command name is the name given to the command class object.

    MVC

    In MVC 1, controller and model,both are JSP. While in MVC2 controller is servlet and model is java class. In MVC1 there is tight coupling between page and model as data access is usually done using Custom tag or through java bean call.

    In MVC2 architecture there is only one controller which receives all the request for the application and is responsible for taking appropriate action in response to each request.

    Lazy Initialize Spring Beans

    Spring provides an attribute called lazy-init to inform the Spring IOC container for not creating that bean at the start up. lazy-init will be set as true to indicate the container. The beans will be created only when requested.




        id="..." class="..."
         
     

     
        id="..." class="..." lazy-init="true"
         
     

     
        id="..." class="..." init-method="..."
         
     

     
        id="..." class="..." destroy-method="..."

    The init-method attribute specifies a method that is to be called on the bean immediately upon instantiation. Similarly, destroy-method specifies a method that is called just before a bean is removed from the container.


    @Configuration
    // @Lazy - For all Beans to load lazily
    public class AppConf {

        @Bean
        @Lazy
        public Demo demo() {
            return new Demo();
        }
    }

    @Component
    @Lazy
    public class Demo {
        ....
        ....
    }

    @Component
    public class B {

        @Autowired
        @Lazy // If this is not here, Demo will still get eagerly instantiated to satisfy this request.
        private Demo demo;

        .......
     }

    double checked locking singleton

    public static Singleton getInstanceDC() {
        if (_instance == null) { // Single Checked
            synchronized(Singleton.class) {
                if (_instance == null) {// Double checked
                    _instance = new Singleton();
                }
            }
        }
        return _instance;
    }


    public static synchronized Singleton getInstanceTS() {
        if (_instance == null) {
            _instance = new Singleton();
        }
        return _instance;
    }

    Association - Aggregation- Composition- Inheritance

    உப்பு மாங்காய்

    சுருக்குப்பை கிழவி. சுருக்கங்கள் சூழ் கிழவி. பார்க்கும் போதெல்லாம் கூடையுடனே குடியிருப்பாள். கூடை நிறைய குட்டி குட்டி மாங்காய்கள். வெட்டிக்க...