Maven Hello World example

In this post we will see a sample web project which displays "Hello World" in the web browser. To achieve this we need to open a maven project. Click File -> New -> Other -> Maven Project.
Then click "Next" and next type "webapp" in the Filter. Select the following details:
  • GroupId: org.codehaus.mojo.archetypes
  • ArtifactId: webapp-j2ee14
  • Version: 1.3
Then click Next and provide GroupId, ArtifactId and other details as per your choice. The project created looks like the below screen.
The project will have many files including "pom.xml" and "index.jsp". Open "pom.xml" file and make the following changes. Replace "build" tag with the below code. Since we want to use tomcat 7 in our project we need to mention the same in the pom.xml file.
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.tomcat.maven</groupId>
        <artifactId>tomcat7-maven-plugin</artifactId>
        <version>7</version>
      </plugin>
    </plugins>
  </build>
The complete "pom.xml" file looks like this.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>Maven_Hello_World</groupId>
  <artifactId>MavenHelloWorld_Example</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>MavenHelloWorld_Example</name>
  <url>http://maven.apache.org</url>

  <dependencies>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.4</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.1</version>
      <scope>provided</scope>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.tomcat.maven</groupId>
        <artifactId>tomcat7-maven-plugin</artifactId>
        <version>7</version>
      </plugin>
    </plugins>
  </build>
</project>
After the changes are made to the "pom.xml" file, right click on the file and then "Run As -> Maven clean". Next right click on the same file and then do "Run As -> Maven generate-sources". These two above steps will clean the project and rebuild it which will help in removing any errors if any.
Next build the project. This can be done by right clicking on the "pom.xml" file and "Run As -> Maven build...". Please check that there are two Maven build options given. When we run our project for the first time, use the option "Maven build...".
This will open a window where in we need to give "tomcat:run" in the "Goals:" and then click on Run as shown in the below screen.
The project will run successfully but it will not show any output. To get the output we need to open a browser and enter the following URL.

http://localhost:8080/MavenHelloWorld_Example
This URL is provided by the maven in the console as shown below.
The URL will give the following output in the browser.

Adding dependencies for Spring and Hibernate

In this post we will see how to use maven for building dependencies for Spring, Hibernate etc. To start with, click on File -> New -> Other as shown below.
In the New window, type maven and select "Maven Project" and click Next.
Do not select anything here. Leave the default check box as it is and click Next.
In this window, the default ArtifactId select would be "maven-archetype-quickstart". Click Next.
In this window, give the following details and click Finish. ArtifactId is the name of the project.
This creates folders and a pom.xml file. This "pom.xml" file is the back bone for maven. We can add jar files to our project by adding dependencies to the pom.xml file. Open pom.xml file. Suppose we want to add spring-orm jar file. To do that, open google.com and search for "hibernate-core maven". Click on the first link (http://mvnrepository.com/artifact/org.hibernate/hibernate-core/3.6.10.Final). This link will display the list of jar file versions and its related binary file to be down loaded. Let us suppose that we have chosen the version "3.6.10.FINAL" for our project. So click on the version and it will give the piece of code to be added for the pom.xml file. Copy this code and paste it in the pom.xml file under the dependencies tag. Once the piece of code has been added and saved, you can observe that maven downloads the jar that has been added for dependency. The following screens will make it more clear for understanding.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>

 <groupId>Spring_Hibernate_Maven</groupId>
 <artifactId>SpringHibernateMavenIntegration</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <packaging>jar</packaging>

 <name>SpringHibernateMavenIntegration</name>
 <url>http://maven.apache.org</url>

 <properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <junit.version>3.8.1</junit.version>
 </properties>

 <dependencies>
  <dependency>
   <groupId>junit</groupId>
   <artifactId>junit</artifactId>
   <version>3.8.1</version>
   <scope>test</scope>
  </dependency>

  <dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-core</artifactId>
   <version>3.6.10.Final</version>
  </dependency>

  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-orm</artifactId>
   <version>3.2.6.RELEASE</version>
  </dependency>

  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-context</artifactId>
   <version>3.2.6.RELEASE</version>
  </dependency>

 </dependencies>
</project>

We can also add the dependencies by clicking on the "Add" button in the "Dependencies" tab of the pom.xml file as shown in the below screens.

Maven tutorial

Maven Intro and Maven Integration for Eclipse

In this post we will see what Maven is and how to integrate Maven and Eclipse. Maven is a build tool. Maven provides developers a complete build lifecycle framework. Maven plugins help in building projects. Maven downloads project dependency libraries automatically. For this Maven needs internet connection.
The Maven and Eclipse integration can be done by a plugin. Follow the below steps to add Maven plugin to Eclipse.
As shown in the below picture, open Eclipse. Go to "Help" and select "Install New Software".
An "Install" window would open. Select "--All Available Sites--" under "Work with:" section. This would list all the available sites. It would take some time to search for the Maven site. So, type maven in the filter section. Select "Maven Integration for Eclipse".
There is another way to get the plugin. In the "Install" window, click on "Add" button. Open a browser and enter this URL: http://wiki.eclipse.org/M2E_updatesite_and_gittags. At the bottom of the page you can see m2e releases. Copy the latest release URL. Now come back to the "Install" window. Give some name in the Add Repository window, like "MavenPlugin" and then paste the copied URL in the Location box as shown in the below picture.
Select "Maven Integration for Eclipse" from the list and click "Next".
Select the "I accept the terms of the license agreement" and click "Finish".
Now Eclipse will install the required software as shown in the picture below.
Once the installation has been done, Eclipse will ask for restart. Click "Yes".
Once the Eclipse has been restarted, click File -> Other, as shown below.
In the New window, type "maven" in the Wizards section. If the Maven has been installed properly then you should see "Maven Project".

JSP interview questions and answers

  1. What is JSP?
    Answer: JSP stands for JavaServer Pages. JSP is java server side technology to create dynamic web pages. JSP is extension of Servlet technology to help developers create dynamic pages with HTML like syntax.
  2. Explain lifecycle of a JSP.
    Answer: Whenever a JSP page is requested for the first time or the JSP page has been modified, then JSP page is translated into a servlet class and the servlet class is compiled. This servlet class is equivalent to any servlet class but few changes in the names of the methods. A JSP Lifecycle consists of following steps:
    • Translation
    • Compilation
    • Loading the class
    • Instantiating the class
    • jspInit() invocation
    • _jspService() invocation
    • jspDestroy() invocation
    "jspInit()" method is similar to init() method of servlets. This method is invoked by the container only once when a JSP page is initialized. It can be overridden by a page author to initialize resources such as database and network connections, and to allow a JSP page to read persistent configuration data. "_jspService()" is the JSP method that gets invoked by JSP container for each client request by passing request and response object. Notice that method name starts with underscore to distinguish it from other lifecycle methods because we can’t override this method. All the JSP code goes inside this method and it’s overridden by default. A page author cannot override this method, as its implementation is provided by the container. "jspDestroy()" method is called by container when JSP is unloaded from memory such as shutting down application or container. This method is called only once in JSP lifecycle and we should override this method to release any resources created in JSP init method.
  3. Explain about implicit or well known variables in JSP
    Answer: According to the jsp specification we can use the following variables as part of the scriptlets without declaring the variables in the jsp page. These variables are called as "well known variables" or "implicit variables". There are 9 implicit variables:
    • pageContextis a convenient class which provides the methods like forward, include, getSession, getServletConfig, getServletContext, getRequest, getResponse, setAttribute, getAttribute, removeAttribute etc.
    • requestobject is an instance of a java class that implements the javax.servlet.http.HttpServletRequest interface. The request object can be used to get header information, parameters, attributes etc.
    • responseobject is an instance of a java class that implements the javax.servlet.http.HttpServletResponse interface. Using the "response" object we can set the response content type, add cookie and redirect the response.
    • sessionobject is an instance of a java class that implements the javax.servlet.http.HttpSession interface. Using the "session" object we can store session state for a single user.
    • applicationobject is an instance of a java class that implements the javax.servlet.ServletContext interface. It gives facility for a JSP page to obtain and set information about the web application in which it is running.
    • outobject is an instance of the javax.servlet.jsp.JspWriter class. Using the "out" object we can send some content to the client. In other words we can write the output content.
    • configobject is instance of javax.servlet.ServletConfig implementation and used to get the JSP init params configured in deployment descriptor.
    • exceptionobject is instance of java.lang.Throwable class and used to provide exception details in JSP error pages.
    • pageobject is instance of java.lang.Object class and represents the current JSP page. page object provide reference to the generated servlet class. This object is very rarely used.
  4. What is a scriptlet?
    Answer: A scriptlet contains Java code that is written between <% and %> tags, which gets executed whenever a JSP page is invoked. The scriptlet code goes into service() method when the JSP page is translated into a servlet. For example: <% out.println("Hello World!"); %>
  5. What is a JSP declaration?
    Answer: A declaration declares one or more variables or methods that you can use in Java code later in the JSP file. A declaration block is enclosed between the <%! and %> tags. For example: <%! Date theDate = new Date(); %>
  6. What is a JSP expression?
    Answer: An expression is written between the <%= and %> tags. An expression is evaluated, converted to a String, and inserted where the expression appears in the JSP file. It is not required to end the expression with a semicolon, as it implicitly adds a semicolon to all the expressions within the expression tags. For example: Date: <%= new java.util.Date()%>
  7. What are JSP directives?
    Answer: JSP directives are placed between <%@ and %>. JSP directives are used to give special instructions to the container for the translation of JSP to servlet code. These directives affects the overall structure of the servlet class. Following are the directives that JSP provides:
    • page directive: page directive provide attributes that gets applied to the entire JSP page. They define page dependent attributes. Some of the page attributes are as follows: <%@ page import="java.util.Date,java.io.*" %>
      <%@ page buffer="20kb" %>
      <%@ page errorPage="errorPage.jsp" %>
    • include directive: The JSP include directive is used to include the contents of another file to the current JSP page. The files are included during the translation phase. The files to be included can be JSP, HTML etc. An example of include directive is: <%@ include file="two.jsp" %>
    • taglib directive: The JSP taglib directive is used to define a tag library with prefix that we can use in JSP. Declares a tag library, containing custom actions, used in the page. <%@ taglib uri="/WEB-INF/c.tld" prefix="c"%>
  8. Explain about JSP standard action tags.
    Answer: JSP provides with some standard action tags that affect the overall runtime behavior of the JSP. These action tags can be used to include a file, to forward a request to a new page, work with java bean objects. Some of the action tags available are as follows:
    • jsp:include - It includes a response from a servlet or a JSP page into the current page.
    • jsp:forward - To forward the request to another resource.
    • jsp:useBean - To get the java bean object and make it available for the page.
    • jsp:getProperty - It gets the value of a property from a JavaBean and adds it to the response.
    • jsp:setProperty - It sets the properties for a JavaBean.
  9. What is difference between include directive and jsp:include action?
    Answer: The differences between include directive and jsp:include action are as follows:
    1. The include directive is processed at the translation time while the include action is processed at the run time.
    2. The include action always includes the contents of the specified file irrespective of whether the specified file is a static resource or a dynamic resource whereas include action executed a specified dynamic resource and only the result gets included in the response of the calling JSP.
    3. In JSP include action, we can pass params to be used in the included resource with jsp:param action element but in JSP include directive we can’t pass any params.
  10. What is the difference between ServletContext and PageContext?
    Answer: ServletContext gives the information about the container whereas PageContext gives the information about the Request.
  11. Explain about JSP buffer.
    Answer: The JSP buffer is explained with example at ... "Click here"
  12. How do you handle errors in JSP?
    Answer: To handle errors in JSP, we need to set the attribute isErrorPage="true" and also set the ErrorPage to a page which need to be displayed when error occurs. To know more about the error page with an example ... Click here
  13. What are the scopes available in jsp:useBean tag?
    Answer: jsp:useBean tag has the following scopes available:
    1. page: This is the default scope. It specifies that we can use this bean within the JSP page.
    2. request: This scope has wider scope than page. It specifies that we can use this bean from any JSP page that processes the same request.
    3. session: This scope has wider scope than request. It specifies that we can use this bean from any JSP page in the same session whether processes the same request or not.
    4. application: This scope has wider scope than session. It specifies that we can use this bean from any JSP page for the entire application.
  14. What is the difference in using request.getRequestDispatcher() and context.getRequestDispatcher()?
    Answer: request.getRequestDispatcher(path) takes relative path of the resource whereas context.getRequestDispatcher(path) takes the absolute path of the resource.

Spring interview questions and answers

  1. What is spring?
    Answer: Spring is an open source framework, which is light weight. It resolves commonly and repeatedly occurred problems. Spring is famous for its modularity, which means we can use only those parts of spring that we need to build our application. Rest of the parts can be ignored.
  2. What is Inversion Of Control?
    Answer: Inversion of control or IoC is the core of spring framework. As the name suggests IoC manages java objects from construction to destruction. In other words it manages the life cycle of the object. For example, a person X is supposed to do a work. Instead of person X, person Y has done the work. The outcome of the person Y work is used by person X. We call this as "Inversion of Control". In struts we create the DAO object and call the methods. If we use spring IoC, spring is responsible to create DAO class object. Developer is responsible to call the methods of DAO.
  3. What is Dependency Injection?
    Answer: Dependency Injection (DI) is a flavor of Inversion of Control. The inversion of control is more general concept and dependency injection is a concrete form of IoC. Dependency is a process whereby objects define their dependency. There are two ways using which dependency injection can be achieved in spring. One is Setter method injection and the other is using Constructor injection.
  4. What is Aspect Oriented Programming or AOP?
    Answer: In simple words Aspect Oriented Programming (AOP) concept is similar to the triggers concept in data base. Using aspects Spring can add additional functionality to a method execution. This additional functionality could be before a method execution or after method execution.
  5. What is autowiring?
    Answer: The Spring container provides the functionality of connecting beans with each other automatically. Instead of developer injecting one bean into the other using "ref" attribute, Spring can look into the BeanFactory and decide how to inject one bean into the other. This is called as autowiring.
  6. What are the different modes of auto wiring?
    Answer: The autowiring functionality has five modes which can be used to instruct Spring container to use autowiring for dependency injection:
    • no/default
    • byName
    • byType
    • constructor
    • autodetect
    To know more about the auto wiring modes ... Click here
  7. Explain the different bean scopes available in spring.
    Answer: There are different bean scopes that are available in spring. They are:
    • singleton: When singleton scope is given, spring container will create only one instance for that bean.
    • prototype: When prototype scope is given, spring container can create any number of instances.
    • request: Request scopes a bean definition to a HTTP request.
    • session: Session scopes a bean definition to a HTTP session
    • global-session: Global-session scopes a bean definition to a global HTTP session.
  8. Explain about lazy-init concept in spring.
    Answer: Whenever the spring container object is created based on application context it creates all the spring beans and establish the dependencies for all the beans whose scope attribute is default/singleton. If we do not want the spring container to create all the spring beans then we need to set lazy-init to "true". By default this value is "false". When lazy-init is set to "true" then spring container will not create object immediately even if scope is set to "singleton". To know more about lazy-init concept ... Click here
  9. Explain bean life-cycle in spring Bean Factory Container.
    Answer: Bean life cycle in Spring Bean Factory Container is as follows:
    • The spring container finds the bean’s definition from the XML file and instantiates the bean.
    • Using the dependency injection, spring populates all of the properties as specified in the bean definition.
    • If the bean implements the BeanNameAware interface, the factory calls setBeanName() passing the bean’s ID.
    • If the bean implements the BeanFactoryAware interface, the factory calls setBeanFactory(), passing an instance of itself.
    • If there are any BeanPostProcessors associated with the bean, their post- ProcessBeforeInitialization() methods will be called.
    • If an init-method is specified for the bean, it will be called.
    • Finally, if there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called.
  10. What does @Required annotation mean?
    Answer: The @Required annotation indicates that the affected bean property must be populated at configuration time, through an explicit property value in a bean definition or through autowiring.
  11. What does @Autowired annotation mean?
    Answer: The @Autowired annotation can be used to autowire bean on a setter method or on a constructor or on any method with arbitrary name. This annotation gives developer more control over the code.
  12. What does @Qualifier annotation mean?
    Answer: There may be a situation when you create more than one bean of the same type and want to wire only one of them with a property, in such case you can use @Qualifier annotation along with @Autowired to remove the confusion by specifying which exact bean will be wired.
  13. Explain about java based configuration in spring.
    Answer: Spring has introduced java based configuration to make the task of the developer easy. A developer, instead of writing the configuration in an XML file, can provide the details in the classes where the logic is written with the help of annotations. For example, "@Bean" annotation tells the spring that a method annotated with @Bean will return an object that should be registered as a bean in the Spring application context.
  14. Explain the different concepts in Aspect Oriented Programming
    Answer: There are different concepts in Aspect Oriented Programming. They are as follows:
    • Aspect
    • Join Point
    • Advice
    • Pointcut
    • Introduction
    • Target
    • AOP proxy
    • Weaving
    To know more about these concepts with an example ... Click here
  15. Explain spring MVC architecture.
    Answer: The spring MVC architecture has been explained clearly at ... Spring MVC architecture

JUnit interview questions and answers

  1. What is JUnit?
    Answer: JUnit is an open source testing framework for the java programming language. The test cases are written in java. Test-driven development is the ideal way to create a bug free code.
  2. How to write a Junit test class?
    Answer: Follow the below steps to write a test case:
    • The test class should extend TestCase class.
    • Define a method setUp() and initialize all the objects in that method. This setUp() method should be overridden.
    • Define a method tearDown() and release all the objects. This tearDown() method should also be overridden.
    • For each method, one or more test cases or test methods are written depending on the logic of the method.
  3. What is JUnit TestSuite?
    Answer: JUnit TestSuite is a composite of tests. The TestSuite is a container class under package junit.framework.TestSuite. TestSuite runs a collection of test cases. In JUnit, both @RunWith and @Suite annotation are used to run the suite test.
  4. What are Parameterized tests?
    Answer: Parameterized tests allow user or developer to run the same test over and over again using different values.
  5. What happens if a JUnit Test Method is declared as "private"?
    Answer: If a JUnit test method is declared as private, then the compilation would be successful, but the execution of the test method would fail. This is because JUnit requires all the test methods to be declared as "public" and the return type should be "void"
  6. How do you test a “private” method?
    Answer: "private" methods can only be accessed from the same class. No other class will have any access to the private method. Hence developer has to test the private methods manually.
  7. How can we test a method that do not return anything?
    Answer: There are some ways we can write test case for the methods which do not return anything. The way test cases are written depends on the logic of the method. For example.
    • A method may take parameters and then modify the values or variables of an object.
    • A method may modify values in a file or in a database.
    • A method may change values of static variables.
  8. How do you test a method that throws desired exceptions?
    Answer: Add the optional expected attribute to the @Test annotation. The following is an example test that passes when the expected FileNotFoundException is raised: "@Test(expected=FileNotFoundException.class)"

Hibernate interview questions and answers

  1. What is ORM?
    Answer: ORM stands for Object Relational Mapping. It is a programming technique for converting data between object oriented programming language and relational database. In simple words it helps in persistence of java objects to tables in the data base.
  2. What is Hibernate?
    Answer: Hibernate is a ORM framework that lets users to map java objects to relational tables using configuration files.
  3. What is SessionFactory?
    Answer: SessionFactory is a factory to create hibernate Session objects. SessionFactory is threadsafe so that many threads can access it concurrently (use the same SessionFactory). A SessionFactory is usually built once at the start up. Below is the code to create a SessionFactory
     //Creates a SessionFactory object
     SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); 
     
  4. What is Session?
    Answer: Session represents a small unit of work in Hibernate. Session is a light weight object and it is not thread safe that is session objects cannot be shared by multiple threads. Session objects are created by SessionFactory and they are closed when all the work is completed.
     //Creates a SessionFactory object
     SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
     //Creates a Session object
     Session session = sessionFactory.openSession(); 
     
  5. What is first level cache?
    Answer: First level cache is maintained at the session object. By default hibernate uses first level cache. Caching is used by hibernate to reduce the number of SQL queries it needs to generate within a given transaction.
  6. What is second level cache?
    Answer: Second level cache is associated at the SessionFactory object. The second level cache is available to the complete application. Hibernate first tries to retrieve the objects from first level cache that i.e. from session objects. If it cannot find then it goes to the second level cache which is SessionFactory. If hibernate cannot find objects in SessionFactory then it loads the objects from the database.
  7. What is query cache?
    Answer: Query cache stores results of SQL query. Query cache can be used along with second level cache for improved performance. An example of query cache that hibernate supports is EhCache.
  8. What is lazy initialization?
    Answer: Lazy initialization means, you do not initialize the entire object. You only initialize the first level variables member variables of the object and then you initialize the list only you need the list or only when we access the list. Click here to know more
  9. What are the different object states in hibernate?
    Answer: There are three different object states in hibernate. They are:
    • Transient
    • Persistent
    • Detached
    Transient objects are the newly created instances of the persistent class. It is the state of the objects that were never associated with a session. Persistence objects are the objects that gets associated with a hibernate session. Depending on the flush strategy these objects gets synchronized with the database. Objects which were associated with the session earlier, but currently not associated to any session are called detached objects. These detached objects can be re-attached to the session by calling update() (or) saveOrUpdate() methods.
  10. Explain the difference between session.lock and session.update in hibernate
    Answer: Both session.lock and session.update of session class are used to re-attach an object which has been detached earlier. But session.lock assumes that database is in sync with the detached objects and simply re-attaches the object to the session. Hence session.lock should be used very carefully.
  11. What is criteria API?
    Answer: Criteria is a simplified API for retrieving by composing criterion objects. This is very convenient approach for functionality like "search" screens where there is a variable number for conditions to be placed upon the result search. To know more about criteria api "Click here"

Interview Q & A

J K Rowling

The Biography of J K Rowling - "Hard work is the key to success"
She has come a long way from her early days of struggle to become one of the most popular writers of our time. She is a perfect example of person who has raised from poverty to wealth.
Joanne Kathleen Rowling or better known as J.K. Rowling was born on 31 July 1965. Rowling has a sister who is 2 years younger to her. To keep her sister entertained, Rowling had to create stories, which was probably the reason why she is one of the most successful story writers.
From an early age J.K. Rowling had an ambition to be a writer. As a child she often wrote fantasy stories which she would read out to her mother and sister. When she was six, she wrote down her first story about a rabbit called Rabbit. As a child she was shy and had no sports abilities, but she had a great love for literature.
After finishing school, her parents encouraged her to study French. She fulfilled her parents wish by studying French though she preferred to study English. After graduating, she moved to London and worked in several jobs. One of the jobs were to work as secretary. She soon resigned from the job because she was not organized and she would be day dreaming while at work. She was not happy with her life. She has resinged her job, her mother fell ill, she had a difficult relationship with her father.
In the early 1990, she had to travel from Manchester to London and the train was delayed for more than four hours. During the course of time, she first had the idea for a story about a young boy who goes to study at a school for wizards. Rest of the characters also popped up in her mind. She wanted to write it down but she did not have a pen. She was too shy to ask for a pen, so nothing has been written. As soon as she arrived at her destination, she started writing down "Harry Potter" book. She lost her mother in the same year due to her prolonged illness.
Rowling got a job as a English teacher in Portugal. It was here that she met her first husband, and together they had a child Jessica. The couple split after few years and Rowling was thrown out of the house. She had no other other choice but to return to England. She had to work in cafes for full time and as a single parent she had to take care of her child. She struggled to take time out to finish her first book 'Harry Potter and the Philosopher's Stone'. It took her 7 years to complete the book. After finishing the book, she sent to many agents. One of the agent had to spend more than a year to find a publisher. The book was published in 1997 and Rowling was paid an advance of £1500. She also received a grant from the Scottish arts council, which enabled her to write full time. After the books initial success in the UK, an American company Scholastic agreed to pay a remarkable £100,000 for the rights to publish in America. In 1998, Warner Bros secured the film rights for the books, giving a seven figure sum.
The seventh and final book in the Harry Potter series was published in the year 2007. It was one of the fastest selling books of all time. The potter books have gained worldwide attention and sold more than 400 million copies. According to Sunday Times, Rowling's estimated wealth stands at £530 million. Rowling has attributed her considerable achievements to her ability to focus all her attention on the things that mattered to her the most. She says that everyone has a hidden talent within him or her, you just have to reach out for it and allow it to bloom.
Some of the famous quotes by J K Rowling:
  1. "Anything's possible if you've got enough nerve."
  2. "It is our choices... that show what we truly are, far more than our abilities."
  3. "If you want to see the true measure of a man, watch how he treats his inferiors, not his equals."
  4. "It matters not what someone is born, but what they grow to be."
  5. "Wit beyond measure is a man’s greatest treasure."
  6. "The only way out is through."
  7. "I believe in hard work and luck, and that the first often leads to the second."

Spring MVC Login Page

Pointcut example

In this post we will see how to use pointcut. Below example explains the pointcut concept.
File: com.ram.model.Mobile.java
package com.ram.model;

public class Mobile {
 private String name;
 private int number;
 
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getNumber() {
  return number;
 }
 public void setNumber(int number) {
  this.number = number;
 }
 
}

File: com.ram.model.Landline.java
package com.ram.model;

public class Landline {
 private String name;
 private int number;
 
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getNumber() {
  return number;
 }
 public void setNumber(int number) {
  this.number = number;
 }
 
}

File: com.ram.service.Home.java
package com.ram.service;

import com.ram.model.Landline;
import com.ram.model.Mobile;

public class Home {
 private Mobile mobile;
 private Landline landline;
 
 public Mobile getMobile() {
  return mobile;
 }
 public void setMobile(Mobile mobile) {
  this.mobile = mobile;
 }
 public Landline getLandline() {
  return landline;
 }
 public void setLandline(Landline landline) {
  this.landline = landline;
 }
 
}

File: com.ram.aspect.PointcutAspect.java
package com.ram.aspect;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;

@Aspect
public class PointcutAspect {
 
 @Before("allGetters()")
 public void AdviceOne(){
  System.out.println("First advice from the method AdviceOne ...");
 }
 
 @Before("allGetters()")
 public void AdviceTwo(){
  System.out.println("Second advice from the method AdviceTwo ...");
 }
 
 @Pointcut("execution(* get*())")
 public void allGetters() {}
}

File: WEB-INF/dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
       http://www.springframework.org/schema/context 
       http://www.springframework.org/schema/context/spring-context-3.0.xsd
       http://www.springframework.org/schema/aop 
       http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
 
    <!-- Tells the spring that we are using aspects in our application -->   
    <aop:aspectj-autoproxy/>
       
  <bean name="mobile" class="com.ram.model.Mobile">
     <property name="name" value="Sony"></property>
     <property name="number" value="987654321"></property>
    </bean>
       
    <bean name="landline" class="com.ram.model.Landline">
     <property name="name" value="Optus"></property>
     <property name="number" value="0198765432"></property>
    </bean>
       
    <bean name="home" class="com.ram.service.Home" autowire="byName"/>
       
    <bean name="pointcutAspect" class="com.ram.aspect.PointcutAspect"/>
    
</beans>

File: com.ram.main.PointcutExample.java
package com.ram.main;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.ram.service.Home;

public class PointcutExample {
 public static void main(String[] args){
  ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
  Home home = context.getBean("home", Home.class);
  System.out.println(home.getLandline().getName());
  System.out.println(home.getLandline().getNumber());
 }
}

Run the PointcutExample.java program and you get the below output:

AOP wildcard expressions

In the previous post we have seen how to use a advice. But the problem with the example given in the previous post is that, the advice will run for any method which matches the criteria. In other words, the execution criteria given is generic and it is not specific to a particular method. Below are some of the execution criteria's which can be applied to advises.
@Before("execution(public String com.ram.model.Circle.getName())")
 public void LoggingAdvice(){
  ...
 }
The below code is an example of wildcard expression for the advice. It says that the advice should be run for all methods which are public and whose return type could be anything even void and whose method names start with 'get'.
@Before("execution(public * get*())")
 public void LoggingAdvice(){
  ...
 }
The below code is an another example of wildcard expression for the advice. It says that the advice should be run for all methods whose access modifier could be anything, whose return type could be anything, whose name start with 'get' and which will take zero or more parameters. The '..' indicate that the method can take zero or more parameters.
@Before("execution(* get*(..))")
 public void LoggingAdvice(){
  ...
 }

AOP Introduction and example

In this post, we will learn about AOP (Aspect Oriented Programming). AOP is a way to apply services also called as cross cutting services to objects. In simple words Aspect Oriented Programming (AOP) concept is similar to the triggers concept in data base. Using aspects Spring can add additional functionality to a method execution. This additional functionality could be before a method execution or after method execution. Before we proceed with the example, there are certain concepts in Aspect Oriented Programming which we need to understand.
  • Aspect: Aspect is a modularization on concern that cuts across multiple objects. In Spring AOP, aspects are implemented using regular classes (the schema-based approach) or regular classes annotated with the @Aspect annotation.
  • Join Point: It is a point during the execution of a program. Execution of a method or handling an exception are examples of Join Point.
  • Advice: Advice is the actual action to be taken either before or after the method execution. The method written is invoked by the spring framework during the program execution.
  • Pointcut: It is the point of execution in the application at which cross cutting concern need to be applied. In other words this is a set of one or more join points where an advice should be executed. We will learn more on pointcut in the next post.
  • Introduction: An introduction is also known as inner type declaration, allows you to add new methods or attributes to existing classes.
  • Target object: It is an object being advised by one or more aspects. Also referred to as the advised object. Since Spring AOP is implemented using runtime proxies, this object will always be a proxied object.
  • AOP proxy: It is an object created by the AOP framework in order to implements the aspect contracts.
  • Weaving: Weaving as the word means is to link aspects with other application types or objects to finally create an advised object.
File: com.ram.model.Triangle.java
package com.ram.model;

public class Triangle {
 private String name;

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }
 
}

File: com.ram.model.Circle.java
package com.ram.model;

public class Circle {
 private String name;

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }
 
}

File: com.ram.service.ShapeService.java
package com.ram.service;

import com.ram.model.Circle;
import com.ram.model.Triangle;

public class ShapeService {
 private Circle circle;
 private Triangle triangle;
 
 public Circle getCircle() {
  return circle;
 }
 public void setCircle(Circle circle) {
  this.circle = circle;
 }
 public Triangle getTriangle() {
  return triangle;
 }
 public void setTriangle(Triangle triangle) {
  this.triangle = triangle;
 }
 
}

There are different types of advice, but for this example lets take @Before. This advice executes before a join point.
File: com.ram.aspect.LoggingAspect.java
package com.ram.aspect;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class LoggingAspect {
 
 //Advice methods can be configured to run on a particular method.
 @Before("execution(public String getName())")
 public void LoggingAdvice(){
  System.out.println("Advice run. Get method called");
 }
}

File: WEB-INF/dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
       http://www.springframework.org/schema/context 
       http://www.springframework.org/schema/context/spring-context-3.0.xsd
       http://www.springframework.org/schema/aop 
       http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
 
    <!-- Tells the spring that we are using aspects in our application -->   
    <aop:aspectj-autoproxy/>
       
 <bean name="triangle" class="com.ram.model.Triangle">
  <property name="name" value="Triangle Name"></property>
 </bean>
 
 <bean name="circle" class="com.ram.model.Circle">
  <property name="name" value="Circle Name"></property>
 </bean>
 
 <bean name="shapeService" class="com.ram.service.ShapeService" autowire="byName"/>
 
 <bean name="loggingAspect" class="com.ram.aspect.LoggingAspect" />
    
</beans>

File: com.ram.main.AOPMain.java
package com.ram.main;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.ram.service.ShapeService;

public class AOPMain {
 public static void main(String[] args) {
  ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
  ShapeService service = context.getBean("shapeService", ShapeService.class);
  System.out.println(service.getCircle().getName());
 }

}

Run the AOPMain.java program and you get the below output:

Spring MVC hello world example

To understand Spring MVC, let's take the example of a simple hello world program.
Let us start our Hello World program with a controller. Any user request is first taken by the DispatcherServlet. The DispatcherServlet reads the URL, and executes the appropriate method in the controller. The class has been annotated with the @Controller annotation. This indicates that this class is a spring mvc controller and it is capable of handling web requests. This class will be recognized as a controller for processing requests, by the spring container when it scans the packages.
The helloWorld() method has been annotated with a @RequestMapping annotation. This annotation tells spring that this controller should process all the requests beginning with "/hello" in the URL. The URL may include "/hello.html" or "/hello.jsp" etc. Instead of using "/hello" in the helloWorld() we can use "/" as well. The helloWorld() method returns ModelAndView object. This object contains a message with key "message" and its related value "Hello World!". This data is passed to the view.
File: com.ram.controller.HelloWorldController.java
package com.ram.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HelloWorldController {
 @RequestMapping("/hello")
 public ModelAndView helloWorld(){
  
  String message = "Hello World!";
  return new ModelAndView("hello","message", message);
 }
}

File: WEB-INF/jsp/hello.jsp
<html>
<head>
    <title>Spring 3.0 Hello World</title>
</head>
<body>
    ${message}
</body>
</html>

This hello.jsp will display the value in the message that is passed by the controller.
File: WebContent/index.jsp
<html>
<head>
    <title>Spring 3.0 Hello World</title>
</head>
<body>
    <a href="hello.html">Click here</a>
</body>
</html>

File: WEB-INF/web.xml
<?xml version="1.0" encoding="UTF-8"?>
<vweb-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    
    <display-name>Spring 3 MVC Hello World</display-name>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
 
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>
    
</web-app>

In the "web.xml" we define DispatcherServlet which acts as front controller or the entry point for the request.
File: WEB-INF/dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
 http://www.springframework.org/schema/context
 http://www.springframework.org/schema/context/spring-context-3.0.xsd">
 
    <context:component-scan base-package="com.ram.controller" />
    
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
    
</beans>

In the "dispatcher-servlet.xml" file context:component-scan which will allow spring to load all the components from the package given. Next comes the bean id "view resolver". ViewResolver decides which View is responsible for rendering the response and also adds prefix and suffix.
Run the project "SpringMVCHelloWorld" and you get output in the browser as shown below. Click on "Click here" and "Hello World!" message is displayed.