In this post, we will see how to list all files with certain extension in a folder.
For example, you want to list all .jpg or .zip files in a folder.

We will  use FilenameFilter interface to list the files in a folder, so we will create a inner class which will implement FilenameFilter interface and implement accept method. We need to pass created inner class to java.io.File 's list method to list all files with specific extension.

Java Program :
package org.arpit.java2blog;

import java.io.File;
import java.io.FilenameFilter;

public class GetAllFilesWithCertainExtMain {
 /*
  * @author Arpit Mandliya
  */
 public static void main(String[] args) {

  GetAllFilesWithCertainExtMain main=new GetAllFilesWithCertainExtMain();
  System.out.println("Finding .zip files in the folder /Users/Arpit/Desktop/Blog");
  System.out.println("-----------------");
  // Read the file
  File folder=new File("/Users/Arpit/Desktop/Blog");
  main.getAllFilesWithCertainExtension(folder,"zip");
  
  System.out.println("-----------------");
 }
 
 public  void getAllFilesWithCertainExtension(File folder,String filterExt)
 {
  MyExtFilter extFilter=new MyExtFilter(filterExt);
  if(!folder.isDirectory())
  {
   System.out.println("Not a folder");
  }
  else
  {
   // list out all the file name and filter by the extension
   String[] list = folder.list(extFilter);

   if (list.length == 0) {
    System.out.println("no files end with : " + filterExt);
    return;
   }

   for (int i = 0; i < list.length; i++) {
    System.out.println("File :"+list[i]);
   }
  }
 }
 
 // inner class, generic extension filter
  public class MyExtFilter implements FilenameFilter {

   private String ext;

   public MyExtFilter(String ext) {
    this.ext = ext;
   }

   public boolean accept(File dir, String name) {
    return (name.endsWith(ext));
   }
  }
}

When I ran above program, I got following output:
Finding .zip files in the folder /Users/Arpit/Desktop/Blog
-----------------
File :sampleFile1.zip
File :sampleFile2.zip
File :sampleFile3.zip
File :Spring3-Quartz-Example.zip
File :SpringQuartzIntegrationExample.zip
-----------------

So we have found all .zip file in folder "/Users/Arpit/Desktop/Blog"

In this post, we will see how to delete Directory/Folder which is non empty. You can use java.io.File 's delete empy folder but you can not delete it if it is non empty.
There are multiple ways to do it.
  • Using java recursion
  • Using Apache common IO

Using java recursion:

It is very straight forward to do it. It will iterate through all files in the folder. If it is a file then we can directly delete it but if It finds folder inside it then we again call same method.
// Delete using recursion
 public static void delete(File file)
   throws IOException{

  if(file.isDirectory()){

   //We can directly delete if we found empty directory
   if(file.list().length==0){

    file.delete();
    System.out.println("Deleting folder : " 
      + file.getAbsolutePath());

   }else{

    //list all the files in directory
    File files[] = file.listFiles();

    for (File temp : files) {
     //recursive delete
     delete(temp);
    }

    // Check directory again, if we find it empty, delete it
    if(file.list().length==0){
     file.delete();
     System.out.println("Deleting folder : " 
       + file.getAbsolutePath());
    }
   }

  }else{
   //if file, then we can directly delete it
   file.delete();
   System.out.println("Deleting file  : " + file.getAbsolutePath());
  }
 }


Using Apache common IO:

Delete non empty folder is very straight forward. You just need to call FileUtils.deleteDirectory() method.
// Delete using Apache common IO
 public static void deleteUsingApacheIO(File f)
 {
  try {
   FileUtils.deleteDirectory(f);
  } catch (IOException e) {

   e.printStackTrace();
  }
 }

Java Program:

package org.arpit.java2blog;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;

public class DeleteNonEmptyDirectoryMain {

 public static void main(String[] args) {
  
  
  System.out.println("Deleting using recursion");
  System.out.println("---------------");
  File folder= new File("/Users/Arpit/Desktop/Blog/temp1");
  // Using recusrion
  try {
   delete(folder);
  } catch (IOException e) {
   e.printStackTrace();
  }
  
  System.out.println("---------------");
  System.out.println("Deleting using Apache IO");
  File folder2= new File("/Users/Arpit/Desktop/Blog/temp2");
  deleteUsingApacheIO(folder2);
  System.out.println("Deleting folder : " 
    + folder2.getAbsolutePath());
 }

 // Delete using recursion
 public static void delete(File file)
   throws IOException{

  if(file.isDirectory()){

   //We can directly delete if we found empty directory
   if(file.list().length==0){

    file.delete();
    System.out.println("Deleting folder : " 
      + file.getAbsolutePath());

   }else{

    //list all the files in directory
    File files[] = file.listFiles();

    for (File temp : files) {
     //recursive delete
     delete(temp);
    }

    // Check directory again, if we find it empty, delete it
    if(file.list().length==0){
     file.delete();
     System.out.println("Deleting folder : " 
       + file.getAbsolutePath());
    }
   }

  }else{
   //if file, then we can directly delete it
   file.delete();
   System.out.println("Deleting file  : " + file.getAbsolutePath());
  }
 }

 // Delete using Apache common IO
 public static void deleteUsingApacheIO(File f)
 {
  try {
   FileUtils.deleteDirectory(f);
  } catch (IOException e) {

   e.printStackTrace();
  }
 }
}

When I ran above program, I got following output
Deleting using recursion
---------------
Deleting file  : /Users/Arpit/Desktop/Blog/temp1/.DS_Store
Deleting file  : /Users/Arpit/Desktop/Blog/temp1/BinaryTree/.DS_Store
Deleting file  : /Users/Arpit/Desktop/Blog/temp1/BinaryTree/verticalSum.jpg.png
Deleting file  : /Users/Arpit/Desktop/Blog/temp1/BinaryTree/VerticalSumOrder.png
Deleting folder : /Users/Arpit/Desktop/Blog/temp1/BinaryTree
Deleting file  : /Users/Arpit/Desktop/Blog/temp1/jersey json/.DS_Store
Deleting file  : /Users/Arpit/Desktop/Blog/temp1/jersey json/jerseyJsonCountry.png
Deleting file  : /Users/Arpit/Desktop/Blog/temp1/jersey json/jerseyJsonCountryID.png
Deleting file  : /Users/Arpit/Desktop/Blog/temp1/jersey json/jerseyMavenBuild.png
Deleting file  : /Users/Arpit/Desktop/Blog/temp1/jersey json/jerseyMavenCleanInstall.png
Deleting file  : /Users/Arpit/Desktop/Blog/temp1/jersey json/jerseyProjectStructure.png
Deleting folder : /Users/Arpit/Desktop/Blog/temp1/jersey json
Deleting folder : /Users/Arpit/Desktop/Blog/temp1
---------------
Deleting using Apache IO
Deleting folder : /Users/Arpit/Desktop/Blog/temp2



In this post, we will see how to download file from URL in java. It can be used when you want to automatically download any file from URL using java.

There are many ways to do it and some of them are :

Java Program:

package org.arpit.java2blog;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;

import org.apache.commons.io.FileUtils;

/*
 * @author Arpit Mandliya
 */
public class FileDownloadFromURLMain {

 public static void main(String[] args) {


  String dirName = "/Users/Arpit/Desktop/Blog";

  try {

   System.out.println("---------------------------");
   System.out.println("Downloading file from github using java file IO");
   
   // Using java IO
   downloadFileFromUrlWithJavaIO(
     dirName + "/sampleFile1.zip",
     "https://github.com/arpitmandliya/SpringRestfulWebServicesWithJSONExample/archive/master.zip");

   System.out.println("Downloaded file from github using java file IO");
   System.out.println("---------------------------");
   System.out.println("Downloading file from github using apache common IO");

   // Using Apache common IO
   downloadFileFromUrlWithCommonsIO(
     dirName + "/sampleFile2.zip",
     "https://github.com/arpitmandliya/SpringSecurityHelloWorldExample/archive/master.zip");

   System.out.println("Downloaded file from github using apache common IO");
   System.out.println("---------------------------");
   System.out.println("Downloading file from github using NIO");

   // Using NIO
   downloadFileFromURLUsingNIO(
     dirName + "/sampleFile3.zip",
     "https://github.com/arpitmandliya/SpringMVCHelloWorldExample/archive/master.zip");

   System.out.println("Downloaded file from github using NIO");
   System.out.println("---------------------------");

  } catch (MalformedURLException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }

 }

 // Using Java IO
 public static void downloadFileFromUrlWithJavaIO(String fileName, String fileUrl)
   throws MalformedURLException, IOException {
  BufferedInputStream inStream = null;
  FileOutputStream outStream = null;
  try {
   URL fileUrlObj=new URL(fileUrl);
   inStream = new BufferedInputStream(fileUrlObj.openStream());
   outStream = new FileOutputStream(fileName);

   byte data[] = new byte[1024];
   int count;
   while ((count = inStream.read(data, 0, 1024)) != -1) {
    outStream.write(data, 0, count);
   }
  } finally {
   if (inStream != null)
    inStream.close();
   if (outStream != null)
    outStream.close();
  }
 }

 // Using common IO
 public static void downloadFileFromUrlWithCommonsIO(String fileName,
   String fileUrl) throws MalformedURLException, IOException {
  FileUtils.copyURLToFile(new URL(fileUrl), new File(fileName));
 }

 // Using NIO
 private static void downloadFileFromURLUsingNIO(String fileName,String fileUrl) throws IOException {
  URL url = new URL(fileUrl);
  ReadableByteChannel rbc = Channels.newChannel(url.openStream());
  FileOutputStream fOutStream = new FileOutputStream(fileName);
  fOutStream.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
  fOutStream.close();
  rbc.close();
 }

}
When you run above program , file will be downloaded in above mentioned directory.You will get following output:
---------------------------
Downloading file from github using java file IO
Downloaded file from github using java file IO
---------------------------
Downloading file from github using apache common IO
Downloaded file from github using apache common IO
---------------------------
Downloading file from github using NIO
Downloaded file from github using NIO
---------------------------



It is very easy to check if file exists or not in your file system. You can use java.io.File's exists() method to check if file exists or not.

Java program :

package org.arpit.java2blog;

import java.io.File;

public class FileExistsMain {
 /*
  * @author Arpit Mandliya
  */
 public static void main(String[] args) {

  System.out.println("-----------------");
  // Read the file
  File mp3File=new File("/Users/Arpit/Desktop/MySong.mp3");
  
  if(mp3File.exists())
  {
   System.out.println("MySong.mp3 file exists");
  }
  else
  {
   System.out.println("MySong.mp3 file does not exist");
  }
  
  System.out.println("-----------------");
  
  File mp3FileFolder=new File("/Users/Arpit/Desktop/MySong");
  
  if(mp3FileFolder.exists())
  {
   System.out.println("MySong folder exists");
  }
  else
  {
   System.out.println("MySong folder does not exist");
  }
  System.out.println("-----------------");
 }

}

When you run above program, you will get following output:
-----------------
MySong.mp3 file exists
-----------------
MySong folder does not exist
-----------------

In this post, we will see how to get extension of file in java. As java.io.File does not provide any direct method for getting extension of file. This is used when you want to process file differently on the basis of its extension. I have worked on a project where I required this utility method.

There are two simple way to get it.
  • using simple String handling program
  • using Apache io

Using simple String handling program:

Create a simple java class named "GetExtensionOfFileMain.java"
package org.arpit.java2blog;

import java.io.File;

public class GetExtensionOfFileMain {

	public static void main(String[] args)
	{
		ClassLoader classLoader = GetExtensionOfFileMain.class.getClassLoader();
		
		File xlsxFile=new File(classLoader.getResource("Countries.xlsx").getFile());
		String fileExtension=getExtensionOfFile(xlsxFile);
		System.out.println("File extension for Countries.xlsx is "+ fileExtension);
		
		File csvFile=new File(classLoader.getResource("Capital.csv").getFile());;
		String fileExtensionCSV=getExtensionOfFile(csvFile);
		System.out.println("File extension for Captial.csv is "+fileExtensionCSV);
		
		File folder=new File("src/main/resources");
		String fileExtensionFolder=getExtensionOfFile(folder);
		System.out.println("File extension for src/main/resources is "+fileExtensionFolder);
	}
	
	public static String getExtensionOfFile(File file)
	{
		String fileExtension="";
		// Get file Name first
		String fileName=file.getName();
		
		// If fileName do not contain "." or starts with "." then it is not a valid file
		if(fileName.contains(".") && fileName.lastIndexOf(".")!= 0)
		{
			fileExtension=fileName.substring(fileName.lastIndexOf(".")+1);
		}
		
		return fileExtension;
	}
}

When you run above program, you will get following output:
File extension for Countries.xlsx is xlsx
File extension for Captial.csv is csv
File extension for src/main/resources is 

Using Apache io:

You need to download Apcahe io jar and put it to the classpath.
After doing above steps, you just need to call FilenameUtils.getExtension to retrieve file name

package org.arpit.java2blog;

import java.io.File;

import org.apache.commons.io.FilenameUtils;

public class GetFileExtensionApache {

	public static void main(String[] args)
	{
		ClassLoader classLoader = GetFileExtensionApache.class.getClassLoader();
		
		File xlsxFile=new File(classLoader.getResource("Countries.xlsx").getFile());
		String fileExtension=FilenameUtils.getExtension(xlsxFile.getName());
		System.out.println("File extension for Countries.xlsx is "+ fileExtension);
		
		File csvFile=new File(classLoader.getResource("Capital.csv").getFile());;
		String fileExtensionCSV=FilenameUtils.getExtension(csvFile.getName());
		System.out.println("File extension for Captial.csv is "+fileExtensionCSV);
		
		File folder=new File("src/main/resources");
		String fileExtensionFolder=FilenameUtils.getExtension(folder.getName());
		System.out.println("File extension for src/main/resources is "+fileExtensionFolder);
	}
	
	
}

When you run above program, you will get foloowing output:
File extension for Countries.xlsx is xlsx
File extension for Captial.csv is csv
File extension for src/main/resources is 









In this post, we will see how to get size of file in java. We can directly use java.io.File 's length method to get its size in bytes. We can convert it to KB and MB accordingly.
package org.arpit.java2blog;

import java.io.File;

public class GetSizeOfFileMain {

	public static void main(String[] args) {
	
		// Read the file
		File mp3File=new File("/Users/Arpit/Desktop/MySong.mp3");
		
		// Use length method to get size of file in bytes
		double fileSizeinBytes=mp3File.length();
		
		System.out.println( "Size of file in bytes :" +fileSizeinBytes + " bytes");
		
		System.out.println( "Size of file in KB :" +(double)fileSizeinBytes/1024 + " KB");
		
		System.out.println( "Size of file in MB :" +(double)fileSizeinBytes/(1024*1024) + " MB");
		

	}

}

When you run above program, you will get following output:
Size of file in bytes :3699969.0 bytes
Size of file in KB :3613.2509765625 KB
Size of file in MB :3.5285654067993164 MB

In this post, we will see how to convert date to string in java. It is more of utility which is mostly used while displaying dates in different string formats while generating any pdf or excel reports.You may also check how to convert string to date

Java program:

package org.arpit.java2blog;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.Calendar;
 
/**
 * SimpleDateFormat example: Convert from a Date to a formatted String
 *

 */
public class SimpleDateFormatExample
{
  public static void main(String[] args)
  {
    //  get today's date
    Date todayDate = Calendar.getInstance().getTime();
 
    //  we need to create format object here by specifying desired string format
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-hh.mm.ss");
 
    // create a new String using the date format we want
    String dateInStringFormat = formatter.format(todayDate);
     
    //  this prints date in required format 
    System.out.println("Date in format yyyy-MM-dd-hh.mm.ss = " + dateInStringFormat);
    
    // More examples:
    
    // Example 2
    formatter = new SimpleDateFormat("dd/MM/yyyy hh.mm.ss");
    dateInStringFormat = formatter.format(todayDate);
    System.out.println("Date in format dd/MM/yyyy hh.mm.ss = " + dateInStringFormat);
    
    // Example 3
    formatter = new SimpleDateFormat("yyyyMMdd");
    dateInStringFormat = formatter.format(todayDate);
    System.out.println("Date in format yyyyMMdd = " + dateInStringFormat);
    
    // Example 4
    formatter = new SimpleDateFormat("E, MMM dd yyyy");
    dateInStringFormat = formatter.format(todayDate);
    System.out.println("Date in format E, MMM dd yyyy = " + dateInStringFormat);
    
  }
}
When you run above program, you will get following output:
Date in format yyyy-MM-dd-hh.mm.ss = 2016-01-26-02.03.02
Date in format dd/MM/yyyy hh.mm.ss = 26/01/2016 02.03.02
Date in format yyyyMMdd = 20160126
Date in format E, MMM dd yyyy = Tue, Jan 26 2016


In this post, we will see how to convert String to Date object in java. It is used when we have formatted String and need to convert it to Date object.You may also check how to convert Date to String

Java program:

package org.arpit.java2blog;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class StringToDateExample {

 public static void main(String[] args) {

  String strDate1 = "25/01/2016";
  String strDate2 = "25-Jan-2014";
  String strDate3 = "Mon, Jan 25 2016";

  /*
   * We will use SimpleDateFormat's parse method to convert String to date. 
   */

  try{

   SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy");

   // use parse method of SimpleDateFormat to convert it to date
   // Date object will be returned by parse method
   Date date1 = sdf1.parse(strDate1);

   System.out.println("Date in format dd/MM/yyyy " + sdf1.format(date1));
   
   
   
   SimpleDateFormat sdf2 = new SimpleDateFormat("dd-MMM-yyyy");
   Date date2 = sdf2.parse(strDate2);
   System.out.println("Date in format dd-MMM-yyyy: " + sdf2.format(date2));
   
   
   SimpleDateFormat sdf3 = new SimpleDateFormat("E, MMM dd yyyy");
   Date date3 = sdf3.parse(strDate3);
   System.out.println("Date in format E, MMM dd yyyy: " + sdf3.format(date3));

  }catch(ParseException e){

   // This exception will be thrown if string can not be converted to date
   System.out.println("Java String could not be converted to Date: " + e);
  }
 }

}

When you run above program, you will get following output:
Date in format dd/MM/yyyy 25/01/2016
Date in format dd-MMM-yyyy: 25-Jan-2014
Date in format E, MMM dd yyyy: Mon, Jan 25 2016

In this post, we will see how to schedule jobs using Spring Quartz scheduler or how to integrate spring with Quartz. We have already seen how to schedule jobs using Timer and TimerTask .

There are two ways by which you can specify quartz jobs.
    MethodInvokingJobDetailFactoryBean JobDetailFactoryBean

JobDetailFactoryBean is used for complex task. You need to create job class which extends QuartzJobBean.

Project structure:


Steps for creating Spring Quartz Scheduler Example using JobDetailFactoryBean are:
Step 1:
Create simple java maven project with Name "SpringQuartzSchedulerExampleUsingQuartzJobBean".

Step 2:
Update pom.xml to put spring core and spring quartz dependencies.
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>com.arpit.java2blog</groupId>
 <artifactId>SpringQuartzSchedulerExample</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <name>SpringQuartzSchedulerExample</name>
 <description>It provide spring quartz scheduler example using MethodInvokingJobDetailFactoryBean</description>
 <dependencies>
  <dependency>
   <groupId>junit</groupId>
   <artifactId>junit</artifactId>
   <version>3.8.1</version>
   <scope>test</scope>
  </dependency>

  <dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>javax.servlet-api</artifactId>
   <version>3.1.0</version>
  </dependency>

  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-core</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-context-support</artifactId>
   <version>${spring.version}</version>
  </dependency>

  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-tx</artifactId>
   <version>${spring.version}</version>
  </dependency>


  <!-- Quartz framework dependencies -->
  <dependency>
   <groupId>org.quartz-scheduler</groupId>
   <artifactId>quartz</artifactId>
   <version>2.2.0</version>
  </dependency>
 </dependencies>
 <build>
  <finalName>SpringQuartzSchedulerExample</finalName>
  <plugins>
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.1</version>
    <configuration>
     <source>${jdk.version}</source>
     <target>${jdk.version}</target>
    </configuration>
   </plugin>
  </plugins>
 </build>
 <properties>
  <spring.version>4.2.1.RELEASE</spring.version>
  <jdk.version>1.7</jdk.version>
 </properties>

</project>
Step 3:
Create  a class called "SendEmailTask.java" in src/main/java in package com.arpit.java2blog.spring.
It is class whose code you want to execute at specific time or time interval repeatedly.
package com.arpit.java2blog.spring;

import java.util.Calendar;

public class SendEmailTask {
 
  public void sendEmail() {
       
    // You may want to put some condition for sending email
          // Actual email send logic   
    System.out.println("Sending email at "+ Calendar.getInstance().getTime());
   
  }
}

Step 4:
Create a class named "JobScheduler.java" in src/main/java in package com.arpit.java2blog.spring.. This class will extend QuartzJobBean and executeInternal method will get called at particular time specified in trigger.
package com.arpit.java2blog.spring;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

public class JobScheduler extends QuartzJobBean {
 SendEmailTask sendEmailTask;

 
 public void setSendEmailTask(SendEmailTask sendEmailTask) {
  this.sendEmailTask = sendEmailTask;
 }


 @Override
 protected void executeInternal(JobExecutionContext arg0) throws JobExecutionException {
  
  sendEmailTask.sendEmail();
 }
 
 
}



Step 5:
In this step, you need to create "quartz-config.xml" in src/main/resources.
quartz-config.xml will have all configuration required to schedule a task . You need to put four entries here
  • Need to specify task (SendEmailTask).
  • Need to specify JobDetailFactoryBean 
  • Need to put entry for triggers which specify time interval and start delay time.
  • Need to specify ScheduleFactoryBean to bind triggers and JobDetailFactoryBean together.
 quartz-config.xml
<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-4.0.xsd
             http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">



 <!--Specify Task bean -->
 <bean id="sendEmailTask" class="com.arpit.java2blog.spring.SendEmailTask" />

 <!-- Spring Quartz -->
 <bean name="emailJob"
  class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
  <property name="jobClass" value="com.arpit.java2blog.spring.JobScheduler" />

  <property name="jobDataAsMap">
   <map>
    <entry key="sendEmailTask" value-ref="sendEmailTask" />
   </map>
  </property>
  <property name="durability" value="true" />
 </bean>


 <!-- simple trigger specify repeat interval and delay time -->
 <bean id="simpleTrigger"
  class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean">

  <property name="jobDetail" ref="emailJob" />
  <property name="repeatInterval" value="10000" />
  <property name="startDelay" value="1000" />

 </bean>

 <!-- scheduler factory bean to bind,the executing code and time intervals 
  together -->
 <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
  <property name="jobDetails">
   <list>
    <ref bean="emailJob" />
   </list>
  </property>

  <property name="triggers">
   <list>
    <ref bean="simpleTrigger" />
   </list>
  </property>
 </bean>

</beans>
Step 6: 
Finally we will create main class to execute this. We will create object of ClassPathXmlApplicationContext to load quartz-config.xml create class name Application.java in src/main/java in package com.arpit.java2blog.spring
package com.arpit.java2blog.spring;

/**
 * @author Arpit Mandliya
 *
 */
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Application {

public static void main(String[] args) throws Exception {
  new ClassPathXmlApplicationContext("quartz-config.xml");
 }
}

Step 7:
When you run above program, you will get following output.
Jan 24, 2016 1:09:13 AM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@1441e2aa: startup date [Sun Jan 24 01:09:13 IST 2016]; root of context hierarchy
Jan 24, 2016 1:09:13 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [quartz-config.xml]
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Jan 24, 2016 1:09:14 AM org.springframework.context.support.DefaultLifecycleProcessor start
INFO: Starting beans in phase 2147483647
Jan 24, 2016 1:09:14 AM org.springframework.scheduling.quartz.SchedulerFactoryBean startScheduler
INFO: Starting Quartz Scheduler now
Sending email at Sun Jan 24 01:09:15 IST 2016
Sending email at Sun Jan 24 01:09:25 IST 2016
Sending email at Sun Jan 24 01:09:35 IST 2016
Sending email at Sun Jan 24 01:09:45 IST 2016
Sending email at Sun Jan 24 01:09:55 IST 2016

Download source code:

click to begin
20KB .zip

We are done with Spring Quartz Scheduler Example using JobDetailFactoryBean.

In this post, we will see how to schedule jobs using Spring Quartz scheduler or how to integrate spring with Quartz. We have already seen how to schedule jobs using Timer and TimerTask .

There are two ways by which you can specify quartz jobs.
    MethodInvokingJobDetailFactoryBean JobDetailFactoryBean

MethodInvokingJobDetailFactoryBean is used for simpler task. It specifies target object and target method, so target object's method will be executed at the time specified using trigger.

Project structure:




Steps for creating Spring Quartz Scheduler Example using MethodInvokingJobDetailFactoryBean are:
Step 1:
Create simple java maven project with Name "SpringQuartzSchedulerExample".

Step 2:
Update pom.xml to put spring core and spring quartz dependencies.
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>com.arpit.java2blog</groupId>
 <artifactId>SpringQuartzSchedulerExample</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <name>SpringQuartzSchedulerExample</name>
 <description>It provide spring quartz scheduler example using MethodInvokingJobDetailFactoryBean</description>
 <dependencies>
  <dependency>
   <groupId>junit</groupId>
   <artifactId>junit</artifactId>
   <version>3.8.1</version>
   <scope>test</scope>
  </dependency>

  <dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>javax.servlet-api</artifactId>
   <version>3.1.0</version>
  </dependency>

  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-core</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-context-support</artifactId>
   <version>${spring.version}</version>
  </dependency>

  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-tx</artifactId>
   <version>${spring.version}</version>
  </dependency>


  <!-- Quartz framework dependencies -->
  <dependency>
   <groupId>org.quartz-scheduler</groupId>
   <artifactId>quartz</artifactId>
   <version>2.2.0</version>
  </dependency>
 </dependencies>
 <build>
  <finalName>SpringQuartzSchedulerExample</finalName>
  <plugins>
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.1</version>
    <configuration>
     <source>${jdk.version}</source>
     <target>${jdk.version}</target>
    </configuration>
   </plugin>
  </plugins>
 </build>
 <properties>
  <spring.version>4.2.1.RELEASE</spring.version>
  <jdk.version>1.7</jdk.version>
 </properties>

</project>
Step 3:
Create  a class called "SendEmailTask.java" in src/main/java in package com.arpit.java2blog.spring.
It is class whose code you want to execute at specific time or time interval repeatedly.
package com.arpit.java2blog.spring;

import java.util.Calendar;

public class SendEmailTask {
 
  public void sendEmail() {
       
    // You may want to put some condition for sending email
          // Actual email send logic   
    System.out.println("Sending email at "+ Calendar.getInstance().getTime());
   
  }
}

Step 4:
In this step, you need to create "quartz-config.xml" in src/main/resources.
quartz-config.xml will have all configuration required to schedule a task . You need to put four entries here
  • Need to specify task (SendEmailTask).
  • Need to specify MethodInvokingJobDetailFactoryBean which specify class and method which will get executed.
  • Need to put entry for triggers which specify time interval and start delay time.
  • Need to specify ScheduleFactoryBean to bind triggers and MethodInvokingJobDetailFactoryBean together.
 quartz-config.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-4.0.xsd
             http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

 <!--Specify Task bean  -->
 <bean id="sendEmailTask" class="com.arpit.java2blog.spring.SendEmailTask" />

 <!-- specifing class and method that is going to be called on a specified 
  time basis -->
 <bean id="emailJob"
  class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
  <property name="targetObject" ref="sendEmailTask" />
  <property name="targetMethod" value="sendEmail" />
 </bean>

 <!-- simple trigger specify repeat interval and delay time -->
 <bean id="simpleTrigger"
  class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean">
  <property name="jobDetail" ref="emailJob" />
  <property name="repeatInterval" value="10000" />
  <property name="startDelay" value="1000" />
 </bean>

 <!-- scheduler factory bean to put,the executing code and time intervals 
  together -->
 <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
  <property name="jobDetails">
   <list>
    <ref bean="emailJob" />
   </list>
  </property>
  <property name="triggers">
   <list>
    <ref bean="simpleTrigger" />
   </list>
  </property>
 </bean>

</beans>

Step 5: 
Finally we will create main class to execute this. We will create object of ClassPathXmlApplicationContext to load quartz-config.xml create class name Application.java in src/main/java in package com.arpit.java2blog.spring
package com.arpit.java2blog.spring;

/**
 * @author Arpit Mandliya
 *
 */
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Application {

public static void main(String[] args) throws Exception {
  new ClassPathXmlApplicationContext("quartz-config.xml");
 }
}

Step 6:
When you run above program, you will get following output.
Jan 17, 2016 3:15:52 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@1441e2aa: startup date [Sun Jan 17 15:15:52 IST 2016]; root of context hierarchy
Jan 17, 2016 3:15:53 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [quartz-config.xml]
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Jan 17, 2016 3:15:53 PM org.springframework.context.support.DefaultLifecycleProcessor start
INFO: Starting beans in phase 2147483647
Jan 17, 2016 3:15:53 PM org.springframework.scheduling.quartz.SchedulerFactoryBean startScheduler
INFO: Starting Quartz Scheduler now
Sending email at Sun Jan 17 15:15:54 IST 2016
Sending email at Sun Jan 17 15:16:04 IST 2016
Sending email at Sun Jan 17 15:16:14 IST 2016
Sending email at Sun Jan 17 15:16:24 IST 2016
Sending email at Sun Jan 17 15:16:34 IST 2016

Download source code:

click to begin
20KB .zip

We are done with Spring Quartz Scheduler Example using MethodInvokingJobDetailFactoryBean.

In this post, we will see how to create a simple java project using maven in eclipse. We have already seen before how to create dynamic web project using maven in eclipse.

I am using following tools for this post.
  • eclipse-jee-mars-R-macosx-cocoa-x86_64
  • Apache tomcat 8
  • m2eclipse plugin
  • jdk 1.7

Steps for creating dynamic web project using maven in eclipse.


1) Install m2eclipse for maven plugin in eclipse. Please follow this link for installing m2eclipse plugin in eclipse.

2) goto new -> project-> Maven Project and click on next

3) You will see below screen , again click on next

4) We need to put group id and artifact id here.

Let me tell you more about group id and artifact id.

Group id : It uniquely identifies your project among all. So it may be something like com.companyname

Artifact id : It is name of jar or war without version. it may be something like project, so here we have put artifact id as SimpleJavaProjectUsingMaven

Version : Version is used for version control for artifact id. If you distribute this project, you may incrementally create different version of it.

If we have any dependency on any parent project, we can declare it in Parent project.
New Maven Java Project

5) Click on finish , you will see  project structure as below

Bingo !! we are done with simple java project using maven in eclipse.

Please comment if you are facing any issue with this.

In previous post,we have used default login page generated by Spring security framework. In this post, we will see how to use custom login page in Spring security.

Spring MVC tutorial:

    Spring MVC hello world example Spring MVC Hibernate MySQL example Spring MVC interceptor example Spring MVC angularjs example Spring MVC @RequestMapping example Spring Component,Service, Repository and Controller example Spring MVC @ModelAttribute annotation example Spring MVC @RestController annotation example Spring MultiActionController Example Spring MVC ModelMap Spring MVC file upload example Spring restful web service example Spring restful web service json example Spring Restful web services CRUD example Spring security hello world example Spring security custom login form example
In this post, we will see how to apply custom login form  spring security to spring mvc hello world example.

If you want to secure your spring web application , you just need to configure some files to make it happen using spring security. We will apply login security on hello world example, so when only authorised users will be able to access hello world message.

Here are steps to apply spring security custom login form on spring mvc hello world example.

Step 1: 
Create Spring mvc hello world example named SpringSecurityHelloWorldExample . It will create basic spring mvc application.

Step 2: 
Add spring security to pom.xml. You need to add following dependencies to the pom.
pom.xml 
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>com.arpit.java2blog</groupId>
 <artifactId>SpringSecurityHelloWorlExample</artifactId>
 <packaging>war</packaging>
 <version>0.0.1-SNAPSHOT</version>
 <name>SpringSecurityHelloWorldExample Maven Webapp</name>
 <url>http://maven.apache.org</url>
 <dependencies>
  <dependency>
   <groupId>junit</groupId>
   <artifactId>junit</artifactId>
   <version>3.8.1</version>
   <scope>test</scope>
  </dependency>

  <dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>javax.servlet-api</artifactId>
   <version>3.1.0</version>
  </dependency>

  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-core</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>${spring.version}</version>
  </dependency>
   <!-- Spring Security -->
               <dependency>
               <groupId>org.springframework.security</groupId>
               <artifactId>spring-security-core</artifactId>
               <version>${security.version}</version>
               </dependency>

               <dependency>
               <groupId>org.springframework.security</groupId>
               <artifactId>spring-security-web</artifactId>
               <version>${security.version}</version>
               </dependency>

               <dependency>
               <groupId>org.springframework.security</groupId>
               <artifactId>spring-security-config</artifactId>
               <version>${security.version}</version>
               </dependency>

               <dependency>
               <groupId>jstl</groupId>
               <artifactId>jstl</artifactId>
               <version>1.2</version>
               <scope>provided</scope>
               </dependency>
 </dependencies>
 <build>
  <finalName>SpringSecurityHelloWorlExample</finalName>

  <plugins>
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.1</version>
    <configuration>
     <source>${jdk.version}</source>
     <target>${jdk.version}</target>
    </configuration>
   </plugin>
  </plugins>

 </build>
 <properties>
  <spring.version>4.2.1.RELEASE</spring.version>
  <security.version>4.0.3.RELEASE</security.version>
  <jdk.version>1.7</jdk.version>
 </properties>
 
 
</project>

Create Controller  and view

step 3:
Change controller class named "HelloWorldController.java" as below
package org.arpit.java2blog.springmvc.controller;

import java.security.Principal;

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

@Controller
public class HelloWorldController {

 @RequestMapping("/helloworld")
 public ModelAndView hello(ModelMap model,Principal principal) {

  String loggedInUserName=principal.getName();
  
  return new ModelAndView("hello", "userName", loggedInUserName);
 }

 @RequestMapping(value="/login", method = RequestMethod.GET)
 public String login(ModelMap model) {

  return "login";

 }

 @RequestMapping(value="/loginError", method = RequestMethod.GET)
 public String loginError(ModelMap model) {
  model.addAttribute("error", "true");
  return "login";

 }
}


As  request first goes to dispatcherServlet and it redirects to controller class. Here @Controller depicts that this is our controller class. @RequestMapper is used to map incoming http request to handler method(hello() in above controller).So hello() method of HelloWorldController.java will handle GET request from dispatcher.
Here We have used Principal object to get current logged in username. It is set by Spring security framework.

Step 4: 
Modify hello.jsp in /WEB-INF/pages folder
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>  
<!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=UTF-8">
<title>Hello</title>
</head>
<body>
${message}


<c:url value="/j_spring_security_logout" var="logoutUrl" />
<a href="${logoutUrl}">Log Out</a>
 
</body>
</html>

Step 5:
Create login.jsp in /WEB-INF/pages folder
 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>  
<html>
<style type="text/css">
<%@include file="style.css" %>
</style>
<head>
<title>Custom Login Page</title>
</head>
<body onload='document.loginForm.j_username.focus();'>
<h3>Custom Login Page</h3>
 
<%
 
String errorString = (String)request.getAttribute("error");
if(errorString != null && errorString.trim().equals("true")){
out.println("<span class=\"dark\">Incorrect login name or password. Please try again");
}
%>
 
<form name='loginForm' action="<c:url value='login' />""
method='POST'>
 
<table>
<tr>
<td>User:</td>
<td><input type='text' name='username' value=''>
</td>
</tr>
<tr>
<td>Password:</td>
<td><input type='password' name='password' />
</td>
</tr>
<tr>
<td><input name="submit" type="submit"
value="submit" />
</td>
<td><input name="reset" type="reset" />
</td>
</tr>
</table>
 
</form>
</body>
</html>
We have used css file in above login.jsp. Create style.css file as below.
#header
{
font-size:40px;
}
.dark
{
color:red;
}

Step 6:  

Now we need to add spring configuration xml. Create a file named spring-security.xml.
<beans:beans xmlns="http://www.springframework.org/schema/security"
 xmlns:beans="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-4.0.xsd
    http://www.springframework.org/schema/security
    http://www.springframework.org/schema/security/spring-security-4.0.xsd">

 <http auto-config="true" use-expressions="true">
  <intercept-url pattern="/resources/**" access="permitAll" />
  <intercept-url pattern="/hello*" access="hasRole('ROLE_ADMIN')" />
  
<form-login login-page="/login" default-target-url="/helloworld"
   authentication-failure-url="/loginError" />
  <logout logout-success-url="/" logout-url="/j_spring_security_logout" />
  <csrf disabled="true" />
 </http>

 <authentication-manager>
  <authentication-provider>
   <user-service>
    <user name="java2blog" password="java123" authorities="ROLE_ADMIN" />
    <user name="arpit" password="arpit123" authorities="ROLE_ADMIN" />

   </user-service>
  </authentication-provider>
 </authentication-manager>

</beans:beans>

We have used form-login in above file, so if user tries to access any secured url, he will be authenticated based on above form-login configuration.
Lets understand meaning of each attribute of form-login tag

login-page : we need to provide url for login page.
default-target-url : here if authentication is successful, then target page url should be provided.
authentication-failure-url : if authentication is unsuccessful, then redirection page url should be provided here.

intercept-url configure for which pattern what kind of security is configured. For example: If http request url has pattern /hello*(hello.jsp,helloworld.html), it will be accessed to ROLE_ADMIN only.

We have hardcoded username(java2blog and arpit) and password(java123 and arpit123)   in authentication manager, so if user provides correct credential for admin then only he will be able to access helloworld.html.

Step 7: 
springmvc-dispatcher-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:mvc="http://www.springframework.org/schema/mvc" 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/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">

<context:component-scan base-package="org.arpit.java2blog.springmvc.controller" />

 <bean
  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="prefix">
   <value>/WEB-INF/pages/</value>
  </property>
  <property name="suffix">
   <value>.jsp</value>
  </property>
 </bean>
 <mvc:annotation-driven/>

</beans>


Step 8: We need to change in web.xml to configure spring security.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <display-name>Archetype Created Web Application</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>springmvc-dispatcher</servlet-name>
    <servlet-class>
   org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc-dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
   <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>
   /WEB-INF/springmvc-dispatcher-servlet.xml,
   /WEB-INF/spring-security.xml
  </param-value>
 </context-param>
 
 <listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>

 <!-- Spring Security -->
 <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>
  
</web-app>
Here we have used DelegatingFilterProxy which intercepts http request and pass it to springSecurityFilterChain. springSecurityFilterChain is a bean created by spring with http element used in spring-security.xml. It maintains list of all filters and is responsible for chain of filters.

We are done with changes required for spring security.

Step 9:
It's time for maven build.
   
Provide goals as clean install (given below) and click on run


Run the application


Step 10:
Right click on project -> run as -> run on server
Select apache tomcat and click on finish

   You will see below screen:

When you click on above link, you will get following login page.
If you put wrong password and try to login, you will get below screen
 


If you put correct user id and password


Bingo !! you have logged in successfully.

When you click on logout, you will be back to first screen.

Download source code:

click to begin
20KB .zip
Please comment if you have any issues with above post.

In this post, we will see how to apply basic spring security to spring mvc hello world example.

Spring MVC tutorial:

    Spring MVC hello world example Spring MVC Hibernate MySQL example Spring MVC interceptor example Spring MVC angularjs example Spring MVC @RequestMapping example Spring Component,Service, Repository and Controller example Spring MVC @ModelAttribute annotation example Spring MVC @RestController annotation example Spring MultiActionController Example Spring MVC ModelMap Spring MVC file upload example Spring restful web service example Spring restful web service json example Spring Restful web services CRUD example Spring security hello world example Spring security custom login form example
If you want to secure your spring web application , you just need to configure some files to make it happen using spring security. We will apply login security on hello world example. So when only authorised users will be able to access hello world message.

Here are steps to apply basic spring security on spring mvc hello world example.

Step 1: 
Create Spring mvc hello world example named SpringSecurityHelloWorldExample . It will create basic spring mvc application.

Step 2: 
Add spring security to pom.xml. You need to add following dependencies to the pom.
pom.xml 
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>com.arpit.java2blog</groupId>
 <artifactId>SpringSecurityHelloWorlExample</artifactId>
 <packaging>war</packaging>
 <version>0.0.1-SNAPSHOT</version>
 <name>SpringSecurityHelloWorldExample Maven Webapp</name>
 <url>http://maven.apache.org</url>
 <dependencies>
  <dependency>
   <groupId>junit</groupId>
   <artifactId>junit</artifactId>
   <version>3.8.1</version>
   <scope>test</scope>
  </dependency>

  <dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>javax.servlet-api</artifactId>
   <version>3.1.0</version>
  </dependency>

  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-core</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>${spring.version}</version>
  </dependency>
   <!-- Spring Security -->
               <dependency>
               <groupId>org.springframework.security</groupId>
               <artifactId>spring-security-core</artifactId>
               <version>${security.version}</version>
               </dependency>

               <dependency>
               <groupId>org.springframework.security</groupId>
               <artifactId>spring-security-web</artifactId>
               <version>${security.version}</version>
               </dependency>

               <dependency>
               <groupId>org.springframework.security</groupId>
               <artifactId>spring-security-config</artifactId>
               <version>${security.version}</version>
               </dependency>

               <dependency>
               <groupId>jstl</groupId>
               <artifactId>jstl</artifactId>
               <version>1.2</version>
               <scope>provided</scope>
               </dependency>
 </dependencies>
 <build>
  <finalName>SpringSecurityHelloWorlExample</finalName>

  <plugins>
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.1</version>
    <configuration>
     <source>${jdk.version}</source>
     <target>${jdk.version}</target>
    </configuration>
   </plugin>
  </plugins>

 </build>
 <properties>
  <spring.version>4.2.1.RELEASE</spring.version>
  <security.version>4.0.3.RELEASE</security.version>
  <jdk.version>1.7</jdk.version>
 </properties>
 
 
</project>
Step 3: 
Modify hello.jsp in /WEB-INF/ folder
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>  
<!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=UTF-8">
<title>Hello</title>
</head>
<body>
${message}


<c:url value="/j_spring_security_logout" var="logoutUrl" />
<a href="${logoutUrl}">Log Out</a>
 
</body>
</html>

Step 4:  
Now we need to add spring configuration xml. Create a file named spring-security.xml.
<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="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-4.0.xsd
    http://www.springframework.org/schema/security
    http://www.springframework.org/schema/security/spring-security-4.0.xsd">

    <http auto-config="true" use-expressions="true">
      <intercept-url pattern="/resources/**" access="permitAll" />

       <intercept-url pattern="/hello*" access="hasRole('ROLE_ADMIN')" />
<logout logout-success-url="/" logout-url="/j_spring_security_logout" />
   <csrf disabled="true"/>
    </http>

    <authentication-manager>
      <authentication-provider>
        <user-service>
            <user name="java2blog" password="java123" authorities="ROLE_ADMIN" />
           
        </user-service>
      </authentication-provider>
    </authentication-manager>

</beans:beans>

intercept-url configure for which pattern what kind of security is configured. For example: If http request url has pattern /hello*(hello.jsp,helloworld.html), it will be accessed to ROLE_ADMIN only.

We have hardcoded username(java2blog) and password(java123)   in authentication manager, so if user provides correct credential for admin then only he will be able to access helloworld.htm/.

We have not configured any login page here, so spring security will generate one for us.

Step 5: We need to change in web.xml to configure spring security.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <display-name>Archetype Created Web Application</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>springmvc-dispatcher</servlet-name>
    <servlet-class>
   org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc-dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
   <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>
   /WEB-INF/springmvc-dispatcher-servlet.xml,
   /WEB-INF/spring-security.xml
  </param-value>
 </context-param>
 
 <listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>

 <!-- Spring Security -->
 <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>
  
</web-app>
Here we have used DelegatingFilterProxy which intercepts http request and pass it to springSecurityFilterChain. springSecurityFilterChain is a bean created by spring with http element used in spring-security.xml. It maintains list of all filters and is responsible for chain of filters.

We are done with changes required for spring security.

Step 6:
It's time for maven build.
   
Provide goals as clean install (given below) and click on run


Run the application


Step 7:
Right click on project -> run as -> run on server
Select apache tomcat and click on finish

   You will see below screen:


When you click on above link, you will get following login page.


If you put wrong password and try to login, you will get below screen


If you put correct user id and password



Bingo !! you have logged in successfully.


When you click on logout, you will be back to first screen.

Download source code:

click to begin
20KB .zip
Please comment if you have any issues with above post.
 

Java tutorial for beginners Copyright © 2012