Sunday 31 March 2013

Spring 3 MVC Form Validation

0 comments
In this tutorial, you will learn how to validate form value before saving it or inserting it into a database table.

 In the below example, the form contains the following fields :

 User Name
Age
Password

 If you left any field blank it will display message, also it check the minimum and maximum range of size.

 We uses two classes for validating size and empty field - javax.validation.constraints.Size & org.hibernate.validator.constraints.NotEmpty respectively.

 For this, we add two jars hibernate-validator-4.0.2.GA.jar and validation-api-1.0.0.GA.jar.
 Given below the Application flow followed by the code used in the application : Application Flow :
 The first page :



The jar file used in the application is given below :



web.xml






 Spring3LoginValidation

 

  dispatcher

  org.springframework.web.servlet.DispatcherServlet
  

  1

 

 

  dispatcher

  /forms/*

 

 

  index.jsp

 

index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>









Spring 3 Login Validation





Spring 3 Login Validation

dispatcher-servlet.xml






 

 


 


 


  

   /WEB-INF/views/

  

  

   .jsp

  

 


 

  

 



ValidationController.java

package com.controllers;

import com.form.ValidationForm;
import java.util.Map;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/validationform.html")
public class ValidationController {

 // Display the form on the get request
 @RequestMapping(method = RequestMethod.GET)
 public String showValidatinForm(Map model) {
  ValidationForm validationForm = new ValidationForm();
  model.put("validationForm", validationForm);
  return "validationform";
 }

 // Process the form.
 @RequestMapping(method = RequestMethod.POST)
 public String processValidatinForm(@Valid ValidationForm validationForm,
   BindingResult result, Map model) {
  if (result.hasErrors()) {
   return "validationform";
  }
  // Add the saved validationForm to the model
  model.put("validationForm", validationForm);
  return "validationsuccess";
 }

}

ValidationForm.java

package com.form;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.Size;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.format.annotation.NumberFormat;
import org.springframework.format.annotation.NumberFormat.Style;

public class ValidationForm {
 @NotEmpty
 @Size(min = 1, max = 20)
 private String userName;
 @NotNull
 @NumberFormat(style = Style.NUMBER)
 @Min(1)
 @Max(110)
 private Integer age;
 @NotEmpty(message = "Password must not be blank.")
 @Size(min = 1, max = 10, message = "Password must between 1 to 10 Characters.")
 private String password;

 public void setUserName(String userName) {
  this.userName = userName;
 }

 public String getUserName() {
  return userName;
 }

 public void setAge(Integer age) {
  this.age = age;
 }

 public Integer getAge() {
  return age;
 }

 public void setPassword(String password) {
  this.password = password;
 }

 public String getPassword() {
  return password;
 }
}

messages.properties

NotEmpty.validationForm.userName=User Name must not be blank.

Size.validationForm.userName=User Name must between 1 to 20 characters

validationform.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>

<%@taglib prefix="form" uri="http://www.springframework.org/tags/form"%>









Insert title here







 
User Name:
Age:
Password:

validationsuccess.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>

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









Insert title here





Welcome


Login form successfully validate the form values provided by you

The values provided by you are :

UserName :

Age :

password :

You can display error message using annotation or using "message" bean and "messages.properties" message file. We uses both type of methods to give you a demonstration. Download Complete Project

Sunday 24 March 2013

Spring 3 MVC Hello World Example

0 comments
In this tutorial, you will learn how to display "hello world" message in Spring 3.0 MVC

The step by step method will give you a clear idea : 

 Step1 : First of all, create a dynamic project in eclipse of name "Spring3_MVC_HelloWorld" as given below :




Step2 : Add the spring 3 jar files to the lib folder of WEB-INF. The added jar files are given below :

Step3 : Editing deployment descriptor(web.xml). The entry point of Spring MVC application is the Servlet define in deployment descriptor web.xml . Here, the dispatcher servlet(org.springframework.web.servlet.DispatcherServlet) is the entry point. This xml file maps the DispatcherServlet with url pattern *.html. The first file that will appear to you i.e. index.jsp should be defined as welcome file in the web.xml. The code of the web.xml file is given below :

 Spring3_MVC_HelloWorld
 
  index.jsp
 
 
  Dispatcher
  org.springframework.web.servlet.DispatcherServlet
  1
 
 
  Dispatcher
  *.html
 


One thing to note here is the name of servlet in tag in web.xml. Once the DispatcherServlet is initialized, it will looks for a file name [servlet-name]-servlet.xml in WEB-INF folder of web application. In this example, the framework will look for file called spring-servlet.xml. This xml file is known as configuration file. Configuration File Create a file Dispatcher-servlet.xml in the WEB-INF folder. Copy the following content in it :



 
 
 
 
 
 


  
  
  
  
 

The tag is used to load all the components from package com.controller and all its sub packages. This will load our HelloWorldController class. The bean viewResolver will resolve the view and add prefix string /WEB-INF/jsp/ and suffix .jsp to the view in ModelAndView. The HelloWorldController class return a ModelAndView object with view name ?hello?. This will be resolved to path /WEB-INF/jsp/hello.jsp. Step 4: Creation of index.jsp file which is the entry point for our application. Create index.jsp in WEB-INF folder and copy the following code in it :


Spring 3 Hello World Example


    
Show Me  Hello


Step5 : Create the controller class. First create package "com.controller" and add the class HelloWorldController.java in it and copy the following code in it :
package com.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() {
  System.out.println("In Controller");
  String message = "Hello World, Spring 3.0!";
  return new ModelAndView("hello", "message", message);
 }
}
When the Spring scans our package The annotation @Controller identify this class as the controller bean for processing request. The @RequestMapping annotation tells Spring that this Controller should process all requests beginning with /hello in the URL path. That includes /hello/* and /hello.html. This viewResolver bean in Dispatcher-servlet.xml will resolve the view and add prefix string /WEB-INF/jsp/ and suffix .jsp to the view in ModelAndView. Note that in our HelloWorldController class, we have return a ModelAndView object with view name ?hello?. This will be resolved to path /WEB-INF/jsp/hello.jsp . Step6 : The View in MVC. Create hello.jsp to display hello world message. This hello.jsp should be placed inside WEB-INF/jsp . Copy the content from the jsp file given below :


Spring 3 MVC Hello World Example


    ${message}


Output : When you execute the application :


Download Complete Project

Tuesday 19 March 2013

Measuring elapsed time using Spring StopWatch

0 comments

Measuring elapsed time using Spring StopWatch

package Core;

import org.springframework.util.StopWatch;

public class ExecutionTimeStopWatch {
 void method() throws InterruptedException
 {
  System.out.println("Execution Start");
  Thread.sleep(2000);
  int b = 12+7*88/9;
  System.out.println("Execution End "+ b);
 }
 
 public static void main(String[] args) {
  try {
   StopWatch watch = new StopWatch();
   
   ExecutionTime obj = new ExecutionTime();
   watch.start();
   obj.method();
   watch.stop();
   System.out.println("Time Taken: "+ watch.getTotalTimeMillis());
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
 }
}



Thursday 14 March 2013

Spring Bean Scopes

0 comments
Spring framework supports five type of scopes and for bean instantiation as of Spring 3.0 and also we can create a custom scope.
  1. singleton
  2. prototype
  3. request
  4. session
  5. global_session

1. singleton scope

singleton is the default scope.  Singleton Design Pattern requires no introduction as it is the easiest of all to understand. In the bean definition if the scope is not given, then by default singleton scope is assumed. In a given Spring container a singleton scoped bean
will be instantiated only once and the same will be used for its lifetime.
<bean id=zooEntity class=com.entities.Zoo
/>
<!-- if scope is not given, singleton is assigned as default scope, therefore both these configurations are same -->
<bean id=zooEntity class=com.entities.Zoo scope=singleton />

2. prototype scope

prototype scope allows the bean to be instantiated whenever it is requested. Every time a separate instance is created, just opposite to singleton. Stateful beans which hold the conversational state should be declared as prototype
scope.

3. request scope

Spring bean configured as request scope instantiates the bean for a single HTTP request. The instantiated object lives through the HTTP request. This is available only for web-aware spring application context.

4. session scope

session scope is very similar to  HttpSession Scope. Beans instantiated based on session scope scope lives through the HTTP session. Similar to request scope, it is applicable only for web aware spring application contexts.

5. global_session scope

global_session scope is equal as session scope on portlet-based web applications. This scope is also applicable only for web aware spring application contexts. If this is global_session is used in normal web application (not in portlet), then it will behave as session scope and there will not be any error.

Annotation based Spring scope configuration

/** * Annotation-based configuration of session scope */
@Component
@Scope("session")
public class ShopCart { }
Added to these built-in spring container scopes, we have an option to create custom scope. I will write a separate tutorial on spring custom scope.

Spring Security

0 comments

Spring MVC

0 comments

Spring Core

0 comments
Related Posts Plugin for WordPress, Blogger...