dineshonjava

JSTL SQL Transaction<sql:transaction> Tag Example

The <sql:transaction> tag is used to group <sql:query> and <sql:update> into transactions. You can put as many <sql:query> and <sql:update> as statements inside <sql:transaction> to make them a single transaction.

It ensures that the database modifications performed by the nested actions are either committed or rolled back if an exception is thrown by any nested action.

JSTL Transaction Tag provides the capability to run SQL statement in a group. You can run multiple SQL statements at a time. It is called one single transaction. In this transaction either all statments run successfully or all fail if one statement does not run successfully.

Syntax
<sql:transaction dataSource="<string>" isolation="<string>"/>

JSTL Transaction Tag has following attribute.

1. dataSource Attribute: Specifies the datasource for the transaction.

2. isolation Attribute: Specifies the level of isolation for the transaction.

JSTL SQL Transaction Tag Example:-

<%@ page import="java.io.*,java.util.*,java.sql.*"%>
<%@ page import="javax.servlet.http.*,javax.servlet.*"%>
<%@ page import="java.util.Date,java.text.*" %>

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
 
<html>
<head>
<title>JSTL sql:transaction Tag</title>
</head>
<body>
 
<sql:setDataSource var="snapshot" driver="com.mysql.jdbc.Driver"
     url="jdbc:mysql://localhost/TEST"
     user="root"  password="cohondob"/>

<%
Date DoB = new Date("2013/10/23");
int studentId = 1111;
%>

<sql:transaction dataSource="${snapshot}">
   <sql:update var="count">
      UPDATE Students SET firstName = 'Sandhya' WHERE Id = 2222
   </sql:update>
   <sql:update var="count">
      UPDATE Students SET fistName = 'Sweetu' WHERE Id = 3333
   </sql:update>
   <sql:update var="count">
     INSERT INTO Students 
     VALUES (4444,'Neha', 'Verma', '2013/10/23');
   </sql:update>
</sql:transaction>

<sql:query dataSource="${snapshot}" var="result">
   SELECT * from Students;
</sql:query>
 
<table border="1" width="100%">
<tr>
<th>Emp ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>DoB</th>
</tr>
<c:forEach var="row" items="${result.rows}">
<tr>
<td><c:out value="${row.id}"/></td>
<td><c:out value="${row.first}"/></td>
<td><c:out value="${row.last}"/></td>
<td><c:out value="${row.dob}"/></td>
</tr>
</c:forEach>
</table>
 
</body>
</html>



Now try to access above JSP, which should display the following result:

Emp ID First Name Last Name DOB
1111 Dinesh Rajput 2013/10/23
2222 Anu Rajput 2013/10/23
2222 Sweetu Rajput 2013/10/23
2222 Sandhya Bansal 2013/10/23


<<Previous <<   || Index ||   >>Next >>





JSTL SQL dateParam<sql:dateParam> Tag Example

The <sql:dateParam> tag is used as a nested action for <sql:query> and <sql:update> supply a date and time value for a value placeholder. If a null value is provided, the value is set to SQL NULL for the placeholder.

JSTL dateParam Tag provides the value of the date parameter. In SQL update statement, date paramter is sent using JSTL dateParam tag.

Syntax
<sql:dateParam value="<string>" type="<string>"/>

JSTL Param Tag has following attribute.

1. value Attribute: Specifies the value of the date parameter.
2. type Attribute: Specifies the type of the parameter. It can be DATE , TIME or TIMESTAMP. TIMESTAMP is the default value.

JSTL SQL date param Tag Example:
To start with basic concept, let us create a simple table Students table in TEST database and create few records in that table as follows:

<%@ page import="java.io.*,java.util.*,java.sql.*"%>
<%@ page import="javax.servlet.http.*,javax.servlet.*" %>
<%@ page import="java.util.Date,java.text.*" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
 
<html>
<head>
<title>JSTL sql:dataParam Tag</title>
</head>
<body>
 
<sql:setDataSource var="snapshot" driver="com.mysql.jdbc.Driver"
     url="jdbc:mysql://localhost/TEST"
     user="root"  password="pass123"/>

<%
Date DoB = new Date("12-08-1987");
int empId = 1111;
%>
 
<sql:update dataSource="${snapshot}" var="count">
   UPDATE Students SET dob = ? WHERE Id = ?
   <sql:dateParam value="<%=DoB%>" type="DATE" />
   <sql:param value="<%=studentId%>" />
</sql:update>
 
<sql:query dataSource="${snapshot}" var="result">
   SELECT * from Students;
</sql:query>
 
<table border="1" width="100%">
<tr>
   <th>Emp ID</th>
   <th>First Name</th>
   <th>Last Name</th>
   <th>DoB</th>
</tr>
<c:forEach var="row" items="${result.rows}">
<tr>
   <td><c:out value="${row.id}"/></td>
   <td><c:out value="${row.first}"/></td>
   <td><c:out value="${row.last}"/></td>
   <td><c:out value="${row.dob}"/></td>
</tr>
</c:forEach>
</table>
 
</body>
</html>


Now try to access above JSP, which should display the following result:

Emp ID First Name Last Name DOB
1111 Dinesh Rajput 12-08-1987
2222 Sweety Rajput 20-11-1989


<<Previous <<   || Index ||   >>Next >>





JSTL SQL Param<sql:param> Tag Example

JSTL Param Tag provides the value of the parameter. In SQL update statement, paramters are sent using JSTL Param tag. The <sql:param> tag is used to set the parameters to the SQL query. We use this tag to set the placeholders and data to match the placeholder position to insert the data into the database or to update the database records. This tag is used as a nested tag inside the <sql:query> to provide the parameters to the query.

Syntax
<sql:param value="<string>"/>

JSTL Param Tag has following attribute.

1. value Attribute: Specifies the value of the parameter.

JSTL <sql:param> Tag Example:-
The following example takes input from the employee and inserts the entered citizen information into the database using the combination of <sql:query> and <sql:param> tags. The list of records are displayed in tabular manner once the new record has been inserted.

Now let us write a JSP which will make use of <sql:update> to execute a SQL DELETE statement to delete one record with id = 103 from the table as follows:

<%@ page import="java.io.*,java.util.*,java.sql.*"%>
<%@ page import="javax.servlet.http.*,javax.servlet.*" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>

<html>
<head>
<title>JSTL sql:param Tag</title>
</head>
<body>
 
<sql:setDataSource var="snapshot" driver="com.mysql.jdbc.Driver"
     url="jdbc:mysql://localhost:3306/DAVDB"
     user="root"  password="root"/>

<c:set var="empId" value="3333"/>

<sql:update dataSource="${snapshot}" var="count">
  DELETE FROM Employees WHERE Id = ?
  <sql:param value="${empId}" />
</sql:update>

<sql:query dataSource="${snapshot}" var="result">
   SELECT * from Employees;
</sql:query>
 
<table border="1" width="100%">
<tr>
<th>Emp ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
</tr>
<c:forEach var="row" items="${result.rows}">
<tr>
<td><c:out value="${row.id}"/></td>
<td><c:out value="${row.first}"/></td>
<td><c:out value="${row.last}"/></td>
<td><c:out value="${row.age}"/></td>
</tr>
</c:forEach>
</table>

</body>
</html>



Now try to access above JSP, which should display the following result:

Emp ID First Name Last Name Age
1111 Dinesh Rajput 27
2222 Sweety Rajput 23


<<Previous <<   || Index ||   >>Next >>





JSTL <sql:update>SQL UPDATE Tag Example

JSTL Update Tag provides capability to write insert, update or delete statements directly from JSP.

The <sql:update> tag executes the provided SQL query through its body or through its sql attribute. Execution SQL queries using <sql:update> tag does not return any data. This tag can execute INSERT, UPDATE and DELETE statements.

Syntax-
<sql:update var="<string>" scope="<string>" sql="<string>" dataSource="<string>"/>

JSTL <sql:Update> Tag has following attributes.

1. datasource Attribute: Specifies the datasource. Make sure that you already created datasource using serDataSource tag before writing query.

2. sql Attribute: Specifies the SQL statement to run on database.

3. var Attribute: Store the result of SQL statement.

JSTL SQL UPDATE Tag Example:
Now let us write a JSP which will make use of <sql:update> to execute a SQL INSERT statement to create one record in the table as follows:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>JSTL SQL Tags - setDataSource Example</title>
</head>
<body>

 <sql:setDataSource driver="com.mysql.jdbc.Driver"
            url="jdbc:mysql://localhost:3306/database_name"
            var="localSource" 
            user="database_user"  
            password="database_password"/>
<sql:update dataSource="${snapshot}" var="count">
   INSERT INTO Employees VALUES (333, 27, 'Anamika', 'Rajput');
</sql:update>
 <sql:query dataSource="${localSource}" var="result">
SELECT * from Employees;
</sql:query>
 
<table border="1" width="100%">
<tr>
<th>Emp ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
</tr>
<c:forEach var="row" items="${result.rows}">
<tr>
<td><c:out value="${row.id}"/></td>
<td><c:out value="${row.first}"/></td>
<td><c:out value="${row.last}"/></td>
<td><c:out value="${row.age}"/></td>
</tr>
</c:forEach>
</table>
</body>
</html>


Now try to access above JSP, which should display the following result:

Emp ID First Name Last Name Age
1111 Dinesh Rajput 27
2222 Sweety Rajput 23
3333 Anamika Rajput 23


<<Previous <<   || Index ||   >>Next >>





JSTL SQL Query Tag <sql:query> Example

JSTL Query Tag provides capability to fetch the data from databased by executing query directly from JSP and it can be stored in a variable to use later with the help of scope attribute.

JSTL SQL Query Tag has following attributes.

1. datasource Attribute: Specifies the datasource. Make sure that you already created datasource using serDataSource tag before writing query.

2. sql Attribute: Specifies the SQL statement to run on database.

3. var Attribute: Store the result of SQL statement.

Syntax-
<sql:query

  var="<string>"

  scope="<string>"

  sql="<string>"

  dataSource="<string>"

  startRow="<string>"

  maxRows="<string>"/>


JSP SQL <sql:query> tag Example:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>JSTL SQL Tags - setDataSource Example</title>
</head>
<body>

 <sql:setDataSource driver="com.mysql.jdbc.Driver"
            url="jdbc:mysql://localhost:3306/database_name"
            var="localSource" 
            user="database_user"  
            password="database_password"/>

 <sql:query dataSource="${localSource}" var="result">
SELECT * from Employees;
</sql:query>
 
<table border="1" width="100%">
<tr>
<th>Emp ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
</tr>
<c:forEach var="row" items="${result.rows}">
<tr>
<td><c:out value="${row.id}"/></td>
<td><c:out value="${row.first}"/></td>
<td><c:out value="${row.last}"/></td>
<td><c:out value="${row.age}"/></td>
</tr>
</c:forEach>
</table>
</body>
</html>

Now try to access above JSP, which should display the following result:

Emp ID First Name Last Name Age
1111 Dinesh Rajput 27
2222 Sweety Rajput 24




<<Previous <<   || Index ||   >>Next >>




JSTL SQL SetDataSource<sql:setDataSource> Example

JSTL setDataSource Tag provides capability to create a datasource directly from JSP and it can be stored in a variable to use later with the help of scope attribute.

Syntax-
<sql:setDataSource

  var="<string>"

  scope="<string>"

  dataSource="<string>"

  driver="<string>"

  url="<string>"

  user="<string>"

  password="<string>"/>


JSP <sql:setDataSource> Tag has following attributes.

1. driver Attribute: Specifies the driver to connect database. For each database there is a separate driver. In this example, we are connecting to MySQL database and hence driver is com.mysql.jdbc.Driver

2. url Attribute: Specifies the location of the database.

3. var Attribute: Specifies the variable which holds the dataSource once it is created.

4. user Attribute: Specifies the user you already created to access database.

5. password Attribute: Specifies the password for the user you already assigned to access database.

JSP setDataSource Example:

Consider the following information about your MySQL database setup:
  • We are using JDBC MySQL driver.
  • We are going to connect to TEST database on local machine.
  • We would use user_id and mypassword to access TEST database.

All the above parameters would vary based on your MySQL or any other database setup. Keeping above parameters in mind, following is a simple example to use setDataSource tag:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>JSTL SQL Tags - setDataSource Example</title>
</head>
<body>

 <sql:setDataSource driver="com.mysql.jdbc.Driver"
            url="jdbc:mysql://localhost:3306/database_name"
            var="localSource" 
            user="database_user"  
            password="database_password"/>

 <sql:query dataSource="${localSource}" 
            sql="SELECT * FROM employee WHERE salary > 10000" 
            var="result" />
 
</body>
</html>

As shown above setDataSource Tag set data source in a variable localSource. Using this data source, you can do SQL operations directly from JSP.




<<Previous <<   || Index ||   >>Next >>




JSTL Format Tag <fmt:requestEncoding> Example

The <fmt:requestEncoding> tag is used to specify the character encoding of the request. The character encoding specified using this tag is used to decode the incoming forms data entered by the user. We must use this tag to set the character encoding if the encoding used is different from the ISO-8859-1.

Even if the contentType is defined in the JSP page directive by the programmer, the character encoding must be specified because the actual user’s locale may be different from the defined value in the page directive.

Syntax
<fmt:requestEncoding value="<string>"/>

Attribute:
The tag has following attributes:

key: Name of character encoding you want to apply when decoding request parameters.

You use the
tag when you want to specify character encoding for decoding data posted from forms. This tag must be used with character encodings that are different from ISO-8859-1. The tag is required since most browsers do not include a Content-Type header in their requests.

The purpose of the
tag is to specify the content type of the request. You must specify the content type, even if the encoding of the page generating the response is specified via the contentType attribute of a page directive. This is because the response's actual locale (and thus character encoding) may differ from the value specified in the page directive.

If the page contains an I18N-capable formatting action that sets the response's locale (and thus character encoding) by calling ServletResponse.setLocale(), any encoding specified in the page directive will be overridden.

Example-
The following JSP code sets the character encoding to UTF-8 and displayed localized messages.


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>JSTL fmt:requestEncoding Tag</title>
</head>
<body>
<fmt:requestEncoding value="UTF-8" />
<fmt:setBundle basename="myapp" var="lang"/>
<fmt:setLocale value="en"/>
<fmt:message key="Name" bundle="${lang}"/><br/>
<fmt:message key="Address" bundle="${lang}"/><br/>
<fmt:message key="Number" bundle="${lang}"/><br/>
</body>
</html>
myapp.properties
Name=Dinesh
Address=Noida
Number=9988998899

This would produce following result:




<<Previous <<   || Index ||   >>Next >>




JSTL fmt Tag message <fmt:message> Example

<fmt:message> tag is used to map the key from the key-value paired mapped localized message and returns the value by replacing the key to the respective value.

Syntax
<fmt:message

   key="<string>"

   bundle="<string>"

   var="<string>"

   scope="<string>"/>


Attributes of <fmt:message>:

key : This attribute is an optional attribute that is used for specifying the key (key from the key-value paired localized message) of which value you want to show.
bundle : This attribute is an optional attribute that is used for specifying the Localization context in whose resource bundle message key's value you want to show.
var : This attribute is an optional attribute that is used for specifying the name of the scoped variable that have stored the localized message.
scope : This attribute is an optional attribute and is used for specifying the scope of var.

Example :

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>JSTL fmt:message Tag</title>
</head>
<body>
<fmt:setBundle basename="myapp" var="lang"/>
<fmt:setLocale value="hi_IN"/>
<fmt:message key="Name" bundle="${lang}"/><br/>
<fmt:message key="Address" bundle="${lang}"/><br/>
<fmt:message key="Number" bundle="${lang}"/><br/>
</body>
</html>

myapp.properties
Name=\u0926\u093F\u0928\u0947\u0936
Address=\u0928\u094B\u090F\u0921\u093E
Number=9988998899

Output :

When the execution process will be completed successfully an output will be displayed on your browser as :





<<Previous <<   || Index ||   >>Next >>




JSTL timeZone & setTimeZone fmt Tag Example <fmt:timeZone> <fmt:setTimeZone>

<fmt:timeZone> tag is used to specify the time zone. It's scope is limited to its body, it parses the actions that are nested into its body.

The <fmt:timeZone> tag is used to specify the time zone information for any date formatting in its body. This tag is different from <fmt:setTimeZone> in that, <fmt:setTimeZone> is used to set the default time zone. However, the <fmt:timeZone> tag sets the time zone for the tags within its body. Rest of the JSP page uses the time zone set by the <fmt:setTimeZone> or the default time zone.

Syntax-
<fmt:timeZone value="<string>"/>

Attributes of <fmt:timeZone> tag:

value : This is a required attribute that specifies the name of a time zone/time zone IDs supported by java or an instance of the java.util.TimeZone.

The following JSP code displays the current date using the default time zone and displays current date using the GMT-8 time zone. The GMT-8 time zone is set using the <fmt:timeZone> tag. Notice that we are displaying the date within the body of the <fmt:timeZone> tag.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
  "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>&lt;fmt:timeZone&gt; Demo</title>
  </head>
  <body>
    <h1>&lt;fmt:timeZone&gt; Demo</h1>
    <c:set var="today" value="<%=new java.util.Date()%>" />
    <c:set var="timeZone" value="GMT-8"/>
    Date in the current time zone:
    <strong><fmt:formatDate value="${today}" type="both" /></strong>
    <br/>
    Date in the GMT-8 time zone (nested in &lt;fmt:timeZone&gt; tag):
    <fmt:timeZone value="${timeZone}">
    <strong>
          <fmt:formatDate value="${today}" timeZone="${timeZone}" type="both" />
        </strong>
    </fmt:timeZone>
  </body>
</html>

Output--


JSTL fmt Tag <fmt:setTimeZone> Example-

The <fmt:setTimeZone> is used to set the required time zone value. We can also copy the time zone object into the scoped variable for later use.

In JSP <fmt:setTimeZone> tag of JSTL fmt tag library is used to set a specified time zone or default time zone. The specified time zone may be either a specific name of time zone, supported by java or an instance of the TimeZone class of Java's utility package and the name or an instance can be passed into the required attribute named "value" of this tag.

Attributes of <fmt:setTimeZone> tag

value : This is a required attribute that specifies the name of a time zone/time zone IDs supported by java or an instance of the java.util.TimeZone.
var : This is an optional attribute that defines the name of the scoped variable kept the time zone of java.util.TimeZone type.
scope : This is an optional attribute that may be used for specifying the scope of the attribute 'var'.

Syntax-

<fmt:setTimeZone value="<string>" var="<string>" scope="<string>"/>
 

The following JSP code displays the current date using the default time zone and assigns the time zone to the GMT-8 using the <fmt:setTimeZone> tag. Also displays the date using the newly set time zone.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
  "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>&lt;fmt:setTimeZone&gt; Demo</title>
  </head>
  <body>
    <h1>&lt;fmt:setTimeZone&gt; Demo</h1>
    <c:set var="today" value="<%=new java.util.Date()%>" />
    <p>Date in the current time zone: 
    <strong>
      <fmt:formatDate value="${today}" type="both" timeStyle="long" dateStyle="long" />
    </strong></p>
    <fmt:setTimeZone value="GMT-8" />
    <p>Date in the GMT-8 time zone: 
    <strong>
      <fmt:formatDate value="${today}" type="both" timeStyle="long" dateStyle="long" />
    </strong></p>
  </body>
</html>

Output-





<<Previous <<   || Index ||   >>Next >>




JSTL fmt Tag setBundle Example <fmt:setBundle>

The <fmt:setBundle> tag is used to load a resource bundle and stores it in the named scoped variable or the bundle configuration variable.

<fmt:setBundle> tag in JSTL is used in a JSP page to set the resource bundle. A resource bundle is loaded by this tag and is stored into the named scoped variable or the bundle configuration variable.

Attributes of <fmt:setBundle>
  • basename : This is a required attribute used for specifying the base name of resource bundle . Basename is a resource name, follows the same component separator dot (.) as the package uses for specifying the fully qualified class name. It does not uses the any type of suffixes such as .properties, .class etc.
  • var : This is an optional attribute used for specifying the name of the exported base name to a variable.
  • scope : This is an optional attribute is used for specifying the scope of the variable.

Example-
An example is being given here will demonstrate you how to use the <fmt:setBundle> tag. In this example I have created a Properties file named myapp.properties that contains the key-value pair. Value of key are the English characters. Then created a JSP page named index.jsp into which I have set the locale using the <fmt:setLocale> tag. And then uses the <fmt:setBundle> tag to load the bundle resource from the resource variable. So as an output you will see the values written in English language.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>JSTL fmt:setBundle Tag</title>
</head>
<body>
<fmt:setBundle basename="myapp" var="lang"/>
<fmt:setLocale value="en"/>
<fmt:message key="Name" bundle="${lang}"/><br/>
<fmt:message key="Address" bundle="${lang}"/><br/>
<fmt:message key="Number" bundle="${lang}"/><br/>
</body>
</html>

myapp.properties
Name=Dinesh
Address=Noida
Number=9988998899

Output :

When the execution process will be completed successfully an output will be displayed on your eclipse browser as :





<<Previous <<   || Index ||   >>Next >>




JSTL Set Locale Example <fmt:setLocale>

In this tutorial you will learn about how to use the JSTL fmt tag setLocale in JSP.

JSTL Set Locale Tag is used to change the locale configuration. SetLocal tag takes ISO Language Code and ISO Country Code as a value. By default it is set to en_US.

setLocale tag sets the specified locale provided in its attribute 'value'. This tag keeps the specified locale in the configuration variable of locale.

Attributes of <fmt:setLocale>:
  • value : This is a required attribute and used for specifying a locale. To specify a locale code it must have made from the two-letter (lower case) language code (according to ISO-639) and/or the two-letter (upper-case) of country code (according to the ISO-3166). And if both the language and country code are used for specifying the locale the locale code must be separated by either hyphen (-) or underscore (_).
  • variant : This attribute is used for specifying the browser or vendor specific variant.
  • scope : This attribute specifies the scope of locale configuration variable.
Example :
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>JSTL fmt:bundle Tag</title>
</head>
<body>
<!-- Setting Locale to US -->
    <fmt:setLocale value="en_US"/>
    <fmt:formatNumber value="0.452" type="CURRENCY" minFractionDigits="3"></fmt:formatNumber>
    <br/>
    <!-- Setting Locale to UK -->
    <fmt:setLocale value="en_GB"/>
    <fmt:formatNumber value="0.452" type="CURRENCY" minFractionDigits="3"></fmt:formatNumber>
  <br/>
  <!-- Setting Locale to India -->
    <fmt:setLocale value="en_IN"/>
    <fmt:formatNumber value="0.452" type="CURRENCY" minFractionDigits="3"></fmt:formatNumber>
<br/>
<fmt:setLocale value="en"/>
<fmt:bundle basename="myapp">
<fmt:message key="Name"/><br/>
<fmt:message key="Address"/><br/>
<fmt:message key="Number"/><br/>
</fmt:bundle>
</body>
</html>



As you can see above, currency symbols is displayed based on setting of locale variable.



<<Previous <<   || Index ||   >>Next >>








JSTL bundle tag <fmt:bundle>

In this tutorial you will learn about the JSTL <fmt:bundle> tag.

<fmt:bundle> tag is used to avail the resource for using the formats. A resource bundle is loaded by this tag which will be used by its tag body.

Attributes of <fmt:bundle>
  • basename : This is a required attribute used for specifying the resource bundle base name. Basename is a resource name, follows the same component separator dot (.) as the package uses for specifying the fully qualified class name. It does not uses the any type of suffixes such as .properties, .class etc.
  • prefix : This is an optional attribute that may be used for adding to the beginning to the value of the key of <fmt:message> action. for example <fmt:message key="user.name"/>. Here user is a prefix.
Example :
An example is being given here will demonstrate you how to use the <fmt:bundle> tag. In this example I have created a Properties file named myapp.properties that contains the key-value pair. Value of key are the English characters. Then created a JSP page named index.jsp into which I have set the locale using the <fmt:setLocale> tag. And then uses the <fmt:bundle> tag to load the bundle resource from the resource variable. So as an output you will see the values written in English language.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>JSTL fmt:bundle Tag</title>
</head>
<body>
<fmt:setLocale value="en"/>
<fmt:bundle basename="myapp">
<fmt:message key="Name"/><br/>
<fmt:message key="Address"/><br/>
<fmt:message key="Number"/><br/>
</fmt:bundle>
</body>
</html>

myapp.properties
Name=Dinesh
Address=Noida
Number=9988998899

Output :

When the execution process will be completed successfully an output will be displayed on your eclipse browser as :




<<Previous <<   || Index ||   >>Next >>








JSTL ParseDate & FormatDate Example <fmt:parseDate> <fmt:formatDate>

The <fmt:formatDate> tag is used to format dates in a variety of ways. This tag is used to format date and time according to the user supplied style and format.

Attributes of the tag <fmt:formatDate>

value supplied date and time to be formatted.
type specifies that time or date or both date and time to be formatted of given date/time. 
dateStyle predefined styles to represent date. For example- default, short, long, full etc
timeStyle  predefined styles to represent time. For example- default, short, long, full etc
pattern provided by user in what pattern user want to format. For example: dd-mm-yyyy
timeZone in which time zone user want to represent date/time.
var var is a variable that is used to store created data source.
Scope Define the scope for declared variable like page or request or session or application.

Example:

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

<html>
<head>
  <title>JSTL fmt:dateNumber Tag</title>
</head>
<body>
<h3>Number Format:</h3>
<c:set var="date" value="<%=new java.util.Date()%>" />

<table bgcolor="#D8D8D8" border="1" width="70%">
<tr>
<td width="100%" colspan="2" bgcolor="#1C1C1C">
<p align="center"><b> <font color="#D8D8D8" size="4">Formatting: 
<fmt:formatDate value="${date}" type="both" timeStyle="long" 
dateStyle="long" /> 
</font>
</b></p>
</td>
</tr>
<tr>
<td width="51%">Attribute : type="date"</td>
<td width="49%"><fmt:formatDate type="date" value="${date}" /></td>
</tr>
<tr>
<td width="51%">Attribute : type="time"</td>
<td width="49%"><fmt:formatDate type="time" value="${date}" /></td>
</tr>
<tr>
<td width="51%">Attribute : type="both"</td>
<td width="49%"><fmt:formatDate type="both" value="${date}" /></td>
</tr>
<tr>
<td width="51%">Attribute : type="both" dateStyle="default"
timeStyle="default"</td>
<td width="49%"><fmt:formatDate type="both" dateStyle="default"
timeStyle="default" value="${date}" /></td>
</tr>
<tr>
<td width="51%">Attribute : type="short" dateStyle="default"
timeStyle="short"</td>
<td width="49%"><fmt:formatDate type="both" dateStyle="short"
timeStyle="short" value="${date}" /></td>
</tr>
<tr>
<td width="51%">Attribute : type="both" dateStyle="medium"
timeStyle="medium"</td>
<td width="49%"><fmt:formatDate type="both" dateStyle="medium"
timeStyle="medium" value="${date}" /></td>
</tr>
<tr>
<td width="51%">Attribute : type="both" dateStyle="long"
timeStyle="long"</td>
<td width="49%"><fmt:formatDate type="both" dateStyle="long"
timeStyle="long" value="${date}" /></td>
</tr>
<tr>
<td width="51%">Attribute : type="both" dateStyle="full"
timeStyle="full"</td>
<td width="49%"><fmt:formatDate type="both" dateStyle="full"
timeStyle="full" value="${date}" /></td>
</tr>
<tr>
<td width="51%">Attribute : pattern="yyyy-MM-dd"</td>
<td width="49%"><fmt:formatDate pattern="yyyy-MM-dd" value="${date}" />
</td>
</tr>
<tr>
<td width="51%">Attribute : pattern="yyyy-MM-dd hh:mm:ss"</td>
<td width="49%"><fmt:formatDate pattern="yyyy-MM-dd hh:mm:ss"
value="${date}" /></td>
</tr>
</table>
</body>
</html>

This would produce following result:
JSTL ParseDate

<fmt:parseDate> Tag-
The <fmt:parseDate> tag is used to parse dates.

Example-

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

<html>
<head>
  <title>JSTL fmt:parseDate Tag</title>
</head>
<body>
<h3>Date Parsing:</h3>
<c:set var="now" value="20-10-2013" />

<fmt:parseDate value="${now}" var="parsedEmpDate" 
                              pattern="dd-MM-yyyy" />
<p>Parsed Date: <c:out value="${parsedEmpDate}" /></p>

</body>
</html>


This would produce following result:

JSTL ParseDate & FormatDate Example



<<Previous <<   || Index ||   >>Next >>








JSTL Parse Number Example <fmt:parseNumber>

JSTL Parse Number tag is used to parse the numbers, percentage or currency.

JSTL Parse Number Example:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

<html>
<head>
 <title>JSTL Parse Number Example</title>
</head>
<body>
    <!-- Setting Locale to US -->
    <fmt:parseNumber value="156.1432" var="test" integerOnly="TRUE" type="NUMBER"></fmt:parseNumber>
    <c:out value="${test}"></c:out>
</body>
</html>


As you can see above, JSTL Parse Number Tag is used to parse the number. Parse Number Tag in JSTL has following attributes.

1. value : Value attribute provides the number to be parsed.

2. type: Type attribute specifies the type of string to be parsed. It can be NUMBER, PERCENT or CURRENCY.

3. var : Var attribute provides the variable that is used to store the parsed number. This variable can be used later in the jsp.

4. intgerOnly: integerOnly attribute allows to store number in Integer format only. Default value is false.

5. pattern: Pattern attribute provides custom formatting pattern that determines how the string in the value attribute is to be parsed.

6. scope: Scope attribute provides the scope of variable.




<<Previous <<   || Index ||   >>Next >>








JSTL formatNumber Tag <fmt:formatNumber>

JSTL formatNumber tag is used to change the format of numbers or currency.

JSTL formatNumber Example:

To display the numbers on JSP in proper format, you can use the <fmt:formatNumber> tag like this:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

<html>
<head>
  <title>JSTL fmt:formatNumber Tag</title>
</head>
<body>
<h3>Number Format:</h3>
<c:set var="balance" value="120000.2309" />
<p>Formatted Number (1): <fmt:formatNumber value="${balance}" 
            type="currency"/></p>
<p>Formatted Number (2): <fmt:formatNumber type="number" 
            maxIntegerDigits="3" value="${balance}" /></p>
<p>Formatted Number (3): <fmt:formatNumber type="number" 
            maxFractionDigits="3" value="${balance}" /></p>
<p>Formatted Number (4): <fmt:formatNumber type="number" 
            groupingUsed="false" value="${balance}" /></p>
<p>Formatted Number (5): <fmt:formatNumber type="percent" 
            maxIntegerDigits="3" value="${balance}" /></p>
<p>Formatted Number (6): <fmt:formatNumber type="percent" 
            minFractionDigits="10" value="${balance}" /></p>
<p>Formatted Number (7): <fmt:formatNumber type="percent" 
            maxIntegerDigits="3" value="${balance}" /></p>
<p>Formatted Number (8): <fmt:formatNumber type="number" 
            pattern="###.###E0" value="${balance}" /></p>
<p>Currency in USA :
<fmt:setLocale value="en_US"/>
<fmt:formatNumber value="${balance}" type="currency"/></p>
</body>
</html>

As you can see above, in the JSTL formatNumber tag, var attribute is used to define the variable than needs to be formatted. Proper formatting needs help of other attributes from formatNumber tag.


Attributes of <fmt:formatNumber> tag are:

      1. var:This attribute provides numeric value to be formatted.

       2. type: This attribute specifies whether the value is to be formatted as number, currency, or percentage.

       3. maxFractionDigits: This attribute provides maximum number of digits in the fractional portion of the formatted output.

       4.  minFractionDigits : This attribute provides Minimum number of digits in the fractional portion of the formatted output.

       5. pattern: This attribute provides custom formatting pattern.

       6. value: This attribute provides Numeric value to be formatted.

      7. scope: This attribute provides scope of var.

       8. currencyCode: This attribute provides ISO 4217 currency code. Applied only when formatting currencies (i.e. if type is equal to "currency"). Ignored otherwise.

      9. currencySymbol: This attribute provides Currency symbol. Applied only when formatting currencies (i.e. if type is equal to "currency"); ignored otherwise.

       10. groupingUsed: This attribute specifies whether the formatted output will contain any grouping separators..

      11. maxIntegerDigits: This attribute provides Maximum number of digits in the integer portion of the formatted output.

       12. minIntegerDigits: This attribute provides Minimum number of digits in the integer portion of the formatted output.





<<Previous <<   || Index ||   >>Next >>







JSTL Redirect Tag <c:redirect>

JSTL Redirect tag is used to redirect the request to another resource. The <c:redirect> tag redirects the browser to an alternate URL by providing automatically URL rewriting, it supports context-relative URLs, and it supports the <c:param> tag.

JSTL <c:Redirect> Tag Example:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>JSTL Redirect Tag Example</title>
</head>
<body>
  <c:redirect url="http://www.dineshonjava.com"></c:redirect>
</body>
</html>

As you can see above, JSTL Redirect tag is being used to redirect the request to another resource.

Attributes of JSTL Redirect tag are:

1. url: This attribute provides the URL of the resource to redirect to.

2. context: This attribute provides Name of the context when redirecting to a relative URL resource

that belongs to a foreign context.



<<Previous <<   || Index ||   >>Next >>







JSTL url Tag <c:url>

JSTL URL tag is used to format and save url in a variable to use it at later stage. The <c:url> tag formats a URL into a string and stores it into a variable. This tag automatically performs URL rewriting when necessary. The var attribute specifies the variable that will contain the formatted URL.

The JSTL url tag is just an alternative method of writing the call to the response.encodeURL() method. The only real advantage the url tag provides is proper URL encoding, including any parameters specified by children param tag.

JSTL <C:URL> Tag Example:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>JSTL URL Tag Example</title>
</head>
<body>
  <c:url value="http://www.dineshonjava.com" var="tutorialLink">
    <c:param name="author" value="Dinesh"></c:param>
  </c:url>
  <c:import url="${tutorialLink}"></c:import>
</body>
</html>

As you can see above, <c:url> tag is being used to store the value of url in a variable tutorialLink.

In <c:import> tag, the url attribute will have following value.

http://www.dineshonjava.com?author=Dinesh

Attributes of <c:url> tag are:

      1. value:This attribute provides URL to be processed.

       2. var: This attribute provides name of the exported scoped variable for the processed url. The type of the scoped variable is String.

       3. context: This attribute provides name of the context when specifying a relative URL resource that belongs to a foreign context.

       4. scope: This attribute provides the scope for var.



<<Previous <<   || Index ||   >>Next >>







JSTL param Tag <c:param>

JSTL Param Tag is used to pass the parameters to the url. The <c:param> tag allows proper URL request parameter to be specified with URL and it does any necessary URL encoding required.

Within a <c:param> tag, the name attribute indicates the parameter name, and the value attribute indicates the parameter value.

JSTL <c:param> Tag Example:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>c:forTokens Tag Example</title>
</head>
<body>
<c:url value="/footer.jsp" var="myURL">
   <c:param name="employeeId" value="1234"/>
   <c:param name="employeeName" value="Dinesh"/>
</c:url>
<c:import url="${myURL}"/>
</body>
</html>

As you can see above, JSTL Param Tag is being used within <c:url> tag. In the <c:param> tag, name attribute is used to define the parameter name and value attribute is used to set the value of the parameter.


Attributes of <c:forTokens> tag are:

Required Attributes:

      1. name:This attribute provides name of the query string parameter.

Optional Attributes:

       1. value: This attribute provides value of the parameter.





<<Previous <<   || Index ||   >>Next >>







JSTL forTokens Tag <forTokens>

JSTL forTokens tag is used to iterate over the tokens separated by delimiters. JSTL forTokens tag is another tag in core JSTL library to support Iteration or looping. It effectively complements, more useful <c:forEach> tag, by allowing you to iterate over comma separated or any delimited String. You can use this tag to split string in JSP and can operate on them individually. forTokens tag has similar attribute like forEach JSTL tag except one more attribute called delims, which specifies delimiter.

JSTL <c:forTokens> tag Example:

To display the names on JSP, you can use the <forTokens> tag like:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title><c:forTokens> Tag Example</title>
</head>
<body>
<c:forTokens items="Dinesh,Anamika,Sweety" delims="," var="name">
   <c:out value="${name}"/><p>
</c:forTokens>
</body>
</html>
As you can see above, in the JSTL forTokens tag, items attribute is used to define the tokens. It will iterate over tokens separated by delimiter. In each iteration, it will get a token defined with attribute var. status attribute keeps track of iteration.

Withing starting and ending tag of  forTokens, you can display or apply other logic to each token.

Attributes of <c:forTokens> tag are:


Required Attributes:

      1. items:This attribute provides string of tokens to iterate over..

       2. delims: This attribute provides the set of delimiters. The characters that separate the tokens in the string.

Optional Attributes:

       1. var: This attribute provides name of the exported scoped variable for the current item of the iteration. This scoped variable has nested visiblity. Its type depends on the object of the underlying collection.

       2. varStatus: This attribute provides name of the exported scoped variable for the status of the iteration. Object exported is of type javax.servlet.jsp.jstl.core.LoopTagStatus. This scoped variable has nested visibility.

       3. begin: If items specified: Iteration begins at the item located at the specified index. First item of the collection has index 0. If items not specified: Iteration begins with index set at the value specified.

      4. end: If items specified: Iteration ends at the item located at the specified index (inclusive). If items not specified: Iteration ends when index reaches the value specified.

     5. step: Iteration will only process every step items of the collection, starting with the first one.



<<Previous <<   || Index ||   >>Next >>







Spring Security Tutorial- Learn Step to Secure Web

Spring Security Tutorial

In this spring security tutorial we will discuss about some of the security tips about the Spring Framework. Spring Security is a powerful and highly customization authentication and access-control framework to secure Spring-based Java web application.
Introduction-
Spring Security is a customizable authentication and access service framework for server side Java-based enterprise software applications. The Spring security OAuth provides a method for making authenticated HTTP requests using a token - an identifier used to denote an access grant with specific scope, duration, and other attributes. Tokens are issued to third-party clients by an authorization server with the approval of the resource owner. Instead of sharing their credentials with the client, resource owners grant access by authenticating directly with the authorization server which in turn issues a token to the client. The client uses the token (and optional secret) to authenticate with the resource server and gain access.

Spring Security Flow


As you probably know two major areas of application security are authentication and authorization (or access-control). These are the two main areas that Spring Security targets. 
1. Authentication is the process of establishing a principal is who they claim to be (a principal generally means a user, device or some other system which can perform an action in your application).  

2. “Authorization refers to the process of deciding whether a principal is allowed to perform an action within your application. To arrive at the point where an authorization decision is needed, the identity of the principal has already been established by the authentication process. These concepts are common, and not at all specific to Spring Security.  

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

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

Sometimes the mere process of authentication isn't enough. Sometimes you need to also differentiate security based on the way a principal is interacting with your application. For example, you might want to ensure requests only arrive over HTTPS, in order to protect passwords from eavesdropping or end users from man-in-the-middle attacks. This is especially helpful to protect password recovery processes from brute force attacks, or simply to make it harder for people to duplicate your application's key content. To help you achieve these goals, Spring Security fully supports automatic "channel security", together with JCaptcha integration for human user detection.
Irrespective of how authentication was undertaken, Spring Security provides a deep set of authorization capabilities. There are three main areas of interest in respect of authorization, these being authorizing web requests, authorizing whether methods can be invoked, and authorizing access to individual domain object instances. To help you understand the differences, consider the authorization capabilities found in the Servlet Specification web pattern security, EJB Container Managed Security and file system security respectively. Spring Security provides deep capabilities in all of these important areas, which we'll explore later in this reference guide.

Following are the some of the important facilities that Spring Security Framework provides to it’s users:

  • User authentication and authorization.
  • Role based authorization control.
  • Easy to configure with database based authentication and authorization.
  • Encrypted password.
  • Form authentication.
  • File bases user authentication and authorization.
History:
  1. The project was started in late 2003 as 'Acegi Security'by Ben Alex
  2. Subsequently, Acegi was incorporated into the Spring portfolio as Spring Security, an official Spring sub-project.
  3. The first public release under the new name was Spring Security 2.0.0 in April 2008, with commercial support and training available from SpringSource

Acegi Security-
Acegi is the most used web project security tools in respect of Java web development. Acegi is a security framework for authentication, authorization and role based authorization of the users. Spring Security is an implementation of Acegi referral API. Spring Security Framework provides a lot of facilities to take care of the java web enterprise security management. Its really great security framework that work with Spring IoC or DI to inject the dependencies and securing the java web application.

Security Namespace Configuration-
A namespace element can be used simply to allow a more concise way of configuring an individual bean or, more powerfully, to define an alternative configuration syntax which more closely matches the problem domain and hides the underlying complexity from the user.

To start using the security namespace in your application context, you first need to make sure that the spring-security-config jar is on your classpath. Then all you need to do is add the schema declaration to your application context file:
<beans xmlns:security="http://www.springframework.org/schema/security" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemalocation="http://www.springframework.org/schema/beans
          http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
          http://www.springframework.org/schema/security
          http://www.springframework.org/schema/security/spring-security-3.0.3.xsd">
    ...
</beans>
Getting Started with Security Namespace Configuration-
In this section, we'll look at how you can build up a namespace configuration to use some of the main features of the framework. Let's assume you initially want to get up and running as quickly as possible and add authentication support and access control to an existing web application, with a few test logins. Then we'll look at how to change over to authenticating against a database or other security repository. In later sections we'll introduce more advanced namespace configuration options.

1 web.xml Configuration-
<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>

This provides a hook into the Spring Security web infrastructure. DelegatingFilterProxy is a Spring Framework class which delegates to a filter implementation which is defined as a Spring bean in your application context. In this case, the bean is named "springSecurityFilterChain", which is an internal infrastructure bean created by the namespace to handle web security. Note that you should not use this bean name yourself. Once you've added this to your web.xml, you're ready to start editing your application context file. Web security services are configured using the <http> element.

2. A Minimal <http> Configuration-
<http auto-config="true"><intercept-url pattern="/**" access="ROLE_USER" /></http>
  
Which says that we want all URLs within our application to be secured, requiring the role ROLE_USER to access them. The <http> element is the parent for all web-related namespace functionality. The <intercept-url> element defines a pattern which is matched against the URLs of incoming requests using an ant path style syntax. The access attribute defines the access requirements for requests matching the given pattern. With the default configuration, this is typically a comma-separated list of roles, one of which a user must have to be allowed to make the request. The prefix "ROLE_" is a marker which indicates that a simple comparison with the user's authorities should be made. In other words, a normal role-based check should be used. Access-control in Spring Security is not limited to the use of simple roles (hence the use of the prefix to differentiate between different types of security attributes). We'll see later how the interpretation can vary.

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

Element : httpContainer element for HTTP security configuration. Multiple elements can now be defined, each with a specific  pattern to which the enclosed security configuration applies. A pattern can also be configured to bypass Spring  Security's filters completely by setting the "secured" attribute to "false".

Content Model :
(intercept-url | access-denied-handler | form-login | openid-login | x509 | jee | http-basic |  logout | session-management | remember-me | anonymous | port-mappings | custom-filter | request-cache |  expression-handler)*

auto-config="true"
Automatically registers a login form, BASIC authentication,  anonymous authentication, logout services, remember-me and  servlet-api-integration. If set to "true", all of these capabilities are  added (although you can still customize the configuration of each  by providing the respective element). If unspecified, defaults to  "false".

NOTE:
You can use multiple <intercept-url> elements to define different access requirements for different sets of URLs, but they will be evaluated in the order listed and the first match will be used. So you must put the most specific matches at the top. You can also add a method attribute to limit the match to a particular HTTP method (GET, POST, PUT etc.). If a request matches multiple patterns, the method-specific match will take precedence regardless of ordering.

<authentication-manager>
    <authentication-provider>
      <user-service>
        <user authorities="ROLE_USER, ROLE_ADMIN" name="dinesh" password="dineshpassword">
        <user authorities="ROLE_USER" name="sweety" password="sweetypassword">
      </user></user></user-service>
    </authentication-provider>
  </authentication-manager>

The configuration above defines two users, their passwords and their roles within the application (which will be used for access control). It is also possible to load user information from a standard properties file using the properties attribute on user-service. See the section on in-memory authentication for more details on the file format. Using the <authentication-provider> element means that the user information will be used by the authentication manager to process authentication requests. You can have multiple <authentication-provider> elements to define different authentication sources and each will be consulted in turn.



References
1. http://www.codeproject.com/Articles/253901/Getting-Started-Spring-Security
2. Spring Security
3. Spring Security documentation