Posts

Showing posts from November, 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 :...

@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)...

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("------------------------------------------------...

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, t...

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" + ...

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 or...

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 construc...

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 parameters in 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 -  clean ,  clobber ,  compile  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 = "re...

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. InternalResourceViewResolve...

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

Open eclipse Click  File  >  Import Type  Maven  in the search box under  Select an import source: Select  Existing Maven Projects Click  Next Click  Browse  and select the folder that is the root of the Maven project (probably contains the pom.xml file) Click  OK Under  Projects:  click the  checkbox  next to the pom.xml file 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

Different Controllers in Spring

Image
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.Controller interface 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 cl...

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 Dem...

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