Thursday 24 October 2013

Spring Security Form Login Using Database

Posted by Kanhaiya
In this tutorial, we show you how to use database to perform the form-based login authentication in Spring Security.
Note
The last form-based login example will be reused, but the user details are move from XML file to database.
Technologies used :
  • Spring 3.0.5.RELEASE
  • Spring Security 3.0.5.RELEASE
  • Spring JDBC 3.0.5.RELEASE
  • MySQL 5.1
1. Database Tables
In database, you need to create two tables to store user details and user role details, one to many relationship, one user can contains many roles.

A simple and standard table design for user role relationship. And, you are allow to add extra columns for extra functionality. In additional, the table name and column name are not fixed, you can rename to whatever name.
drop table if exists `users`;
CREATE TABLE `users` (
  `USER_ID` INT(10) UNSIGNED NOT NULL,
  `USERNAME` VARCHAR(45) NOT NULL,
  `PASSWORD` VARCHAR(45) NOT NULL,
  `ENABLED` TINYINT(1) NOT NULL,
  PRIMARY KEY (`USER_ID`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;

drop table if exists `user_roles`;
CREATE TABLE `user_roles` (
  `USER_ROLE_ID` INT(10) UNSIGNED NOT NULL,
  `USER_ID` INT(10) UNSIGNED NOT NULL,
  `AUTHORITY` VARCHAR(45) NOT NULL,
  PRIMARY KEY (`USER_ROLE_ID`),
  KEY `FK_user_roles` (`USER_ID`),
  CONSTRAINT `FK_user_roles` FOREIGN KEY (`USER_ID`) REFERENCES `users` (`USER_ID`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;

Insert data for testing, now an user “kanha” is created and contains role named “ROLE_USER“.
INSERT INTO testdb.users (USER_ID, USERNAME,PASSWORD, ENABLED)
VALUES (100, 'kanha', '123456', TRUE);
 
INSERT INTO testdb.user_roles (USER_ROLE_ID, USER_ID, AUTHORITY)
VALUES (1, 100, 'ROLE_USER');

2. Spring JDBC
Create a data source bean, and connect to database via Spring JDBC.


 

  
  
  
  
 


3. Spring Security
In Spring security configuration file, use “jdbc-user-service” tag, and define your query to get the data from database.


 
  
  
 

 
  
   
  
 



4.Run this application
See screenshots of this tutorial.

1. If username or password is incorrect.


2. If username or password is correct.



Download Source Code
SrcCodes: Spring-Security-Login-db-Example.zip


References:
Spring Security form-based login example (user details in XML file)
Spring Security
Spring Security documentation

Saturday 19 October 2013

Spring Security Form Login Example

Posted by Kanhaiya
Spring Security allows developer to integrate security features with J2EE web application easily, it highjacks incoming HTTP request via servlet filters, and implements “user defined” security checking.

In this tutorial, we show you how to integrate Spring Security 3.0 with Spring MVC web application to secure URL access and how to create a custom login form and ask Spring Security to use it for login authentication. After implemented Spring security, to view the content of the page, users need to key in correct “username” and “password”.

Required Tools used:
  • Spring 3.0.5.RELEASE
  • Spring Security 3.0.5.RELEASE
  • JSTL 1.2
  • Tomcat 7
  • Jdk 1.7
  • Maven 3

1. Directory Structure
Review final directory structure of this tutorial


2. Spring Security Dependencies
To use Spring security 3.0, you need “spring-security-core.jar“, “spring-security-web.jar” and “spring-security-config.jar“. Spring libraries are available in Maven central repository.
File : pom.xml

	4.0.0
	Spring-Security-Form-Login-Example
	Spring-Security-Form-Login-Example
	0.0.1-SNAPSHOT
	war
	Spring-Security-Form-Login-Example
	Spring Security Form Login Example
	http://maven.apache.org

	
		3.0.5.RELEASE
	

	

		
		
			org.springframework
			spring-core
			${spring.version}
		

		
			org.springframework
			spring-web
			${spring.version}
		

		
			org.springframework
			spring-webmvc
			${spring.version}
		

		
		
			org.springframework.security
			spring-security-core
			${spring.version}
		

		
			org.springframework.security
			spring-security-web
			${spring.version}
		

		
			org.springframework.security
			spring-security-config
			${spring.version}
		

		
		
			javax.servlet
			jstl
			1.2
		

	
	
		SpringSecurityFormLoginExample
		
			
				maven-compiler-plugin
				3.1
				
					1.7
					1.7
				
			
			
				maven-war-plugin
				2.3
				
					webapp
					false
				
			
		
	

3. Integrate Spring Security
To integrate Spring security with web application, just declare “DelegatingFilterProxy” as servlet filter to intercept incoming request.

File : web.xml

	Spring-Security-Form-Login-Example

	
	
		mvc-dispatcher
		org.springframework.web.servlet.DispatcherServlet
		1
	
	
		mvc-dispatcher
		/
	

	
		org.springframework.web.context.ContextLoaderListener
	

	
		contextConfigLocation					/WEB-INF/mvc-dispatcher-servlet.xml, 			/WEB-INF/spring-security.xml 			

	
	
		springSecurityFilterChain
		org.springframework.web.filter.DelegatingFilterProxy
	

	
		springSecurityFilterChain
		/*
	


4. Spring Configuration
File : mvc-dispatcher-servlet.xml


	

	
		
			/WEB-INF/pages/
		
		
			.jsp
		
	

	
		
			
				mymessages
			
		
	


5. Spring Security : User Authentication
Defined your custom login form in Spring XML file (spring-security.xml). See explanation below :
  1. login-page=”/login” – The login form will be “/login”
  2. default-target-url=”/welcome” – If authentication success, forward to “/welcome”
  3. authentication-failure-url=”/loginfailed” – If authentication failed, forward to “/loginfailed”
  4. logout-success-url=”/logout” – If logout , forward to “/logout
File : spring-security.xml


	
		
				
	

	
		
			
				
			
		
	


6. Spring MVC Controller
Spring controller to handle what URL should go where.
/**
 * 
 */
package com.kanha.controller;

import java.security.Principal;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * @author kanhaiya.sahu
 *
 */
@Controller
public class LoginController {

	@RequestMapping(value="/welcome", method = RequestMethod.GET)
	public String printWelcome(ModelMap model, Principal principal ) {
 
		String name = principal.getName();
		model.addAttribute("username", name);
		model.addAttribute("message", "Spring Security Custom Form example");
		return "hello";
 
	}
 
	@RequestMapping(value="/login", method = RequestMethod.GET)
	public String login(ModelMap model) {
 
		return "login";
 
	}
	
	@RequestMapping(value="/loginfailed", method = RequestMethod.GET)
	public String loginerror(ModelMap model) {
 
		model.addAttribute("error", "true");
		return "login";
 
	}
	
	@RequestMapping(value="/logout", method = RequestMethod.GET)
	public String logout(ModelMap model) {
 
		return "login";
 
	}
}

7. Error Messages
Default Spring’s error message is not user friendly enough. So define a custom error message with override the Spring’s “key” with your custom error message. In this case, just override “AbstractUserDetailsAuthenticationProvider.badCredentials“.

File : mymessages.properties
AbstractUserDetailsAuthenticationProvider.badCredentials=Invalid username or password
8. JSP Views
In custom login form, you have to follow Spring Security standard name :
  1. j_spring_security_check – Login service
  2. j_spring_security_logout – Logout service
  3. j_username – Username
  4. j_password – Password
To display authentication error messages, use this :
${sessionScope["SPRING_SECURITY_LAST_EXCEPTION"].message}
File : login.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>


Login Page



	

Login with Username and Password (Custom Page)

Your login attempt was not successful, try again. Caused : ${sessionScope["SPRING_SECURITY_LAST_EXCEPTION"].message}
User:
Password:


File: hello.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>


	

Message : ${message}

Username : ${username}

" > Logout
Step 9: Run this Application
Run as a server and deploy in Tomcat 7. While browsing the project you will get the following screen for loging:

1. Access URL “http://localhost:8080/Spring-Security-Form-Login-Example/welcome“, Spring will redirect to your custom login form.
URL : http://localhost:8080/Spring-Security-Form-Login-Example/login


2. If username/password is wrong, authentication failed, display custom error messages.
URL : http://localhost:8080/Spring-Security-Form-Login-Example/loginfailed


3. If username/password is correct, authentication success, display requested page.
URL : http://localhost:8080/Spring-Security-Form-Login-Example/welcome



Download Source Code
SrcCodes: Spring-Security-Form-Login-Example.zip


Thursday 17 October 2013

Spring Security Tutorial

Posted by Kanhaiya
Introduction-
Spring Security is a framework that focuses on providing both authentication and authorization to Java applications. Like all Spring projects, the real power of Spring Security is found in how easily it can be extended to meet custom requirements.

Spring Security provides comprehensive security services for J2EE-based enterprise software applications. Spring Security framework was started as an "Acegi Security Framework", later adopted by Spring as its subproject "Spring Security". Spring Security targets two areas namely, Authentication and Authorization (or access-control).


  1. Authentication is the process of establishing a principal is who they claim to be (a “principal” generally means a user, device or some other system which can perform an action in your application).
  2. Authorization refers to the process of deciding whether a principal is allowed to perform an action within your application. To arrive at the point where an authorization decision is needed, the identity of the principal has already been established by the authentication process. These concepts are common, and not at all specific to Spring Security.
Spring Security Concepts-
Spring Security works around two core areas of security, Authentication and Authorization.

"Authentication" is the assurance that the user is actually the user he is claiming to be, for example, when the user logs into any application and gives his credentials, he authenticates himself. At the authentication level, spring supports various authentication models such as Http Basic authentication, Form Based authentication.

"Authorization" is the assurance that the user is allowed to access only those resources that he is authorized to use. For example, in a corporate application, there are some parts of an application where only admin have access and to some parts all the employees have access. These access rules are determined by the access rights given to each user of the system. At the authorization level, spring targets three main areas: authorizing web request, authorizing whether methods can be invoked and authorizing access to individual domain object instances.

Features-
  • Comprehensive and extensible support for both Authentication and Authorization
  • Protection against attacks like session fixation, clickjacking, cross site request forgery, etc
  • Servlet API integration
  • Optional integration with Spring Web MVC
  • Role based authorization control
  • Easy to configure with database based authentication and authorization
  • Encrypted password
  • Form authentication
  • File bases user authentication and authorization
Getting Started-
To get started with the implementation, following jars need to be present in the class path of the project.
  • Core - spring-security-core.jar
  • Web - spring-security-web.jar
  • Config - spring-security-config.jar
Namespace Configuration-
The namespace configuration of the spring provides lot of shortcuts that hides much of the complexity of the framework. To start with this configuration, define a security filter in web.xml as shown below:

  springSecurityFilterChain
  org.springframework.web.filter.DelegatingFilterProxy


   springSecurityFilterChain 
  /*

In the above configuration, DelegatingFilterProxy delegates the control to a filter implementation which is defined as a bean named springSecurityFilterChain. This bean is an infrastructure internal bean to handle namespace configurations. Once this configuration is done, all the incoming requests enter the spring framework for security checks.

Security Configuration-
The security configuration is done in XML file and can have any name such as applicationContext-security.xml. This file needs to be loaded explicitly from web.xml. This is done by adding ContextLoadListener. The following lines needs to be added before security filter definition in web.xml.

   contextConfigLocationWEB-INF/applicationContext-security.xml

    org.springframework.web.context.ContextLoaderListener


applicationContext-security.xml
When the namespace configuration is used, spring-config.jar needs to be present in the classpath. The first line in this XML file is the schema definition as shown below:

    ...

The minimal namespace configuration looks like:

 



    
      
        
        
      
    
 
The above configuration declares that all the urls in the application will be intercepted for the security checks and the urls can only be accessed by the user with role ROLE-USER. The attribute "auto-config=true" defines three elements , and .The default configuration always chooses http-basic authentication model. If the model needs to be changed to the form-login model, then the following configuration is needed.

    
    
    
This configuration is done to enable form-login authentication model where the login page is login.jsp. Note that in the intercept tag, pattern for login.jsp is given and access rule is defined as IS_AUTHENTICATED_ANONYMOUSLY. That means login.jsp is not checked for security, which makes sense as login.jsp is the starting point from where the user is authenticated.

The tag processes the authentication information; defines the credential information and the roles given to each user (authentication information).

The above configuration defines the very minimalistic approach for security. But, when it needs customization according to business requirements, it is very important to understand what happens internally. Spring Security framework is a chain of filters, with each filter having certain responsibility. The next section opens the namespace configuration to bean configuration to understand the flow and responsibility of each filter.

Lets see some applications which describe the Spring Security-

  1. Spring Security form-based login example (user details in XML file)
    Customize login form for authentication, password in xml file.
  2. Spring Security form-based login example (user details in database)
    Customize login form for authentication, password in database.


References:
Spring Security
Spring Security documentation

Monday 14 October 2013

Spring 3 MVC hello world application with maven

Posted by Kanhaiya
Before you start this Spring 3 MVC tutorial, please refer to this new features in Spring 3 documentation, so that you have a brief idea of what’s new in Spring 3.

In this tutorial, I am building hello world application using spring 3 (mvc) framework. Follow the given steps and learn the basics.

Technologies used :
  1. Spring 3.1.2.RELEASE
  2. JDK 1.6
  3. Maven 3
  4. Eclipse 3.6
  5. Maven Integration for Eclipse WTP

Step 1. Create a Dynamic Web Project
When you create adynamic web project in eclipse then by default it showing this


Then remove this src folder and add new folders like this src/test/java, src/test/resources, src/main/java, src/main/resources


Then click next then by default it showing this


Change the "Content directory" name WebContent to webapp then finish it.

We are following this process because here we are creating maven web project. Every maven project follow this standard directory structure .

Then right click on project go for configure option and convert it into maven project with select WAR option because you create a web project. It create a entry of pom.xml.

Step 2. Add Project Dependencies in pom.xml
Add dependency of Spring MVC 3 in Maven pom.xml.
http://maven.apache.org

 
  3.1.2.RELEASE
 

 
  
  
   org.springframework
   spring-webmvc
   ${org.springframework.version}
  
 
Note : Spring MVC depends on spring-core, spring-beans, spring-context, spring-web. If we add 'spring-webmvc' dependency in pom.xml then all the required dependencies / libraries will be automatically downloaded and added to the project's classpath by Maven.

Step 3.
Open command prompt and go to current working project directory path as you created. Now execute below command.
mvn clean install
mvn eclipse:eclipse
mvn resources:resources


By this command it will download all dependencies to maven local repository and include them in project build. After that all these dependencies (all jars) copy in src/main/webapp/WEB-INF/lib from target project

Step 4. Controller Class and Request Mapping
Create a spring controller class called SpringMVCHelloController in package 'com.kanha.controller' and copy following code into it.
/**
 * 
 */
package com.kanha.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author kanhaiya.sahu
 *
 */
@Controller
public class SpringHelloWorldController {
 
 @RequestMapping("/")
 public String printHelloWorld(Model model) {
  model.addAttribute("message", "Spring MVC Hello World Example By Kanhaiya!");
  return "helloWorld";
 }

}
@Controller annotation indicates that this class serves the role of a controller. The Servlet dispatcher scans @Controller annotated Controller classes for mapped handler methods and detects @RequestMapping annotations.
@RequestMapping annotation specifies that this handler method will process all requests beginning with '/' in the URL and return the logical view name.
'org.springframework.ui.Model' object is a map which is passed by the Spring container while invoking the handler method 'printHelloWorld'. The message string has been added to 'Model' object against the key 'message'. This model object is available in the view. We can use the key 'message' to get the value and display the same in the UI.

Step 5. Create a JSP page as View
Now we need to create a JSP page called helloWorld.jsp under 'WEB-INF/pages' directory and copy the following jsp file content. We have used the key 'message' in expression '${message}' to get the value and display the same in 'helloWorld.jsp'.
<%@ page language="java" caontentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> 

  
  Spring MVC Hello World Example Using Maven  


${message}


Step 6. Add Spring Configuration File
Create an xml file called dispatcher-servlet.xml under 'WEB-INF' directory and copy the following content.



    
    
    
 
  
  
 

The above configuration file provides context information to the Spring container. '<context:component-scan>' enables the auto-detection of annotated components (like Controller, Service etc). So spring container will scan and load all the annotated component (e.g. SpringMVCHelloController) from the package 'com.kanha.controller' and it's subpackages.

'<mvc:annotation-driven />' specifies that we are using annotation based configuration.

ViewResolver provides a mapping between logical view name and actual view. It enables us to render models in UI without tying us to a specific view technology like JSPs, JSF, Velocity templates etc. Handler method defined in Controller class must resolve to a logical view name. In our case, 'printHelloWorld' handler method returns 'helloWorld' view name. It gets resolved to the path 'WEB-INF/pages/helloWorld.jsp' by the 'InternalResourceViewResolver' by adding prefix '/WEB-INF/pages/' and suffix '.jsp' to the view name 'helloWorld'.

Step 7. Integrate Spring with Web Application


 SpringMVCHelloWorld

 
  dispatcher
  org.springframework.web.servlet.DispatcherServlet
  1
 
 
  dispatcher
  /
 


DispatcherServlet (Front Controller) is mapped with the '/'. Upon initialization of the DispatcherServlet, Spring MVC looks for a configuration file called [servlet-name]-servlet.xml under the WEB-INF directory and creates the beans defined there. In our case the file is 'dispatcher-servlet.xml'.

Step 8. Overall Project Structure


Step 9. Deploy and Run the Application
Right click on the project 'SpringMVCHelloWorld' and select from context menu 'Run As' --> 'Run on Server'. Select the existing tomcat server. The web application will be deployed in the tomcat web server and a browser will be opened with 'Hello World!' message as shown below



Download Source Code with lib
SrcCodes : SpringMVCHelloWorld.zip


Thursday 10 October 2013

Spring 3.0.x Web MVC Framework

Posted by Kanhaiya

The Spring Framework is a popular open source application framework that can make Java EE development easier. It consists of a container, a framework for managing components, and a set of snap-in services for web user interfaces, transactions, and persistence. A part of the Spring Framework is Spring Web MVC, an extensible MVC framework for creating web applications.

Introduction to Spring Web MVC framework:-
Spring MVC is the web component of Spring’s framework. It provides a rich functionality for building robust Web Applications. The Spring MVC Framework is architected and designed in such a way that every piece of logic and functionality is highly configurable. Also Spring can integrate effortlessly with other popular Web Frameworks like Struts, WebWork, Java Server Faces and Tapestry. It means that you can even instruct Spring to use any one of the Web Frameworks. More than that Spring is not tightly coupled with Servlets or JSP to render the View to the Clients. Integration with other View technologies like Velocity, Freemarker.

Request Processing Lifecycle

In Spring Web MVC you can use any object as a command or form-backing object; you do not need to implement a framework-specific interface or base class. Spring’s data binding is highly flexible: for example, it treats type mismatches as validation errors that can be evaluated by the application, not as system errors. Thus you need not duplicate your business objects’ properties as simple, untyped strings in your form objects simply to handle invalid submissions, or to convert the Strings properly. Instead, it is often preferable to bind directly to your business objects.

Following is the Request process lifecycle of Spring 3.0 MVC:-
  1. The client sends a request to web container in the form of http request.
  2. This incoming request is intercepted by Front controller (DispatcherServlet) and it will then tries to find out appropriate Handler Mappings.
  3. With the help of Handler Mappings, the DispatcherServlet will dispatch the request to appropriate Controller.
  4. The Controller tries to process the request and returns the Model and View object in form ofModelAndView instance to the Front Controller.
  5. The Front Controller then tries to resolve the View (which can be JSP, Freemarker, Velocity etc) by consulting the View Resolver object.
  6. The selected view is then rendered back to client
Features of Spring Web MVC:-
  • Powerful and straightforward configuration of both framework and application classes as JavaBeans. This configuration capability includes easy referencing across contexts, such as from web controllers to business objects and validators.
  • Adaptability, non-intrusiveness, and flexibility. Define any controller method signature you need, possibly using one of the parameter annotations (such as @RequestParam, @RequestHeader, @PathVariable, and more) for a given scenario.
  • Reusable business code, no need for duplication. Use existing business objects as command or form objects instead of mirroring them to extend a particular framework base class.
  • Customizable binding and validation. Type mismatches as application-level validation errors that keep the offending value, localized date and number binding, and so on instead of String-only form objects with manual parsing and conversion to business objects.
  • Customizable handler mapping and view resolution. Handler mapping and view resolution strategies range from simple URL-based configuration, to sophisticated, purpose-built resolution strategies. Spring is more flexible than web MVC frameworks that mandate a particular technique.
  • Flexible model transfer. Model transfer with a name/value Map supports easy integration with any view technology.
  • Customizable locale and theme resolution, support for JSPs with or without Spring tag library, support for JSTL, support for Velocity without the need for extra bridges, and so on.
  • A simple yet powerful JSP tag library known as the Spring tag library that provides support for features such as data binding and themes. The custom tags allow for maximum flexibility in terms of markup code.
  • Beans whose lifecycle is scoped to the current HTTP request or HTTP Session. This is not a specific feature of Spring MVC itself, but rather of the WebApplicationContext container(s) that Spring MVC uses.

Model view controller is a software architecture design pattern. It provides solution to layer an application by separating three concerns business, presentation and control flow.
  • Model can be some DAO layer or some Service Layers which give some information about request or requested information or Model can be a POJO which encapsulates the application data given by the controller.
  • View is responsible for rendering the model data and in general it generates HTML output that the client's browser can interpret.
  • Controller is responsible for processing user requests and building appropriate model and passes it to the view for rendering.


Advantages of Spring MVC Framework:-
  • Supports RESTful URLs.
  • Provide a very clean division between controllers, JavaBean models, and views.
  • Annotation based configuration(i.e. you may reduce the metadata file or less of configuration).
  • Supports to plug with other MVC frameworks like Struts, Struts2, WebWorks etc.
  • Flexible in supporting different view types like JSP, velocity, XML, PDF, Tiles etc.
Front Controller is very important component one which route the all the requests into framework control that means when ever requests land on different controllers it queues that request to the controller of framework without this MVC framework will not may be able to take control of the request at landing at the application. So front controller is not only capture the request but also the following responsibility-
  • It initialize the framework to cater to the requests.
  • Load the map of all URLs and the components responsible to handle the request.
  • Prepare the map for the views.

Spring 3 MVC Basic Architecture:-
The Spring web MVC framework provides model-view-controller architecture and ready components that can be used to develop flexible and loosely coupled web applications. The MVC pattern results in separating the different aspects of the application (input logic, business logic, and UI logic), while providing a loose coupling between these elements.


In Spring 3 MVC framework Dispatcher Servlet access Front Controller which handles all coming requests and queses for forward to the different controller.
  1. Whenever request lands the dispatcher servlet consult with HandlerMapping (HandlerMapping- is a component which have the map of URL and Controller which need to be invoked for that particular request which lands with URL)
  2. Then Dispatcher servlet has information about which is controller need to be invoked.
  3. Then that controller will be invoked.
  4. Then Controller can request the model for some information. (about some DAO, Service layer or Data in POJO, or data in database using business logic)
  5. Once process has been done then dispatcher servlet get the response then dispatcher servlet will get view resolver to build the view and view resolver look out what view has being configured it has been JSP, Velocity, XML etc. based this configuratin view has been prepared and the information from model i.e. POJO it will be put on the view and response will be send back to browser.
Spring 3 MVC Request Flow:-

  1. Request lands to Front Controller i.e. DispatcherServlet
  2. Capture the Request Locale i.e use for internationalization i.e Read .properties files
  3. Then check for multipart-file(MIME type header or not) upload data from distributed application
  4. Then consult with HandlerMapping for which Controller to be invoked
  5. Then responsibility is given to the Handler Chain
  6. This Handler Chain is responsible to be invoked some of the interceptors that needs to be invoked before of a controller and after the controller that means interceptors are here like very to similar to the filters that help to separate the pre-process logic and post-process logic.
  7. After process of pre-process interceptor return to the controller process the post-process logic.
  8. Then return to the view resolver prepared the view based on your configuration decide the which configuration (JSP, Velocity, PDF etc.) to be invoked.
  9. After choosing view technology prepare the view and return the response back to the client.
Framework- Initialization:-
MultipartResolver:-
Spring has built-in multipart support to handle file uploads in web applications. By default, no multipart handling will be done by spring framework. The spring framework will only track for the multipart requests only when there is a component of type MultipartResolver is registered in the spring mvc configuration file.

LocaleResolver:-
Spring has a wonderful support for the Internationalization. The DispatcherServlet enables to automatically resolve the locale in the request. This is done using the LocaleResolver component. The different LocaleResolvers implementations are AcceptHeaderLocaleResolver, CookieLocaleResolver, SessionLocaleResovler etc., These components scan the request headers, cookies and session for the locale respectively.

ThemeResolver-
This component is used to apply different CSS based on the request and the current theme.

HandlerMapping-
This component decides on what controllers method needs to be invoked when a request with a HTTP Method arrives. Based on this components response, the DispatcherServlet will invoke the Controllers handler method.

HandlerAdapter-
Spring MVC gives support to handle the request to the Actions/Controllers of other MVC Frameworks. This component is not for the application developer. This is implemented by the advanced users who want to have their own flow for the request in the framework.

HandlerExceptionResolver-
This component helps to check if there are any exceptions that have occurred during the request processing and if picks the respective view configured for that exception and forwards it to the client.

RequestToViewNameTransaltor-
The RequestToViewNameTranslator helps to transform the URL of the incoming request to a view name.

ViewResolver-
This component plays a vital role in deciding on the view type that needs to be sent and also prepares the view.

All the above mentioned components ie. HandlerMapping, Controller and ViewResolver are parts of WebApplicationContext which is an extension of the plain ApplicationContext with some extra features for web applications.

Required Spring 3.0 MVC Configuration:-
Consider the following DispatcherServlet servlet configuration (in the web.xml file)


    
        golfing
        org.springframework.web.servlet.DispatcherServlet
        1
    

    
        golfing
        /golfing/*
    


With the above servlet configuration in place, you will need to have a file called /WEB-INF/golfing-servlet.xml in your application; this file will contain all of your Spring Web MVC-specific components (beans). You can change the exact location of this configuration file through a servlet initialization parameter.

Defining a Controller:-
@Controller
public class HelloWorldController {

    @RequestMapping("/helloWorld")
    public ModelAndView helloWorld() {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("helloWorld");
        mav.addObject("message", "Hello World!");
        return mav;
    }
}

As an example, with JSP as a view technology, you can use the UrlBasedViewResolver. This view resolver translates a view name to a URL and hands the request over to the RequestDispatcher to render the view.

    
    
    


Spring Web MVC Framework Examples:-
  1. Spring MVC Hello World Example
    This example will explain how to write a simple Spring Web Hello World application.
  2. Spring 3.0 MVC with Hibernate 3.0 CRUD Example using maven
    Learn how to configure Spring 3 MVC with Hibernate 3 Using CRUD Operation in Spring MVC Framework.



Reference
Web MVC framework

Wednesday 9 October 2013

Hello World Example Using Mongo Client Console on MongoDB

Posted by Kanhaiya

In this tutorial we'll take first step to write Hello World Example in the MongoDB. It'll show you how to do basic operations like create, update, find and delete record in MongoDB. These operations are performs using MongoDB client console and server console on localhost, same machine.

1. Install MongoDB:-
Just after downloading the MongoDB zip from its official site and unzip these file and locate to the c:/mongodb/ folder. Open command prompt and change directory to the c:/mongodb/bin/
and run the following command
c:/mongodb/bin>mongod

then you will get the following screen


2. Connect MongoDB:-
To connect MongoDB by uses this command

c:/mongodb/bin>mongo


3. Create a database or table:-
In MongoDB, both database and table are created automatically when the first time data is inserted. Uses use database-name, to switch to your database (even this is not created yet).

In below example, after you inserted a single record, database "testJavaDb", and table "users" are created on the fly.
C:\mongodb\bin>mongo
MongoDB shell version: 2.4.6
connecting to: test
> use testJavaDb
switched to db testJavaDb
> db.users.insert({firstName:"Kanhaiya", lastName:"Sahu", age:"26", companyName:
"TBSL"});
> db.users.find();
{ "_id" : ObjectId("52544875cb1f732ae68c79b5"), "firstName" : "Kanhaiya", "lastN
ame" : "Sahu", "age" : "26", "companyName" : "TBSL" }
>


Note: In MongoDB, collection means table in SQL.

Three database commands.
  1. show dbs – List all databases.
  2. use db_name – Switches to db_name.
  3. show collections – List all tables in the current selected database.

4. Insert A Record:-
To insert a record,
uses db.tablename.insert({data})
or db.tablename.save({data})
> db.users.save({firstName:"Cuty", lastName:"Pie", age:"22", companyName:"TBSL"}
);
> db.users.find();
{ "_id" : ObjectId("52544875cb1f732ae68c79b5"), "firstName" : "Kanhaiya", "lastN
ame" : "Sahu", "age" : "26", "companyName" : "TBSL" }
{ "_id" : ObjectId("5254510bcb1f732ae68c79b6"), "firstName" : "Cuty", "lastName"
 : "Pie", "age" : "22", "companyName" : "TBSL" }
>

5. Update A Record:-
To update a record, uses db.tablename.update({criteria},{$set: {new value}}).
In below example, the companyName of firstName: "Kanhaiya" is updated.
> db.users.update({firstName:"Cuty"},{$set:{companyName:"HCL"}})
> db.users.find();
{ "_id" : ObjectId("52544875cb1f732ae68c79b5"), "firstName" : "Kanhaiya", "lastN
ame" : "Sahu", "age" : "26", "companyName" : "TBSL" }
{ "_id" : ObjectId("5254510bcb1f732ae68c79b6"), "age" : "22", "companyName" : "H
CL", "firstName" : "Cuty", "lastName" : "Pie" }
>

6. Find Records:-
To find or query records, uses db.tablename.find({criteria}).

List all records from table "users".
> db.users.find();
{ "_id" : ObjectId("52544875cb1f732ae68c79b5"), "firstName" : "Kanhaiya", "lastN
ame" : "Sahu", "age" : "26", "companyName" : "TBSL" }
{ "_id" : ObjectId("5254510bcb1f732ae68c79b6"), "age" : "22", "companyName" : "H
CL", "firstName" : "Cuty", "lastName" : "Pie" }
>

7. Delete Record:-
To delete a record, uses db.tablename.remove({criteria}).
In below example, the record of firstName "Kanhaiya" is deleted.
> db.users.remove({firstName:"Kanhaiya"});
> db.users.find();
{ "_id" : ObjectId("5254510bcb1f732ae68c79b6"), "age" : "22", "companyName" : "H
CL", "firstName" : "Cuty", "lastName" : "Pie" }
>

Note:
To delete all records from a table, uses db.tablename.remove().
To drop the table, uses db.tablename.drop().

8. Help command in mongoDB:-
At last, uses help() to guide you how to do things in MongoDB.
help – All available commands.
> help
        db.help()                    help on db methods
        db.mycoll.help()             help on collection methods
        sh.help()                    sharding helpers
        rs.help()                    replica set helpers
        help admin                   administrative help
        help connect                 connecting to a db help
        help keys                    key shortcuts
        help misc                    misc things to know
        help mr                      mapreduce

        show dbs                     show database names
        show collections             show collections in current database
        show users                   show users in current database
        show profile                 show most recent system.profile entries wit
h time >= 1ms
        show logs                    show the accessible logger names
        show log [name]              prints out the last segment of log in memor
y, 'global' is default
        use                 set current database
        db.foo.find()                list objects in collection foo
        db.foo.find( { a : 1 } )     list objects in foo where a == 1
        it                           result of the last line evaluated; use to f
urther iterate
        DBQuery.shellBatchSize = x   set default number of items to display on s
hell
        exit                         quit the mongo shell
>

9. Help on db methods:-
db.help() – Shows help on db.
> db.help();
DB methods:
        db.addUser(userDocument)
        db.adminCommand(nameOrDocument) - switches to 'admin' db, and runs comma
nd [ just calls db.runCommand(...) ]
        db.auth(username, password)
        db.cloneDatabase(fromhost)
        db.commandHelp(name) returns the help for the command
        db.copyDatabase(fromdb, todb, fromhost)
        db.createCollection(name, { size : ..., capped : ..., max : ... } )
        db.currentOp() displays currently executing operations in the db
        db.dropDatabase()
        db.eval(func, args) run code server-side
        db.fsyncLock() flush data to disk and lock server for backups
        db.fsyncUnlock() unlocks server following a db.fsyncLock()
        db.getCollection(cname) same as db['cname'] or db.cname
        db.getCollectionNames()
        db.getLastError() - just returns the err msg string
        db.getLastErrorObj() - return full status object
        db.getMongo() get the server connection object
        db.getMongo().setSlaveOk() allow queries on a replication slave server
        db.getName()
        db.getPrevError()
        db.getProfilingLevel() - deprecated
        db.getProfilingStatus() - returns if profiling is on and slow threshold
        db.getReplicationInfo()
        db.getSiblingDB(name) get the db at the same server as this one
        db.hostInfo() get details about the server's host
        db.isMaster() check replica primary status
        db.killOp(opid) kills the current operation in the db
        db.listCommands() lists all the db commands
        db.loadServerScripts() loads all the scripts in db.system.js
        db.logout()
        db.printCollectionStats()
        db.printReplicationInfo()
        db.printShardingStatus()
        db.printSlaveReplicationInfo()
        db.removeUser(username)
        db.repairDatabase()
        db.resetError()
        db.runCommand(cmdObj) run a database command.  if cmdObj is a string, tu
rns it into { cmdObj : 1 }
        db.serverStatus()
        db.setProfilingLevel(level,) 0=off 1=slow 2=all
        db.setVerboseShell(flag) display extra information in shell output
        db.shutdownServer()
        db.stats()
        db.version() current version of the server
>


10. Help on collection (table name):-
db.collection.help() – Shows help on collection (table). you can replace collection with your table name for showing help
> db.collection.help();
DBCollection help
        db.collection.find().help() - show DBCursor help
        db.collection.count()
        db.collection.copyTo(newColl) - duplicates collection by copying all doc
uments to newColl; no indexes are copied.
        db.collection.convertToCapped(maxBytes) - calls {convertToCapped:'collec
tion', size:maxBytes}} command
        db.collection.dataSize()
        db.collection.distinct( key ) - e.g. db.collection.distinct( 'x' )
        db.collection.drop() drop the collection
        db.collection.dropIndex(index) - e.g. db.collection.dropIndex( "indexNam
e" ) or db.collection.dropIndex( { "indexKey" : 1 } )
        db.collection.dropIndexes()
        db.collection.ensureIndex(keypattern[,options]) - options is an object w
ith these possible fields: name, unique, dropDups
        db.collection.reIndex()
        db.collection.find([query],[fields]) - query is an optional query filter
. fields is optional set of fields to return.
                                                      e.g. db.collection.find( {
x:77} , {name:1, x:1} )
        db.collection.find(...).count()
        db.collection.find(...).limit(n)
        db.collection.find(...).skip(n)
        db.collection.find(...).sort(...)
        db.collection.findOne([query])
        db.collection.findAndModify( { update : ... , remove : bool [, query: {}
, sort: {}, 'new': false] } )
        db.collection.getDB() get DB object associated with collection
        db.collection.getIndexes()
        db.collection.group( { key : ..., initial: ..., reduce : ...[, cond: ...
] } )
        db.collection.insert(obj)
        db.collection.mapReduce( mapFunction , reduceFunction ,  )
        db.collection.remove(query)
        db.collection.renameCollection( newName ,  ) renames the col
lection.
        db.collection.runCommand( name ,  ) runs a db command with the
given name where the first param is the collection name
        db.collection.save(obj)
        db.collection.stats()
        db.collection.storageSize() - includes free space allocated to this coll
ection
        db.collection.totalIndexSize() - size in bytes of all the indexes
        db.collection.totalSize() - storage allocated for all data and indexes
        db.collection.update(query, object[, upsert_bool, multi_bool]) - instead
 of two flags, you can pass an object with fields: upsert, multi
        db.collection.validate(  ) - SLOW
        db.collection.getShardVersion() - only for use with sharding
        db.collection.getShardDistribution() - prints statistics about data dist
ribution in the cluster
        db.collection.getSplitKeysForChunks(  ) - calculates split
 points over all chunks and returns splitter function
>


Saturday 5 October 2013

Installation Process of MongoDB on Windows

Posted by Kanhaiya

This tutorial provides a method for installing and running the MongoDB server (i.e. mongod.exe) on the Microsoft Windows platform through the Command Prompt and outlines the process for setting up MongoDB as a Windows Service.

There are following steps to Install MongoDB on windows OS.

Step 1. Download MongoDB -
Download the MongoDB from the official MongoDB website. Pre built binary packages of MongoDb are available for both 32 bit and 64 bit. You can download it, and install.

Note: Always download the correct version of MongoDB for your Windows system. The 64-bit versions of MongoDB will not work with 32-bit Windows.
You can find the architecture of your version of Windows platform using the following command in the Command Prompt:
wmic os get osarchitecture

Step 2. Unzip MongoDB folder and creating directory -
Unzip it to your prefer location, for example : C:\mongodb\

Step 3. Set up the Environment -
Start the Command Prompt by selecting the Start Menu, then All Programs, then Accessories, then right click Command Prompt, and select Run as Administrator from the popup menu. In the Command Prompt, issue the following commands:

cd \
move C:\mongodb-win32-* C:\mongodb

Note: MongoDB is self-contained and does not have any other system dependencies. You can run MongoDB from any folder you choose. You may install MongoDB in any directory (e.g. D:\test\mongodb)

MongoDB requires a data folder to store its files. The default location for the MongoDB data directory is C:\data\db. Create this folder using the Command Prompt. Issue the following command sequence:
md data
md data\db

Note: You may specify an alternate path for \data\db with the dbpath setting for mongod.exe, as in the following example:
C:\mongodb\bin\mongod.exe --dbpath d:\test\mongodb\data

If your path includes spaces, enclose the entire path in double quotations, for example:
C:\mongodb\bin\mongod.exe --dbpath "d:\test\mongo db data"

Step 4. Start MongoDB -
To start MongoDB, execute from the Command Prompt:
C:\mongodb\bin\mongod.exe

This will start the main MongoDB database process. The waiting for connections message in the console output indicates that the mongod.exe process is running successfully.

Note: Depending on the security level of your system, Windows will issue a Security Alert dialog box about blocking “some features” of C:\\mongodb\bin\mongod.exe from communicating on networks. All users should select Private Networks, such as my home or work network and click Allow access. For additional information on security and MongoDB, please read the Security Concepts page.

Connect to MongoDB using the mongo.exe shell. Open another Command Prompt and issue the following command:
C:\mongodb\bin\mongo.exe


Note: Executing the command start C:\mongodb\bin\mongo.exe will automatically start the mongo.exe shell in a separate Command Prompt window.

For show all Databases use this command-
show dbs;


The mongo.exe shell will connect to mongod.exe running on the localhost interface and port 27017 by default. At the mongo.exe prompt, issue the following two commands to insert a record in the test collection of the default test database and then retrieve that record:
db.test.save( { a: 1 } )
db.test.find()


Note: mongo and mongo Shell Methods is very helpful if you want to develop any applications using JAVA.

Step 5. MongoDB as a Windows Service -
Setup MongoDB as a Windows Service, so that the database will start automatically following each reboot cycle.

Configure the System
You should specify two options when running MongoDB as a Windows Service: a path for the log output (i.e. logpath) and a configuration file.
  1. Create a specific directory for MongoDB log files:
  2. md C:\mongodb\log
  3. Create a configuration file for the logpath option for MongoDB in the Command Prompt by issuing this command:
  4. echo logpath=C:\mongodb\log\mongo.log > C:\mongodb\mongod.cfg
While these optional steps are optional, creating a specific location for log files and using the configuration file are good practice.

Install and Run the MongoDB Service
Run all of the following commands in Command Prompt with “Administrative Privileges:”
  1. To install the MongoDB service:
  2. C:\mongodb\bin\mongod.exe --config C:\mongodb\mongod.cfg --install Modify the path to the mongod.cfg file as needed. For the --install option to succeed, you must specify a logpath setting or the --logpath run-time option.
  3. To run the MongoDB service:
  4. net start MongoDB

Stop or Remove the MongoDB Service
  1. To stop the MongoDB service:
  2. net stop MongoDB
  3. To remove the MongoDB service:
  4. C:\mongodb\bin\mongod.exe --remove
Step# 6: In additional, MongoDB come with a web admin interface listening on port 28017:-



Friday 4 October 2013

Introduction to MongoDB and NoSQL Database

Posted by Kanhaiya


What is MongoDB?
MongoDB (from "humongous") is a cross-platform document-oriented database system. Classified as a "NoSQL" database, MongoDB eschews the traditional table-based relational database structure in favor of JSON-like documents with dynamic schemas (MongoDB calls the format BSON), making the integration of data in certain types of applications easier and faster.

MongoDB is a document database that provides high performance, high availability, and easy scalability.
  • Document Database
    • Documents (objects) map nicely to programming language data types.
    • Embedded documents and arrays reduce need for joins.
    • Dynamic schema makes polymorphism easier.
  • High Performance
    • Embedding makes reads and writes fast.
    • Indexes can include keys from embedded documents and arrays.
    • Optional streaming writes (no acknowledgments).
  • High Availability
    • Replicated servers with automatic master failover.
  • Easy Scalability
    • Automatic sharding distributes collection data across machines.
    • Eventually-consistent reads can be distributed over replicated servers.
Key MongoDB Features
MongoDB focuses on flexibility, power, speed, and ease of use:
  1. Flexibility
  2. MongoDB stores data in JSON documents (which we serialize to BSON). JSON provides a rich data model that seamlessly maps to native programming language types, and the dynamic schema makes it easier to evolve your data model than with a system with enforced schemas such as a RDBMS.
  3. Power
  4. MongoDB provides a lot of the features of a traditional RDBMS such as secondary indexes, dynamic queries, sorting, rich updates, upserts (update if document exists, insert if it doesn’t), and easy aggregation. This gives you the breadth of functionality that you are used to from an RDBMS, with the flexibility and scaling capability that the non-relational model allows.
  5. Speed/Scaling
  6. By keeping related data together in documents, queries can be much faster than in a relational database where related data is separated into multiple tables and then needs to be joined later. MongoDB also makes it easy to scale out your database. Autosharding allows you to scale your cluster linearly by adding more machines. It is possible to increase capacity without any downtime, which is very important on the web when load can increase suddenly and bringing down the website for extended maintenance can cost your business large amounts of revenue.
  7. Ease of use
  8. MongoDB works hard to be very easy to install, configure, maintain, and use. To this end, MongoDB provides few configuration options, and instead tries to automatically do the “right thing” whenever possible. This means that MongoDB works right out of the box, and you can dive right into developing your application, instead of spending a lot of time fine-tuning obscure database configurations.
Some Other Features
  • Ad hoc queries
  • MongoDB supports search by field, range queries, regular expression searches. Queries can return specific fields of documents and also include user-defined JavaScript functions.
  • Indexing
  • Any field in a MongoDB document can be indexed (indices in MongoDB are conceptually similar to those in RDBMSes). Secondary indices are also available.
  • Replication
  • MongoDB supports master-slave replication. A master can perform reads and writes. A slave copies data from the master and can only be used for reads or backup (not writes). The slaves have the ability to select a new master if the current one goes down.
  • Load balancing
  • MongoDB scales horizontally using sharding. The developer chooses a shard key, which determines how the data in a collection will be distributed. The data is split into ranges (based on the shard key) and distributed across multiple shards. (A shard is a master with one or more slaves.) MongoDB can run over multiple servers, balancing the load and/or duplicating data to keep the system up and running in case of hardware failure. Automatic configuration is easy to deploy, and new machines can be added to a running database.
  • File storage
  • MongoDB could be used as a file system, taking advantage of load balancing and data replication features over multiple machines for storing files. In a multi-machine MongoDB system, files can be distributed and copied multiple times between machines transparently, thus effectively creating a load balanced and fault tolerant system.
  • Aggregation
  • MapReduce can be used for batch processing of data and aggregation operations. The aggregation framework enables users to obtain the kind of results for which the SQL GROUP BY clause is used.
  • Server-side JavaScript execution
  • JavaScript can be used in queries, aggregation functions (such as MapReduce), are sent directly to the database to be executed.
  • Capped collections
  • MongoDB supports fixed-size collections called capped collections. This type of collection maintains insertion order and, once the specified size has been reached, behaves like a circular queue.

What is NoSQL?
A NoSQL database provides a mechanism for storage and retrieval of data that employs less constrained consistency models than traditional relational databases. Motivations for this approach include simplicity of design, horizontal scaling and finer control over availability. NoSQL databases are often highly optimized key–value stores intended for simple retrieval and appending operations, with the goal being significant performance benefits in terms of latency and throughput. NoSQL databases are finding significant and growing industry use in big data and real-time web applications. NoSQL systems are also referred to as "Not only SQL" to emphasize that they do in fact allow SQL-like query languages to be used.

NoSQL is a non-relational database management systems, different from traditional relational database management systems in some significant ways. It is designed for distributed data stores where very large scale of data storing needs (for example Google or Facebook which collects terabits of data every day for their users). These type of data storing may not require fixed schema, avoid join operations and typically scale horizontally.

The Need for NoSQL
Relational databases were never designed to cope with the scale and agility challenges that face modern applications – and aren't built to take advantage of cheap storage and processing power that's available today through the cloud. Relational database vendors have developed two main technical approaches to address these shortcomings:
  1. MANUAL SHARDING
  2. Tables are broken up into smaller physical tables and spread across multiple servers. Because the database does not provide this ability natively, development teams take on the work of deploying multiple relational databases across a number of machines. Data is stored in each database instance autonomously. Application code is developed to distribute the data, distribute queries, and aggregate the results of data across all of the database instances. Additional code must be developed to handle resource failures, to perform joins across the different databases, for data rebalancing, replication, and other requirements. Furthermore, many benefits of the relational database, such as transactional integrity, are compromised or eliminated when employing manual sharding.
  3. DISTRIBUTED CACHE
  4. A number of products provide a caching tier for database systems. These systems can improve read performance substantially, but they do not improve write performance, and they add complexity to system deployments. If your application is dominated by reads then a distributed cache should probably be considered, but if your application is dominated by writes or if you have a relatively even mix of reads and writes, then a distributed cache may not improve the overall experience of your end users. NoSQL databases have emerged in response to these challenges and in response to the new opportunities provided by low-cost commodity hardware and cloud-based deployment environments - and natively support the modern application deployment environment, reducing the need for developers to maintain separate caching layers or write and maintain sharding code.
NoSQL Database Types
  • Document databases pair each key with a complex data structure known as a document. Documents can contain many different key-value pairs, or key-array pairs, or even nested documents.
  • Graph stores are used to store information about networks, such as social connections. Graph stores include Neo4J and HyperGraphDB.
  • Key-value stores are the simplest NoSQL databases. Every single item in the database is stored as an attribute name, or key, together with its value. Examples of key-value stores are Riak and Voldemort. Some key-value stores, such as Redis, allow each value to have a type, such as "integer", which adds functionality.
  • Wide-column stores such as Cassandra and HBase are optimized for queries over large datasets, and store columns of data together, instead of rows

Contents:-
  1. Install MongoDB on Windows
  2. MongoDB Hello World Example



References: