Spring Security - Tutorial With Example

In this spring security tutorial and example, we will create a basic login authentication example that comes with spring security. This tutorial will focus on the security configuration using Spring Security 3.1. 

Required Libraries

Following libraries will be required to be in classpath in order to run this spring security login example.





Spring Security in the web.xml


The architecture is based entirely on servlet filters. Keeping this in mind, to begin with, a filter needs to be declared in the web.xml of the application. This links Spring Security's internal servlet filters into the servlet container's infrastructure

<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
            http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

 <display-name>Spring Security Tutorial Application</display-name>

 <!-- - Location of the XML file that defines the root application context 
  - Applied by ContextLoaderListener. -->
 <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>WEB-INF/spring-security.xml</param-value>
 </context-param>

 <filter>
  <filter-name>springSecurityFilterChain</filter-name>
  <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
 </filter>

 <filter-mapping>
  <filter-name>springSecurityFilterChain</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>
 
 <listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>
 <!-- - Provides core MVC application controller. See example-servlet.xml. -->
 <servlet>
  <servlet-name>dispatcher</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
 </servlet>

 <servlet-mapping>
  <servlet-name>dispatcher</servlet-name>
  <url-pattern>*.do</url-pattern>
 </servlet-mapping>

 <welcome-file-list>
  <welcome-file>login.jsp</welcome-file>
 </welcome-file-list>
</web-app>

Please note that the filter name should be named as 'springSecurityFilterChain' because spring security container creates the default bean with this name.

Spring Security configuration For User Authentication

Let's create spring-security.xml under WEB-INF folder to add spring security configuration.

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
 xmlns:sec="http://www.springframework.org/schema/security"
 xsi:schemaLocation="
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">

 <http use-expressions="true" entry-point-ref="loginUrlAuthenticationEntryPoint">
  <intercept-url pattern="/login.do" access="permitAll" />
  <intercept-url pattern="/jsp/*" access="isAuthenticated()"/>
  <form-login/>
 </http>
 
 <beans:bean id="loginUrlAuthenticationEntryPoint"
  class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
  <beans:property name="loginFormUrl" value="/login.do" />
 </beans:bean>
 
 <beans:bean id="securityFilter"
  class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter">
  <beans:property name="authenticationManager" ref="authenticationManager" />
  <!--  When user provides correct username/password and authentication is successful -->
  <beans:property name="authenticationSuccessHandler"
   ref="authenticationSuccessHandler" />
 </beans:bean>
 <authentication-manager alias="authenticationManager">
  <authentication-provider>
   <user-service>
    <user name="chuck.norris" password="cnorris" authorities="ROLE_ADMIN" />
    <user name="user" password="user" authorities="ROLE_USER" />
   </user-service>
  </authentication-provider>
 </authentication-manager>

 <beans:bean id="authenticationSuccessHandler"
  class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
  <beans:property name="defaultTargetUrl" value="/home.do" />
 </beans:bean>
</beans:beans>




Basics of Spring Security Configuration
  • The <http> block states that we want to use web security (which is applied by Spring Security's filters), with form-based login and access control expressions enabled. 
  • entry-point-ref attribute defines a customized AuthenticationEntryPoint to be set. Here default entry point refers login.do which directs the user to login.jsp
  • The first <intercept-url> element says that the login url ("/login.do") is accessible to anyone (the "permitAll" expression).
  • The second <intercept-url> elements says that in order to access any url starting with '/jsp', user needs to be authenticated. If user is not authenticated and it tries to open such url directly, he/she will be redirected to entry point i.e. login page. You can define all such url patterns (one per <intercept-url> element) for which authentication is required.
  • The <authentication-manager> element is being used here to define a list of in-memory users and their passwords and role information, which is convenient for samples and demos. A real world application would more likely use a database, LDAP server or some single sign-on integration.
  • authenticationSuccessHandler property declares a url which user is directed to upon successful authentication.

Sample Login Form

 Let's create a form based login jsp page


<%@ taglib prefix="c" 
           uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<body onload='document.f.j_username.focus();'>
 <h3>Spring Security Login Example</h3>
 
 <c:if test="${not empty error}">
  <div>
   Your login attempt was not successful, try again.<br /> Caused :
   ${sessionScope["SPRING_SECURITY_LAST_EXCEPTION"].message}
  </div>
 </c:if>
 
 <form name='loginForm' action="j_spring_security_check"
  method='POST'>
 
  <table>
   <tr>
    <td>User:</td>
    <td><input type='text' name='j_username' value=''>
    </td>
   </tr>
   <tr>
    <td>Password:</td>
    <td><input type='password' name='j_password' />
    </td>
   </tr>
   <tr>
    <td colspan='2'><input name="submit" type="submit"
     value="submit" />
    </td>
   </tr>
  </table>
 
 </form>
</body>
</html>


Please note that the name of form, name of input for username and password have to be matched as given. The reason is spring uses these default names in its spring security container.

Sample home.jsp

Let's create a sample home page to which user will be redirected upon successful user authentication.


<html>
<body>
 <h3>Spring Security Welcome Page</h3>

 <table>
  <tr>
   <td>Welcome To Home Page Of Spring Security</td>
  </tr>
 </table>
</body>
</html>

Dispatcher Servlet Configuration & Controllers

Let's create a dispatcher configuration and LoginController which will map login.do and home.do urls to their respective jsps.
<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.1.xsd
http://www.springframework.org/schema/context    http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
">
 <context:annotation-config />
 <context:component-scan base-package="com.javakart.springsecurity.controller" />
 <bean id="viewResolver"
  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="prefix">
   <value>/jsp/</value>
  </property>
  <property name="suffix">
   <value>.jsp</value>
  </property>
 </bean>
</beans>



package com.javakart.springsecurity.controller;

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

@Controller
public class LoginController {

 @RequestMapping(value="login.do", method = RequestMethod.GET)
 public ModelAndView showLoginPage(){
  ModelAndView modelAndView = new ModelAndView("login");
  return modelAndView;
 }
 
 @RequestMapping(value="home.do", method = RequestMethod.GET)
 public ModelAndView showHomePage(){
  ModelAndView modelAndView = new ModelAndView("home");
  return modelAndView;
 }
}



Showing a Demo

1. Open “http://localhost:8080/SpringSecurity/jsp/home.jsp“, Spring Security will intercept the request and redirect to “http://localhost:8080/SpringMVC/login.do” and display the login page as below.



2. Try to enter wrong credentials (javakart/javakart), spring security filter will fail this authentication and will show the login page with error as follow.



3. Try to enter right credentials (user/user) and it will redirect the user to home page as follow.


Spring MVC Form Validation Tutorial and Example

This tutorial walks you through the step by step instructions in order to support and apply validation example in Spring MVC. Please see Spring MVC Hello World Example to setup spring MVC environment.
  • Required Libraries
      Following libraries will be required over and above your existing spring setup in order to run this example

           spring-modules-validation-0.6.jar

  • spring-config.xml
Let's create a spring configuration file in order to declare and configure various required beans as follow.

<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.1.xsd
 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
 ">
  
 <context:annotation-config />
 <context:component-scan base-package="com.mycompany.myapp.controller" />
 
 <bean id="viewResolver"
     class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
        <property name="prefix">
            <value>/jsp/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>
 
</beans>


  • Sample Login.jsp

Let's create a sample login.jsp under $WebRoot/jsp folder. This will submit a POST request and will show validation messages in red beside username and password text boxes if user enters invalid values for them and submits the page by clicking Login button .here <form:errros> tag will display validation messages if any. It will not display any message if there is no errors.

<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
    <title>Spring 3 MVC Series - Login Validation Example</title>
</head>
<body>
 
<form:form method="post" action="login.do" commandName="loginModel">
    <table>
    <tr>
        <td>Username : </td>
  <td><form:input path="username" /></td>
  <td><form:errors path="username" /></td>
 </tr>
    <tr>
        <td>Password : </td>
        <td><form:input path="password" /></td>
        <td><form:errors path="password"/></td>
    </tr>
     <tr>
        <td colspan="3">
            <input type="submit" value="Login"/>
        </td>
    </tr>
</table>  
</form:form>
</body>
</html>



  • LoginModel
Let's create a LoginModel class which represents a model consisting of username and password as its fields

package com.mycompany.myapp.model;

import org.springmodules.validation.bean.conf.loader.annotation.handler.Length;
import org.springmodules.validation.bean.conf.loader.annotation.handler.NotBlank;

public class LoginModel{

 @NotBlank
 private String username;
 
 @NotBlank
 private String password;

 public String getUsername() {
  return username;
 }

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

 public String getPassword() {
  return password;
 }

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

Make sure the field names of LoginModel class matches with that of path attributes under <form:input> tag in above login.jsp. See how username and password fields are annotated for not blank values. Explore various such annotations under org.springmodules.validation.bean.conf.loader.annotation.handler package of spring-modules-validation-0.6.jar.

  • LoginController
Let's create a LoginController which will handle login requests. 

package com.mycompany.myapp.controller;

package com.mycompany.myapp.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
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.servlet.ModelAndView;
import org.springmodules.validation.bean.BeanValidator;
import org.springmodules.validation.bean.conf.loader.annotation.AnnotationBeanValidationConfigurationLoader;

import com.mycompany.myapp.model.LoginModel;

@Controller
public class LoginController {
 private BeanValidator beanValidator = new BeanValidator(new AnnotationBeanValidationConfigurationLoader());
 
 @RequestMapping(value="/login.do",method=RequestMethod.GET)
 protected ModelAndView showLoginPage(HttpServletRequest request
  ) throws Exception {
 
  ModelAndView model = new ModelAndView("login");
  model.getModelMap().put("loginModel", new LoginModel());
  return model;
 }
 
 @RequestMapping(value="/login.do",method=RequestMethod.POST)
 protected ModelAndView doLogin(@ModelAttribute("loginModel") LoginModel loginModel, BindingResult bindingResult){
  beanValidator.validate(loginModel, bindingResult);
  if (bindingResult.hasErrors()){
   ModelAndView model = new ModelAndView("login");
   return model;
  }
  ModelAndView model = new ModelAndView("home");
  return model;
 }
 
}


When login page is opened (http://{hostname}:{port}/{webcontext}/jsp/login.jsp, it will call showLoginPage method and will bind LoginModel class with 'loginModel' command declared in <form:form> tag of login.jsp. And when user clicks Login button, doLogin method will be called and its parameter loginModel will contain values entered by user in login.jsp.



  • Error Messages
'not.blank' is the default message. You can override this by providing your custom message in @NotBlank annotation.


If you want to externalize the message into properties file with i18n, then define a key as '@AnnotationName.object.fieldname'. For example,

NotBlank.loginModel.username = Username cannot be blank
NotBlank.loginModel.password = Password cannot be blank


Please see Spring MVC Internationalization Example  to know how to support internationalization in spring mvc so that you can create properties files and define these error messages in it.

Spring Data Redis - JRedis Hello World Example

In this tutorial, we will show you an example how to integrate and use redis data store (which is a NoSQL  Key Value data store) with Spring Data. At the end of this Hello World example, you will be able to write CRUD operations with Spring data Redis based applications.

Redis is an open source, advanced key-value data store. It is often referred to as a data structure server since keys can contain strings, hashes, lists, sets and sorted sets. Spring Data for Redis is part of the umbrella Spring Data project which provides support for writing Redis applications. This example uses a JRedisa specification and reference implementation of Redis

Following libraries and tools will be required in order to run this example.
  • Download and Install Redis DB
  • spring-data-redis-1.0.1.RELEASE
  • commons-logging-1.1.1.jar
  • commons-pool-1.4.jar
  • jackson-core-asl-1.9.0.jar
  • jackson-mapper-asl-1.9.0.jar
  • jedis-2.1.0.jar
  • org.springframework.asm-3.1.1.RELEASE.jar
  • org.springframework.beans-3.1.1.RELEASE.jar
  • org.springframework.context-3.1.1.RELEASE.jar
  • org.springframework.core-3.1.1.RELEASE.jar
  • org.springframework.expression-3.1.1.RELEASE.jar
  • spring-tx-3.1.1.RELEASE.jar

Spring Configuration File (Must be in classpath)
  
Let's create spring configuration file which configures beans JRedis connection factory, RedisTemplate and Repository classes.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
 xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="
   http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
   http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

 <bean id="connectionFactory"
  class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
  p:host-name="localhost" p:port="6379" p:password="" />

 <!-- redis template -->
 <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"
  p:connection-factory-ref="connectionFactory" />
  
 <bean id="userRepository" class="com.mycompany.redis.repository.UserRepository">
  <property name="redisTemplate" ref="redisTemplate"/>
 </bean>

</beans>


DomainObject.java 

Let's create an interfact DomainObject.java which will be implemented by all domain classes. 

package com.mycompany.redis.domain;

import java.io.Serializable;

public interface DomainObject extends Serializable {

 String getKey();

 String getObjectKey();
}


User.java

Let's create a domain object User.java which represents an user entity. This class implements DomainObject interface.

package com.mycompany.redis.domain;

public class User implements DomainObject {

 public static final String OBJECT_KEY = "USER";

 public User() {
 }

 public User(String id, String name){
  this.id = id;
  this.name = name;
 }
 private String id;
 private String name;

 public String getId() {
  return id;
 }

 public void setId(String id) {
  this.id = id;
 }

 public String getName() {
  return name;
 }

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

 @Override
 public String toString() {
  return "User [id=" + id + ", name=" + name + "]";
 }

 @Override
 public String getKey() {
  return getId();
 }

 @Override
 public String getObjectKey() {
  return OBJECT_KEY;
 }
}

Repository.java

Let's create an abstract Repository which can be implemented by specific respositories.
package com.mycompany.redis.repository;

import java.util.List;

import com.mycompany.redis.domain.DomainObject;

public interface Repository<V extends DomainObject> {

 void put(V obj);

 V get(V key);

 void delete(V key);
 
 List<V> getObjects();
}


UserRepository.java

Let's create a UserRepository.java which will provide CRUD APIs to be performed on user object.
package com.mycompany.redis.repository;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import com.mycompany.redis.domain.DomainObject;
import com.mycompany.redis.domain.User;

public class UserRepository implements Repository<User>{

 @Autowired
 private RedisTemplate<String,User> redisTemplate;
 
 public RedisTemplate<String,User> getRedisTemplate() {
  return redisTemplate;
 }

 public void setRedisTemplate(RedisTemplate<String,User> redisTemplate) {
  this.redisTemplate = redisTemplate;
 }

 @Override
 public void put(User user) {
  redisTemplate.opsForHash()
    .put(user.getObjectKey(), user.getKey(), user);
 }

 @Override
 public void delete(User key) {
  redisTemplate.opsForHash().delete(key.getObjectKey(), key.getKey());
 }

 @Override
 public User get(User key) {
  return (User) redisTemplate.opsForHash().get(key.getObjectKey(),
    key.getKey());
 }

 @Override
 public List<User> getObjects() {
  List<User> users = new ArrayList<User>();
  for (Object user : redisTemplate.opsForHash().values(User.OBJECT_KEY) ){
   users.add((User) user);
  }
  return users;
 }
}

Running The Example

Now we are set to run this Spring Data Redis example. Let's run it by following code.


package com.mycompany.redis;

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

import com.mycompany.redis.domain.User;
import com.mycompany.redis.repository.UserRepository;

public class HelloWorld {

 public static void main(String[] args) {
  ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-config.xml");
  UserRepository userRepository = (UserRepository) applicationContext.getBean("userRepository");
  User user1 = new User("1", "user 1");
  User user2 = new User("2","user 2");
  userRepository.put(user1);
  System.out.println(" Step 1 output : " + userRepository.getObjects());
  userRepository.put(user2);
  System.out.println(" Step 2 output : " + userRepository.getObjects());
  userRepository.delete(user1);
  System.out.println(" Step 3 output : " + userRepository.getObjects());
 }
}


And here you go, following is the console output.

Step 1 output : [User [id=1, name=user 1]]
 Step 2 output : [User [id=1, name=user 1], User [id=2, name=user 2]]
 Step 3 output : [User [id=2, name=user 2]]
}
Similarly you can create other domain objects and repositories of the same!!!

Spring Data MongoDB - Hello World Example

In this tutorial, we will show how to configure MongoDB using Spring Data. And then we will create hello world example to show how to perform CRUD operations with MongoDB and Spring Data. 

In order to run this example, you would need to install mongodb and follow the instructions and would need to have following tools and libraries.

  • JDK/Java 1.6 or later
  • Eclipse 3.6 or later
  • spring-data-mongodb-1.0.2.RELEASE (download it from here)
  • spring-data-commons-core-1.2.0.RELEASE (download it from here)
  • java mongodb driver 2.10.1 (dowload it from here)
  • spring-core-3.1.1.RELEASE
  • spring-context-3.1.1.RELEASE
  • spring-asm-3.1.1.RELEASE
  • spring-expression-3.1.1.RELEASE
  • spring-aop-3.1.1.RELEASE
  • spring-tx-3.1.1.RELEASE
  • cglib-nodep-2.1.3
Spring Configuration File (spring-config.xml)

 This spring configuration file contains related bean configurations in order to run this example. Please make sure that this file is in the classpath.

<?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">
        
    <context:annotation-config/>
    
    <context:component-scan base-package="com.mycompany.mongodb">
     <context:exclude-filter type="annotation" expression="org.springframework.context.annotation.Configuration"/>
    </context:component-scan>
    
    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
     <constructor-arg name="mongo" ref="mongo"/>
     <constructor-arg name="databaseName" value="test"/>
     </bean>

 <!-- Factory bean that creates the Mongo instance -->
    <bean id="mongo" class="org.springframework.data.mongodb.core.MongoFactoryBean">
     <property name="host" value="localhost"/>
    </bean>
    
 <!-- Use this post processor to translate any MongoExceptions thrown in @Repository annotated classes -->
 <bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
    
</beans>



Domain Objects or Classes
   
   Account.java and Person.java represent domain classes which spring data will use to convert them from/to mongodb representation.

Account.java

package com.mycompany.mongodb.domain;

public class Account {

 public enum Type {
  SAVINGS, CHECKING
 }

 private String id;

 private String accountNumber;

 private Account.Type accountType;

 private Double balance;

 public Account(){
 }

 public Account(String accountNumber, Type accountType, Double balance) {
  super();
  this.accountNumber = accountNumber;
  this.accountType = accountType;
  this.balance = balance;
 }

 public String getId() {
  return id;
 }

 public void setId(String id) {
  this.id = id;
 }

 public String getAccountNumber() {
  return accountNumber;
 }

 public void setAccountNumber(String accountNumber) {
  this.accountNumber = accountNumber;
 }

 public Account.Type getAccountType() {
  return accountType;
 }

 public void setAccountType(Account.Type accountType) {
  this.accountType = accountType;
 }

 public Double getBalance() {
  return balance;
 }

 public void setBalance(Double balance) {
  this.balance = balance;
 }

 @Override
 public String toString() {
  return "Account [id=" + id + ", accountNumber=" + accountNumber
    + ", accountType=" + accountType + ", balance=" + balance + "]";
 }

}


Person.java 


package com.mycompany.mongodb.domain;

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

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document
public class Person {

 @Id
 private String id;

 private String name;

 private int age;

 private List<Account> accounts = new ArrayList<Account>();

 public Person() {
 }

 public Person(String name, int age) {
  super();
  this.name = name;
  this.age = age;
 }

 public String getId() {
  return id;
 }

 public void setId(String id) {
  this.id = id;
 }

 public String getName() {
  return name;
 }

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

 public int getAge() {
  return age;
 }

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

 public List<Account> getAccounts() {
  return accounts;
 }

 public void addAccount(Account account) {
  this.accounts.add(account);
 }

 public void setAccounts(List<Account> accounts) {
  this.accounts = accounts;
 }

 @Override
 public String toString() {
  return "Person [id=" + id + ", name=" + name + ", age=" + age
    + ", accounts=" + accounts + "]";
 }

}


HelloMongo.java

 This class will perform CRUD operations on Account and Person objects and show you the demo.

package com.mycompany.mongodb;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;

import org.springframework.stereotype.Repository;

import com.mycompany.mongodb.domain.Account;
import com.mycompany.mongodb.domain.Person;

@Repository
public class HelloMongo {

 @Autowired
 MongoOperations mongoOperations;

 public void run() {

  if (mongoOperations.collectionExists(Person.class)) {
   mongoOperations.dropCollection(Person.class);
  }

  mongoOperations.createCollection(Person.class);

  Person p = new Person("John", 39);
  Account a = new Account("1234-59873-893-1", Account.Type.SAVINGS, 123.45D);
  p.getAccounts().add(a);

  mongoOperations.insert(p);

  List<Person> results = mongoOperations.findAll(Person.class);
  System.out.println("Results: " + results);
 }

}


Running the Example

 Following code shows how to run this example

package com.mycompany.mongodb;

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

/**
 * Hello Mongo!
 */
public class App 
{
 public static void main( String[] args ) {
       ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");

        HelloMongo hello = context.getBean(HelloMongo.class);
        hello.run();
        System.out.println( "DONE!" );
 }
}


And here you go. You would see following output once you run this.

Results: [Person [id=50d0043fa8ca9e8996923a08, name=John, age=39, accounts=[Account [id=null, accountNumber=1234-59873-893-1, accountType=SAVINGS, balance=123.45]]]]
DONE!






Setup development environment with Eclipse and Tomcat

In this tutorial, we will guide you through step by step instructions how to setup and create development environment for dynamic web application using eclipse and tomcat. Unlike with static Web projects, dynamic Web projects enable you to create resources such as JavaServer Pages and servlets. Dynamic web projects can contain dynamic Java EE resources such as servlets, JSP files, filters, and associated metadata, in addition to static resources such as images and HTML files. Static web projects only contains static resources.

To create a new dynamic Web project, complete the following steps:
  • Install Tomcat 7.0 or later. Call the home directory of tomcat $TOMCAT_HOME.
  • Open Eclipse and Click File -> New -> Other and select Dynamic Web Project  and click Next as shown in below image

  • Provide the project name and location. Select 3.0 option for Dynamic web module version.

  • Click on New Runtime button under Target runtime section and select Apache Tomcat 7.0 environment under Apache option. Click Next.

  • Click on Browse and select the directory where Tomcat is installed. Provide the JRE and click Finish.

  •  Keep clicking Next button on parent window until it does not appear. Click Finish. Following structure will be created.

  • src is the java source code folder under which various java files (like servlets) will be put. WebContent is the root folder under which various web contents like jsp, html etc will be put. Put any jar files under WEB-INF/lib.
  • Put your web.xml under WEB-INF folder. Sample web.xml is given below.
<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app
          PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
          "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
 
 <!--
  ###########################################################################
  # # # S E R V L E T S # # #
  ###########################################################################
 -->

 
 <!--
  ###########################################################################
  # # # S E R V L E T - M A P P I N G S # # #
  ###########################################################################
 -->

 <!-- JUnitEEServlet mapping -->
 
</web-app>


  • Create login.jsp as follow and put this file under WEB-INF/jsp folder

    <html>
    <head>
        <title>Spring 3 MVC Series - Login</title>
    </head>
    <body>
    <form method="post" action="login.do"  >
        <table>
        <tr>
            <td>Username :</td>
              <td><input type="text" name="username" /></td>
        </tr>
        <tr>
            <td>Password : </td>
            <td><input type="text" name="password" /></td>
        </tr>
         <tr>
            <td colspan="2">
                <input type="submit" value="Login"/>
            </td>
        </tr>
    </table>  
    </form:form>
    </body>
    </html>
    

  • Now click Windows -> Show View -> Servers. In the empty area of server view, right click and select New -> Server. And select Tomcat v7.0 Server. Make sure Apache Tomcat v7.0 is selected in  'Server Runtime Environment' Dropdown. Click Next.

  • Select MyWebProject in the left panel and move it to right panel by clicking Add > button. And click Finish.

  • This would show as below in server view. Right click Tomcat v7.0 Server at localhost and click clean. Right click on Tomcat v7.0 Server and click on Start. Open http://localhost:8080/MyWebProject/jsp/login.jsp. And there you go. You will see login.jsp as below.






File Upload (multiplart) Example Using Spring

In this article, we will demonstrate a step by step example of how to upload a file using Spring and multiplart request. Spring has built-in multipart support to handle fileuploads in web applications. The design for the multipart support is done with pluggable MultipartResolver objects, defined in the org.springframework.web.multipart package. Out of the box, Spring provides a MultipartResolver for use with Commons FileUpload  http://jakarta.apache.org/commons/fileupload). How uploading files is supported will be described here.

Using the MultipartResolver

The following example shows how to use the CommonsMultipartResolver. Of course you also need to put the commons-fileupload.jar in your classpath for the multipart resolver to work.

<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- one of the properties available; the maximum file size in bytes -->
   <property name="maxUploadSize" value="100000"/>
</bean>

Handling a file upload in a form

you create a form with an upload field (see immediately below), then let Spring bind the file onto your form(backing object). To actually let the user upload a file, we have to create a (HTML) form:


<html>
  <head>
    <title>Upload a file using Spring</title>
  </head>
  <body>
    <h1>Please upload a file</h1>
    <form method="post" action="upload.form" enctype="multipart/form-data">
      <input type="file" name="file" />
      <input type="submit" />
    </form>
  </body>
</html>


As you can see, we've created a field named after the property of the bean that holds the byte[]. Furthermore we've added the encoding attribute (enctype="multipart/form-data") which is necessary to let the browser know how to encode the multipart fields (do not forget this!).

Spring Configuration File

So, to be able to upload files using a (HTML) form, declare the resolver, a url mapping to a controller that will process the bean, and the controller itself.


<!-- lets use the Commons-based implementation of the MultipartResolver interface -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
  <property name="mappings">
    <value>
      /upload.form=fileUploadController
</value>
  </property>
</bean>
<bean id="fileUploadController" class="examples.FileUploadController">
  <property name="commandClass" value="examples.FileUploadBean" />
  <property name="formView" value="fileuploadform" />
  <property name="successView" value="confirmation" />
</bean>

Controller

After that, create the controller and the actual class to hold the file property.


public class FileUploadController extends SimpleFormController {
  protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response,
Object command, BindException errors) throws ServletException, IOException {
// cast the bean
FileUploadBean bean = (FileUploadBean) command;
let's see if there's content there
byte[] file = bean.getFile();
if (file == null) {
// hmm, that's strange, the user did not upload anything
}
// well, let's do nothing with the bean for now and return
return super.onSubmit(request, response, command, errors);
}

  protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws ServletException {
    // to actually be able to convert Multipart instance to byte[]
    // we have to register a custom editor
    binder.registerCustomEditor(byte[].class, new ByteArrayMultipartFileEditor());
    // now Spring knows how to handle multipart object and convert them
  }
}

public class FileUploadBean {
  private byte[] file;

  public void setFile(byte[] file) {
    this.file = file;
  }

  public byte[] getFile() {
    return file;
  }
}

As you can see, the FileUploadBean has a property typed byte[] that holds the file. The controller registers a custom editor to let Spring know how to actually convert the multipart objects the resolver has found to properties specified by the bean. In this example, nothing is done with the byte[] property of the bean itself, but in practice you can do whatever you want (save it in a database, mail it to somebody, etc).


How to Send E-mail using Spring and JavaMail

In this article, we will show you an example that will demonstrate how to send e-email using Spring and JavaMail. The following additional jars to be on the classpath of your application in order to be able to use the Spring Framework's email library.
  • The JavaMail mail.jar library
  • The JAF activation.jar library
The Spring Framework provides a helpful utility library for sending email that shields the user from the specifics of the underlying mailing system and is responsible for low level resource handling on behalf of the client.

Basic MailSender and SimpleMailMessage usage

Let us assume that there is a requirement stating that an email message with an order number needs to be generated and sent to a customer placing the relevant order.

public class SimpleOrderManager implements OrderManager {
  private MailSender mailSender;
  private SimpleMailMessage templateMessage;

  public void setMailSender(MailSender mailSender) {
    this.mailSender = mailSender;
  }

  public void setTemplateMessage(SimpleMailMessage templateMessage) {
    this.templateMessage = templateMessage;
  }

  public void placeOrder(Order order) {
    // Do the business calculations...
    // Call the collaborators to persist the order...
    // Create a thread safe "copy" of the template message and customize it
    SimpleMailMessage msg = new SimpleMailMessage(this.templateMessage);
    msg.setTo(order.getCustomer().getEmailAddress());
    msg.setText("Dear " + order.getCustomer().getFirstName() + order.getCustomer().getLastName()
        + ", thank you for placing order. Your order number is " + order.getOrderNumber());
    try {
      this.mailSender.send(msg);
    } catch (MailException ex) {
      // simply log it and go on...
      System.err.println(ex.getMessage());
    }
  }
}

























Find below the bean definitions for the above code:

<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
  <property name="host" value="mail.mycompany.com" />
</bean>
<!-- this is a template message that we can pre-load with default state -->
<bean id="templateMessage" class="org.springframework.mail.SimpleMailMessage">
  <property name="from" value="customerservice@mycompany.com" />
  <property name="subject" value="Your order" />
</bean>
<bean id="orderManager" class="com.mycompany.businessapp.support.SimpleOrderManager">
  <property name="mailSender" ref="mailSender" />
  <property name="templateMessage" ref="templateMessage" />
</bean>