Tuesday, 18 December 2012

Spring IoC Constructor Injection

Posted by Naveen Katiyar On 03:45 7 comments

Spring IoC Constructor Value Injection

Spring IoC Constructor Value Injection is a method of constructor injection in which the value of the attributes of a bean are set using constructor of the class. That means the constructor of the bean must be defined to accept attributes values and set the values to bean properties.
We will see the method of using Spring IoC Constructor Value Injection to set dependencies in Person bean.


Person Bean Code (Person.java)
 package com.naveen.beans;

public class Person {
    private String firstName = null;
    private String lastName = null;

    public Person(String firstName, String lastName){
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String getName(){
        return firstName + " " + lastName;
    }
}

Here, Person bean has two properties and constructor of Person bean allow to set the value of the properties. So, we can use Spring IoC Constructor Value Injection to inject the value of “firstName” and “lastName” in Person.



Spring IoC Bean Configuration file(spring-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: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">

    <bean id="person" class="com.naveen.beans.Person">
        <constructor-arg name="firstName" value="Rita"/>
        <constructor-arg name="lastName" value="Josap"/>
    </bean>
</beans>

In Spring IoC Bean Configuration file, we have configure Person class as a spring bean. <constructor-arg/> tag is used to set constructor parameter values in Spring IoC container. “name” attribute is used to specify the name of the constructor parameter and “value” attributes says the value to be set on it.

SpringBeanTestRunner class to test the example


package com.naveen.runner;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.naveen.beans.Person;

public class SpringBeanTestRunner {

    public static void main(String[] args) {
        System.out.println("Initialing bean factory");
        BeanFactory beanFactory = new ClassPathXmlApplicationContext("spring-servlet.xml");
        System.out.println("Getting person bean");
        Person person = (Person)beanFactory.getBean("person");
        System.out.println("Person Name is " + person.getName());
    }
}
 


In our example runner class, uses ClassPathXmlApplicationContext to load the Spring IoC configuration file “app-config.xml” and configure the beans specified in the configuration file. BeanFactory instance is used to get the person bean and “getName” method is used to print the name in Person bean instance.

That's it,you can run the application by making the changes in source code of previous tutorials.



Spring IoC Constructor Type Injection

In this tutorial, we will learn how we can provide constructor argument value of a bean using data type of argument. Spring IoC Constructor Type Injection is a method in which we provide dependency data on the basis of data type of the Constructor Type. If more than one argument is present in the Constructor of same data type than Spring IoC Container set the value according to the position of the arguments respectively.
Our following example will show the process of using Spring IoC Constructor Type Injection in practical. In our example, there is Peron class which we will configure as a Spring Bean.


Person Bean Code (Person.java)

package com.naveen.beans;

public class Person {
    private String firstName = null;
    private String lastName = null;
    private int age;

    public Person(String firstName, String lastName, int age){
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
    }

    public String getPersonDetail(){
        return "Name :" + firstName + " " + lastName +"\nAge : " + age;
    }
}

Person bean contains three properties,”firstName”, “lastName” and “age”, which are set through constructor of Person class.


Spring IoC Bean Configuration file(spring-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: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">

    <bean id="person" class="com.naveen.beans.Person">
        <constructor-arg type="int" value="21"/>
        <constructor-arg type="java.lang.String" value="Rita"/>
        <constructor-arg type="java.lang.String" value="Josap"/>
    </bean>

</beans>

In our Spring IoC bean configuration file, Person class has been configured as a Spring bean. To set the properties of Person bean we have used Spring IoC Constructor Type Injection.

<constructor-arg type=”int” value=”21″/>: <constructor-arg/> tag specifies that the property should be set using class constructor. There are two attributes we have used in this configuration. “type” attribute says the data type of the property and “value” attribute indicates the value of the property. If there are more then one constructor argument with same data type, spring will set the value sequentially.

SpringBeanTestRunner class to test the example


package com.naveen.runner;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.naveen.beans.Person;

public class SpringBeanTestRunner {

    public static void main(String[] args) {
        System.out.println("Initialing bean factory");
        BeanFactory beanFactory = new ClassPathXmlApplicationContext("spring-servlet.xml");
        System.out.println("Getting person bean");
        Person person = (Person)beanFactory.getBean("person");
        System.out.println("Person Detail is " + person.getPersonDetail());
    }
}

SpringBeanTestRunner class helps us to test our example. It first creates BeanFactory instance from ClassPathXmlApplicationContext class which loads our Spring IoC Bean Configuration file and configues Person class as a bean. Then, “getBean” method of BeanFactory is used to get the instance of Person class. It prints details of person bean get from Spring IoC container.


That's it,you can run the application by making the changes in source code of previous tutorials.

Sunday, 16 December 2012

Spring IoC Setter Injection

Posted by Naveen Katiyar On 21:10 1 comment

Spring IoC setter value injection 

We will learn the process of setting property values of a bean using Spring IoC Setter Value Injection. For Spring IoC Setter Value Injection to work the bean class must contain setter of the property present.
In the following example we will consider a Person class which has two properties to construct the name of the person. We will set the property values in Spring IoC Bean Configuration file and the print the name of the person.

Person Bean class (Person.java)


package com.naveen.beans;

public class Person {
    private String firstName = null;
    private String lastName = null;

    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getName(){
        return firstName + " " + lastName;
    }
}

Person class has two properties “firstName” and “lastName ” and their getter and setters.

Spring IoC Bean Configuration file(spring-servlet.xml)

In configuration file Person class has been configured as a Spring IoC Bean as you seen in the previous tutorial.


<?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: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">

    <bean id="person" class="com.naveen.beans.Person">
        <property name="firstName" value="Carel"/>
        <property name="lastName" value="Staf"/>
    </bean>

</beans>


 
<property/> tag is used to set the value or reference of a property in bean class. This tag has two attributes here. “name” attribute holds the name of the property in bean. In this case there are two properties in Person bean, “firstName” and “lastName”. The “value” attribute holds the value to be set on the property. Spring IoC container will call property setter methods to set the property value.

You can also do the same thing with following bean configuration:

<bean id="person" class="com.naveen.beans.Person">
  <property name="firstName">
      <value>Carel</value>
  </property>
  <property name="lastName">
      <value>Staf</value>
  </property>
</bean>
 

If you want to set null value to a property, then you can use two way to do it :

Both the value will be set as null.

SpringBeanTestRunner class to test the example

Our SpringBeanTestRunner class contains the code to run the example. The runner class first create BeanFactory instance using our Spring IoC Bean Configuration file (spring-servlet.xml) and then get the instance of person bean to call the method “getName’ in it. 


package com.naveen.runner;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.naveen.beans.Person;

public class SpringBeanTestRunner {

    public static void main(String[] args) {
        System.out.println("Initialing bean factory");
        BeanFactory beanFactory = new ClassPathXmlApplicationContext("spring-servlet.xml");
        System.out.println("Getting person bean");
        Person person = (Person)beanFactory.getBean("person");
        System.out.println("Person name is " + person.getName());
    }
}

That's it.You can run the previous example after making above changes.



Spring IoC Setter Bean Ref Injection 

In this session we will go through an example that will make you understand Spring IoC Setter Bean Ref Injection. Bean ref injection means to to pass reference of one bean to another. So the example will show the method of setting one bean reference to another bean in Spring IoC Bean Setter Injection.
In the following example, there is a Address bean to store address of a person and we will pass the reference of Address bean to Person bean using Spring IoC Setter Bean Ref Injection.

Address bean (Address.java)

Address bean has two properties and getter/setter of the properties to store city and country of a person.


package com.naveen.beans;

    public class Address {
    private String city = null;
    private String country = null;
    public String getCity() {
        return city;
    }
    public void setCity(String city) {
        this.city = city;
    }
    public String getCountry() {
        return country;
    }
    public void setCountry(String country) {
        this.country = country;
    }
    @Override
    public String toString() {
        return "City : " + city + ", Country" + country;
    }
}

Person bean code (Person.java)

Person bean contains three properties “firstName”, “lastname” and “address” and their getter and setter.


package com.naveen.beans;

public class Person {
    private String firstName = null;
    private String lastName = null;
    private Address address = null;

    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public Address getAddress() {
        return address;
    }
    public void setAddress(Address address) {
        this.address = address;
    }
    public String getName(){
        return firstName + " " + lastName;
    }

    public String getPersonDetail(){
        return "Name :" + getName() + "\n" + address.toString();
    }
}

Spring IoC Bean Configuration file(spring-servlet.xml)

We have configure both the beans Address and Person in our Spring IoC Bean Configuration file.


<?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: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">
    <bean id="address" class="com.naveen.beans.Address">
        <property name="city" value="New York"/>
        <property name="country" value="USA"/>
    </bean>
    <bean id="person" class="com.naveen.beans.Person">
        <property name="firstName" value="Carel"/>
        <property name="lastName" value="Staf"/>
        <property name="address" ref="address"/>
    </bean>
</beans>

You can see only one new thing from previous tutorial.
<property name=”address” ref=”address”/> : Here “ref” attribute says to Spring that Spring has to create the instance of address bean and set to the property of person bean.

SpringBeanTestRunner class to test the example

SpringBeanTestRunner class will get Person instance from Spring IoC Container and will call the method “getPersonDetail” method which will show the Name and Address of the person to test the example.


package com.naveen.runner;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.naveen.beans.Person;

public class SpringBeanTestRunner {

    public static void main(String[] args) {
        System.out.println("Initialing bean factory");
        BeanFactory beanFactory = new ClassPathXmlApplicationContext("spring-servlet.xml");
        System.out.println("Getting person bean");
        Person person = (Person)beanFactory.getBean("person");
        System.out.println("Person detail is " + person.getPersonDetail());
    }
}

That's it.You can run the previous example after making above changes. 

Thursday, 13 December 2012

Initializing a Spring IoC Bean

Posted by Naveen Katiyar On 21:37 3 comments

 Using Initialization method to initialize a Spring IoC Bean

With the previous tutorial, you know the process of registering a bean class with Spring IoC container using xml configuration files. In this tutorial we will see how to define an initialization method of bean to Spring IoC, so that Spring IoC container invokes the method after creating instance of the bean to perform some initialization work.

Tools Used:
  • Spring IoC Framework 3.0.3
In our example, we will define an initialization method of our Person class that will initialize the properties name and address of the Person class as value “Unknown”.

 Our Spring IoC Bean class with Initialization method


package com.naveen.domain;

public class Person {
    private String name;
    private String address;

    public void init(){
        this.name = "Unknown";
        this.address = "Unknown";
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    public String toString() {
        return "Name :" + this.name + " and Address : " + this.address;
    }
}

As you can see, the init() method works as a initialization method for Person bean class to initialize it’s properties with value “Unknown”.

Spring IoC Container configuration file
 
Now, we have to tell Spring IoC about the init() method, so that it can invoke it after creating the instance of  bean.


<?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: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">
    <bean id="person" class="com.naveen.domain.Person" init-method="init"/>
</beans>

init-metthod attribute of <bean/> tag is used for specifying the initialization method of bean.

Run the example to test the output


package com.naveen.runner;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.naveen.domain.Person;

public class SpringBeanTestRunner {

    public static void main(String[] args) {
        BeanFactory factory = new ClassPathXmlApplicationContext("servlet-config.xml");
        Person person = (Person)factory.getBean("person");
        System.out.println("Person detail is : " + person);
    }
}

Our test runner class will create the instance of BeanFactory using ClassPathXmlApplicationContext and load the configuration file, after that it will get the instance of Person bean from BeanFactory and print the Person bean on console.
While running the example in ellipse, you will get following result, which justify that initialization method has bean called by Spring IoC container.

Download Source code


Getting Started with Spring IoC

Posted by Naveen Katiyar On 02:32 No comments

Configuring Spring Bean and creating Spring Bean instance

This quick start will make you go through the implementations of Spring IoC example and illustrate how to configure your Spring Bean in Spring Configuration file and how to get instance of the bean using Spring IoC container. The example will take a example of Cat class (Cat.java) that will implement Speaks interface (Speaks.java) .


Speaks Interface (Speaks.java)

package com.naveen.beans;

public interface Speaks {
    public void talk();
}

Speaks interface has only one method.


Cat Class (Cat.java)

package com.naveen.beans;

public class Cat implements Speaks {

    public void talk() {
        System.out.println("Miao-miao");
    }
}

Cat class implements Speaks interface and define its own version of talk method.

Spring IoC Bean Configuration File to configure Cat class as a Spring Bean

spring-servlet.xml is our Spring Bean Configuration file that configures Cat class as a Spring IoC bean. 


<?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: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">

    <bean id="cat" class="com.naveen.beans.Cat"/>

</beans>

  • <beans/>: tag is the top level tag for Spring IoC bean configuration file. This tag contains all the beans configurations.
  • <bean/>: tag is used to configure a class as a bean in Spring IoC container. There are two attributes in it, one is “id”,is used to identify a bean in Spring IoC container and also used to get the instance of the bean from Spring IoC container, and the other one is “class”, which defines the fully qualified java class to be configure as a bean.
Runner class (SpringBeanTestRunner.java) of the example

SpringBeanTestRunner class will use Spring IoC to create instance of Cat class and will also invoke talk method in that instance.


package com.naveen.runner;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.naveen.beans.Speaks;

public class SpringBeanTestRunner {

    public static void main(String[] args) {
        System.out.println("Initialing bean factory");
        BeanFactory beanFactory = new ClassPathXmlApplicationContext("spring-servlet.xml");
        System.out.println("Getting cat bean instance");
        Speaks speaks = (Speaks)beanFactory.getBean("cat");
        speaks.talk();
    }
}

ClassPathXmlApplicationContext is used to read our Spring IoC bean configuration file “spring-servlet.xml” from class path and configures all beans. BeanFactory is the class that is used as a factory class of all the bean classes in Spring IoC bean configuration file. BeanFactory is also ClassPathXmlApplicationContext in respective to inheritance. Then we use “getBean” method of BeanFactory to get the bean instance by providing bean id as a parameter.

That's it.You can download  source from bellow links. Import the project in Eclipse and run SpringBeanTestRunner class to test Spring IoC Bean creation technique.

Download Source Code with jars

Click here to download source code

 

Wednesday, 12 December 2012

Introduction to Spring IoC

Posted by Naveen Katiyar On 23:58 1 comment

What is Spring IoC?

Before going through the Spring IoC tutorial, we must know what IoC is and why we use it in real life project development.

IoC or Inversion of Control, is also known as Dependency Injection, is used to create loosely coupled software components. Here, loosely coupled means less dependent software components. Let us illustrate it with an example:

There is a Report class used to generate reports of a bank account and ReportFileWriter is a class that creates a file and writes the report data to the file. Data is provided by the Report class to ReportFileWriter and in response it returns the file instance containing the report. So Report class is dependent on ReportFileWriter class. The dependency graph will be as follow:

Dependency Graph   

In this situation Report class will create an instance of class ReportFileWriter and will call the method “createReport” by passing report data:


ReportFileWriter fw = new ReportFileWriter();
fw.createReport(data);


If you think carefully, in this code we are using tight coupled dependency between Report class and ReportFileWriter class. That means if we want to change the file writer class to PDFReportFileWriter in future we have to change the code of Report class. They are tightly coupled.
IoC solves the problem of tight couple and helps to makes the software component loosely coupled, so that we can maintain our code pretty much easily.

IoC or Inversion of Control is a design pattern that provided instances of a bean or class to another when they needed. That means, we do not have to use new keyword to create instance of dependent class. We will just create a reference of dependent class and IoC pattern will set the instance to the reference when needed.

Now, using IoC Report class will have following code :


ReportFileWriter fw = null;

Public void setFw(ReportFileWriter fw){
    this.fw = fw;
}


IoC container will call setter method to set the instance of ReportFileWriter class. We have to configure the dependency in our classes in IoC configuration file. That will tell the IoC container when and how to inject the dependences.

Creating a better loosely coupled model

In this session we will see how to IoC to create effective loosely coupled components. Consider the previous example of Report class. There is a interface named “ReportWriter” which contains following definition:

public interface ReportWriter {
    public File createReport(ReportData data);
}


Any class implementing ReportWriter interface will be able to create report file of its own format. The report class contains following code:


private ReportWriter reportWriter = null;

public void setReportWriter(ReportWriter rw){
    this.reportWriter = rw;
}

//More Code
reportWriter.createReport(data);
//More Code


Now, we want to provide a facility to generate report in two formats, in PDF and in MS Word. So we will create two classes PDFReportWrite and MSWordReportWriter which will implement the interface ReportWriter. We will configure our IoC container in such a way that when we will need a PDF Report the IoC container will create instance of PDFReportWrite and set to ReportWriter reference of Report class and if we need MS Word format then IoC container will create instance of MSWordReportWriter and set to ReportWriter reference of Report class. No more we have to change the code of Report class to generate a different format report. This is the advantage of IoC design pattern.


Types of Dependency Injection:
There are three ways in which a IoC container can inject dependency class instance to the dependent class:
  1. Setter Injection: In this way, IoC container uses setter of the reference to set the instance of dependency class. Spring IoC provides setter Injection facility. We will learn about it with proper examples in next tutorial.
  2. Constructor Injection: In constructor injection IoC container users construction of dependent class to set the instance of dependency class. We will see example of constructor injection in upcoming tutorials using Spring IoC framework.
  3. Interface Injection: It is more complex process of dependency injection in which interfaces are used to inject the instances. Spring IoC container does not support this type of injection.





 

Spring MVC Ajax Tutorial

Posted by Naveen Katiyar On 22:47 2 comments

Ajax with Spring MVC 3 Using Annotations and JQuery

Its always been fun for me to work with Ajax! Is not it ? I will make it easy for you  to use Ajax with Spring MVC 3 and JQuery. This post will illustrate you how to use Ajax in real life practices of industrial coding. As usual, we will take an practical example of Ajax in Spring MVC 3 framework and will implement it and I will make the implementation easy by make you understand the topic.

Let us see what is our example’s requirement and how Spring MVC 3 Ajax facility will fulfill it :

In our example, we will make a list of students with name and highest education level, to send the list to the placement office so that the students can get chance. We will make the “Add Student Form” available to the student online so that they can submit their name online and get registered. As a lot of students will use the system, so the performance of the system may very much low. To increase to performance of the web application we will use Ajax with Spring MVC 3 Framework and JQuery.

Following steps we have to go through to implement our example :
  1. First of all, we will create a domain class (User.java) that will hold the value of student information.
  2. After that we will create our controller class (UserListController.java) to handle HTTP request. Our controller will handle three types of requests. First, to show the “Add Student Form”, second to handle Ajax request came from “Add Student Form” and add the students to a list, third to show the student information as a list.
  3. Then, we will create jsp page  (AddUser.jsp) to show “Add Student Form” that will use JQuery to send Ajax request to the Spring MVC Controller. The jsp will also confirm to the user that Student has been added to the list.
  4. Then, we will create a jsp (ShowUsers.jsp) that will list all users in the list.

User.java

User.java has two properties name and education to store the student information. Following is the code of User.java :


package com.naveen.domain;

public class User {

    private String name = null;
    private String education = null;
    // Getter and Setter are omitted for making the code short
}




UserListController.java

Controllers has three method to handle three request urls. “showForm” method handle the request for showing the form to the user. Bellow code shows the UserListController.java :


package com.naveen.controllers;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.naveen.domain.User;

@Controller
public class UserListController {
    private List<User> userList = new ArrayList<User>();

    @RequestMapping(value="/AddUser.htm",method=RequestMethod.GET)
    public String showForm(){
        return "AddUser";
    }

    @RequestMapping(value="/AddUser.htm",method=RequestMethod.POST)
    public @ResponseBody String addUser(@ModelAttribute(value="user") User user, BindingResult result ){
        String returnText;
        if(!result.hasErrors()){
            userList.add(user);
            returnText = "User has been added to the list. Total number of users are " + userList.size();
        }else{
            returnText = "Sorry, an error has occur. User has not been added to list.";
        }
        return returnText;
    }

    @RequestMapping(value="/ShowUsers.htm")
    public String showUsers(ModelMap model){
        model.addAttribute("Users", userList);
        return "ShowUsers";
    }
}


“addUsers” is same as the controller method that handle form expect that it also contain annotation @ResponseBody, which tells Spring MVC that the String returned by the method is the response to the request, it does not have to find view for this string. So the retuning String will be send back to the browser as response and hence the Ajax request will work. “showUsers” method is used to show the list of the students to the user.


AddUser.jsp

AddUser.jsp contain a simple form to collect information about the student and uses JQerey JavaScript framework to generate Ajax request to the server. Following is the code in AddUser.jsp :



<html>
    <head>
       
        <script src="js/jquery.js"></script>
        <script type="text/javascript">
        function doAjaxPost() {
        // get the form values
        var name = $('#name').val();
        var education = $('#education').val();

        $.ajax({
        type: "POST",
        url: "/SpringMVCAjax/AddUser.htm",
        data: "name=" + name + "&education=" + education,
        success: function(response){
        // we have the response
        $('#info').html(response);
        $('#name').val('');
        $('#education').val('');
        },
        error: function(e){
        alert('Error: ' + e);
        }
        });
        }
        </script>
    </head>
    <body>
        <h1>Add Users using Ajax ........</h1>
        <table>
            <tr><td>Enter your name : </td><td> <input type="text" id="name"><br/></td></tr>
            <tr><td>Education : </td><td> <input type="text" id="education"><br/></td></tr>
            <tr><td colspan="2"><input type="button" value="Add Users" onclick="doAjaxPost()"><br/></td></tr>
            <tr><td colspan="2"><div id="info" style="color: green;"></div></td></tr>
        </table>
        <a href="/SpringMVCAjax/ShowUsers.htm">Show All Users</a>
    </body>
</html>


You may be little bit confused if you are not aware of JQuery. Here is the explanation of the JQuery code :
  1. var name = $(‘#name’).val();  : -  here the $ is JQuery selector that uses to select any node in HTML whose identifier is passed as argument. If the identifier is a prefix with # that means it is a id of the HTML node. Here, $(‘#name’).val() contains the value of the HTML node whose is “name’. The text box in which user will enter her/his name is with is as name. so java script variable name will contain the name of the user.
  2. $.ajax() :- It is the method in $ variable of JQuery to call Ajax. It has five arguments here. First of all “type” which indicated the request type of Ajax. It can be POST or GET. Then, “url” which indicates the url to be hit of Ajax submission. “data” will contain the raw data to be sent to the server. “success” will contain the function code that has to be call if the request get success and server sends an response to the browser.  “error” will contain the function code that has to be call if the request get any error.
  3. $(‘#info’).html(response); :- will set the response of the server in to the div. In this way “Hello” + name will be shown in the div whose id is “info“.
ShowUsers.jsp

Following are the code in ShowUsers.jsp to print all student information from a ArrayList to jsp page :


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <title>Users Added using Ajax</title>
    </head>
    <body style="color: green;">
    The following are the users added in the list :<br>
        <ul>
            <c:forEach items="${Users}" var="user">
                <li>Name : <c:out value="${user.name}" />; Education : <c:out value="${user.education}"/>
            </c:forEach>
        </ul>
    </body>
</html>

Here, we have used JSTL core taglib to iterate through the ArrayList and show every value in browser.
  • <c:forEach items=”${Users}” var=”user”> : tag is used for iterate through the ArrayList. Property “items” is used to define the bean on which the List object has been stored, so items=”${Users}” says that the users list is present in “Users” bean. “var” attribute says the name of the variable in which each user will be stored.
  • <c:out value=”${user.name}” /> : As, a single user will be stored in variable name “user” so to print the name property in User object we use ${user.name}.

spring-servlet.xml

Our Spring MVC configuration file should be able to handle annotation driven controllers. The configuration are as follows :


<?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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <!-- Scans the classpath of this application for @Components to deploy as beans -->
    <context:component-scan base-package="com.naveen" />

    <!-- Configures the @Controller programming model -->
    <mvc:annotation-driven />

    <!-- Resolves view names to protected .jsp resources within the /WEB-INF/views directory -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>

 Run the application in eclipse and hit the url,You will get the following page.




Download Source Code

Click here to download source code 

URL Permission Based Security

Posted by Naveen Katiyar On 05:07 No comments

URL Permission Based User Interface Creation in Spring Security

In the previous tutorial, we learned how to customize jsp out put based on the role of the logged in user with the help of the Spring Security JSP Taglibs. Now, we will learn the way to customize the jsp page on the basis of a secure url. That means if the logged in user will have permission to visit the url specified in the taglib attribute, the particular jsp segment will be rendered otherwise, the segment will not shown to the user.
Think about the situation, when we are creating a common menu bar for the logged in users. The menu will contain link for the uses of admin as well as the customers. Some of the menu items are common to both users and some are specific to the admin or customer.
In such situation, we will use Url Permission Based User Interface Creation using Spring Security Taglibs. We will check if the user has permission to visit the menu url then the menu url will be shown to user otherwise menu link will not be shown.


The Tutorial is assuming that you have read following tutorials before reading this:
  1. Getting Started with Spring Security
  2. Role based Spring Security
Please read those tutorial or if you have prior knowledge of setting up Spring Security JSP Taglibs to use in jsp then you can continue with the tutorial.

Tools Used:
  • Spring MVC 3.0.3
  • Spring Security 3.0.5
  • Eclipse Indigo 3.7
  • Tomcat 6
  • Jdk 1.6

Tutorial Example and Explanation:

In our example, there are two users associated with the Spring Security Configuration: “admin” and “customer”. Both of them has different roles. But, the welcome page is the shared page between both the users where they are redirected after successful login. We have also two different urls “/admin/**” and “/users/**” configured in Spring Security Configuration file. Only admin user has rights to view pages under url “/admin/**” and only customer has permission to visit the url “/users/**”.

Spring Security Configuration file


<?xml version="1.0" encoding="UTF-8"?>
<b:beans xmlns="http://www.springframework.org/schema/security"
xmlns:b="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd">
    <http realm="Project Realm" auto-config="true" use-expressions="true">
        <intercept-url pattern="/auth/**" filters="none"/>
        <intercept-url pattern="/admin/**" access="hasRole('ROLE_ADMIN')"/>
        <intercept-url pattern="/users/**" access="hasRole('ROLE_USER')"/>
        <intercept-url pattern="/**" access="hasAnyRole('ROLE_ADMIN','ROLE_USER')"/>
        <form-login login-page="/auth/login.jsp" authentication-failure-url="/auth/login.jsp?login_error=1"/>
        <logout logout-success-url="/auth/login.jsp"/>
        <remember-me />
    </http>

    <authentication-manager>
       <authentication-provider>
           <user-service>
               <user name="admin" password="admin" authorities="ROLE_ADMIN"/>
               <user name="customer" password="customer" authorities="ROLE_USER"/>
           </user-service>
       </authentication-provider>
    </authentication-manager>

</b:beans>
 

We have modified our configuration file as specified above.


Welcome page to create url permission based jsp segments 


<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@ page session="true" %>
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
<%@ taglib uri="http://www.springframework.org/security/tags" prefix="sec"%>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Spring Security 3 JSP Taglibs- This is a secure page</title>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1251">
</head>
<body>
    <h1>Welcome!</h1><br />
    <sec:authorize url="/admin/*">
        This session will be visible to an admin only.<br/>
        You are an Administrator.<br/>
    </sec:authorize>
    <sec:authorize url="/users/*">
        This session will be visible to an Customer only.<br/>
        You are an Customer.<br/>
    </sec:authorize>
        ${HelloMessage}<br />
        <a href="<c:url value="/j_spring_security_logout"/>">Logout</a>
</body>
</html>
 

<sec:authorize url=”/admin/*”> : This means the jsp segment within <sec:authorize/> tag will only show to the logged in user if she/he has permission to view the pages under the url “/admin/*”.

So, if we login with the credentials of admin user we will message specific to the the admin only and same with the customer credentials.

Source code can be downloaded from previous tutorial and could be executed after
making above changes.

That's all for Spring Security Tutorial..... 

Happy Coding.
  

Role Based Spring Security

Posted by Naveen Katiyar On 04:51 No comments

Role Based User Interface Creation Using Spring JSP Taglibs

Spring Security provides jsp taglibs for customizing User Interface according the authenticated user’s role. We can make it possible to show some ui portion to user with role admin and not to others.

This tutorial is based on the previous Spring Security Tutorials. You should first read Getting Started with Spring Security tutorial and then read this tutorial for better understanding.

Tools Used:
  • Spring MVC 3.0.3
  • Spring JDBC 3.0.5
  • Spring Security 3.0.5
  • Eclipse Indigo 3.7
  • Tomcat 6
  • Jdk 1.6
 The tutorial will illustrate you an practical example in which there will be two users with different roles, “ROLE_ADMIN” and “ROLE_USER”.In the example we will modify our Getting Started with Spring Security example to implement role based ui modification using Spring Security JSP Taglibs. We will modify our welcome page to make some portion visible to admin and some portion to user.

Including Spring Security JSP Taglib

We have to add Spring Security Taglib to our jsp file to use this feature of role based user interface modification:


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


Authorize tag in Spring Security taglib

Authorize tag is used for role based user interface creation. For example, if we want to create a jsp portion that will be visible to user with role “ROLE_ADMIN”, it will like following code:


<sec:authorize access="hasRole('ROLE_ADMIN')">
This session will be visible to an admin only.<br/>
You are an Administrator.<br/>
</sec:authorize>


If we put this code to jsp, the message will be shown only to the users with role “ROLE_ADMIN”. access” attribute is used to specify the Spring Security EL Expression and if the expression returns true for the loged in user only then the HTML code within “<sec:authorize/>” tag will be shown to user. The expression in access attribute is send to WebSecurityExpressionHandler defined in the web context. So we have to add WebSecurityExpressionHandler to out security context. It can be done in two ways:
  1. Use default WebSecurityExpressionHandler, which will be only available if we specify use-expressions=”true” in our Spring Security Configuration file under <http/> tag.
  2. Register your WebSecurityExpressionHandler in Spring Security Configuration file.


Common built-in expressions

Following are the common expressions that can be used in access attribute of “<sec:authorize/>” tag:
  • hasRole([role]) : Returns true only if the login user has the role specified in [role].
  • hasAnyRole([role1,role2]) : Returns true only if the login user has atleast one role specified in [role1,role2]. The roles will be specified in comma separated format.
  • isAnonymous() : Returns true only is the login user is an anonymous user.
  • isAuthenticated() : Returns true if the user is not an anonymous user.
  • isFullyAuthenticated() : Returns true if the user is not an anonymous user or a remember me user.
  • isRememberMe() : Returns true if the user is  a remember me user.

Our Example:

Modifying Spring Security Configuration File (spring-security.xml)


<?xml version="1.0" encoding="UTF-8"?>

<b:beans xmlns="http://www.springframework.org/schema/security"
xmlns:b="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

http://www.springframework.org/schema/security

http://www.springframework.org/schema/security/spring-security-3.0.xsd">

<http realm="Project Realm" auto-config="true" use-expressions="true">
    <intercept-url pattern="/auth/**" filters="none"/>
    <intercept-url pattern="/**" access="hasAnyRole('ROLE_ADMIN','ROLE_USER')"/>
    <form-login login-page="/auth/login.jsp" authentication-failure-url="/auth/login.jsp?login_error=1"/>
    <logout logout-success-url="/auth/login.jsp"/>
    <remember-me />
</http>

<authentication-manager>
    <authentication-provider>
        <user-service>
            <user name="admin" password="admin" authorities="ROLE_ADMIN"/>
            <user name="customer" password="customer" authorities="ROLE_USER"/>
        </user-service>
    </authentication-provider>
</authentication-manager>

</b:beans>



We have modified security.xml to:
  • Create two users of different roles.
  • Specify the attribute use-expressions=”true”  in <http/> tag.
  • Provide both the user access to the page url “/**”.

 Modifing welcome.jsp


<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@ page session="true" %>
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Spring Security 3 JSP Taglibs- This is a secure page</title>
        <meta http-equiv="Content-Type" content="text/html; charset=windows-1251">
    </head>
    <body>
        <h1>Welcome!</h1><br />
        <sec:authorize access="hasRole('ROLE_ADMIN')">
         This session will be visible to an admin only.<br/>
         You are an Administrator.<br/>
        </sec:authorize>
        <sec:authorize access="hasRole('ROLE_USER')">
         This session will be visible to an Customer only.<br/>
         You are an Customer.<br/>
        </sec:authorize>
        ${HelloMessage}<br />
        <a href="<c:url value="/j_spring_security_logout"/>">Logout</a>
    </body>
</html>
 

We have just added two message. One for admin user and another for customer user.

Download Source Code