Wednesday, June 24, 2015

mongodb find queries


Mongodb Find queries


db.card.find();======it will display all documents
db.card.findOne();=====it will disply first document
db.card.find({title:"Chicken monchow soup"});=specific document with all fields





db.user_profile.find({"mobileNo":9988776655,"countryCode":"91"})==one document

db.user_profile.find({"mobileNo":9988776655,"countryCode":"91","mobileNo":8112300662,"countryCode":"91"})===two documnets


db.user_profile.find({mobileNo:{$in:[9988776655,8112300662]}})===specific document based on matching values



 db.user_profile.find(
{$or:[
        {"mobileNo": 9988776655, "countryCode":"91"},
        {"mobileNo": 8112300662,"countryCode":"1"} ,===========based on country code
    ]})

List of Regular Expressions Symbols



 Character Classes

Character classes are used to define the content of the pattern. E.g. what should the pattern look for?
.   Dot, any character (may or may not match line terminators, read on)

\d   A digit: [0-9]
\D   A non-digit: [^0-9]
\s   A whitespace character: [ \t\n\x0B\f\r]
\S   A non-whitespace character: [^\s]
\w   A word character: [a-zA-Z_0-9]
\W   A non-word character: [^\w]

However; notice that in Java, you will need to “double escape” these backslashes.
String pattern = "\\d \\D \\W \\w \\S \\s";

Quantifiers

Quantifiers can be used to specify the number or length that part of a pattern should match or repeat. A quantifier will bind to the expression group to its immediate left.

*      Match 0 or more times
+      Match 1 or more times
?      Match 1 or 0 times
{n}    Match exactly n times
{n,}   Match at least n times
{n,m}  Match at least n but not more than m times

Meta-characters

Meta-characters are used to group, divide, and perform special operations in patterns.

\   Escape the next meta-character (it becomes a normal/literal character)
^   Match the beginning of the line
.   Match any character (except newline)
$   Match the end of the line (or before newline at the end)
|   Alternation (‘or’ statement)
()   Grouping
[]   Custom character class

Monday, June 22, 2015

Reading properties from property util classes


Ex:

application.properties

template_card_image_path=D:/smilesurance-plain.png
hooper_code=234
service_id=01
business_code=SMILIN
images_path=D:/Smiline/cards/
corporate_name=Hackett Group
card_validity=Valid till:

PropertyUtils .java

package com.hps.platform.utils;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hps.platform.utility.service.MessageService;

public class PropertyUtils {

private static final Logger LOGGER = LoggerFactory.getLogger(MessageService.class);
private static PropertyUtils propertyUtilsInstance;
private static Properties properties;

static{
propertyUtilsInstance = new PropertyUtils();
}

private PropertyUtils() {
if (properties == null) {
try {
properties = loadProperties();
} catch (IOException e) {
LOGGER.error("Threw a BadException, full stack trace follows:",e);
e.printStackTrace();
}
}
}

private Properties loadProperties() throws IOException {
Properties properties = new Properties();
InputStream inputStream = getClass().getClassLoader().getResourceAsStream("application.properties");
if (inputStream == null) {
throw new FileNotFoundException("not loaded!");
}
properties.load(inputStream);
return properties;
}

public static Properties getProperties() {
return properties;
}

}


we can read the properties in the following way

public static String image_template_path PropertyUtils.getProperties().getProperty("template_card_image_path");
public static String corporateName = PropertyUtils.getProperties().getProperty("corporate_name");
public static String saved_image_path =PropertyUtils.getProperties().getProperty("images_path");


Saturday, June 20, 2015

Retrieving multiple records using spring jdbc+mysql

(type1 without passing any parameters to query and getting all rows)

String SELECT_NAME_CARDID_EXPIRY=""select *from user_enrollment_data";

DAO
public List<FailedRecords> getAllRecords();


DaoImpl

public List<FailedRecords> getAllRecords() {
return mysqlJdbcTemplate.query
(SELECT_NAME_CARDID_EXPIRY, 
new NullRecordRowMapper());  

}

NullRecordRowMapper

public class NullRecordRowMapper implements RowMapper<FailedRecords> {

@Override
public FailedRecords mapRow(ResultSet resultSet, int line)
throws SQLException {
NullRecordsExtractor userExtractor = new NullRecordsExtractor();
return userExtractor.extractData(resultSet);
}
}

NullRecordsExtractor 

Here  FailedRecords  pojo it contains database fileds

public class NullRecordsExtractor  implements ResultSetExtractor<FailedRecords>{
public FailedRecords extractData(ResultSet resultSet) throws SQLException,  
DataAccessException {  

FailedRecords failedRecords = new FailedRecords();  
failedRecords.setId(resultSet.getString(1));
failedRecords.setBusinessCode(resultSet.getString(2));
failedRecords.setCsvData(resultSet.getString(3));
failedRecords.setCardId(resultSet.getString(4));
failedRecords.setCardExpiry(resultSet.getString(5));
failedRecords.setMailStatus(resultSet.getString(6));

failedRecords.setSmsStatus(resultSet.getString(7));
failedRecords.setMobileNo(resultSet.getString(8));
failedRecords.setCreatedDate(resultSet.getDate(9));

/*String firstName=csvData.split(",")[1];
String lastName=csvData.split(",")[2];
System.out.println(firstName+" "+lastName);*/
return failedRecords;  
}  

}  


type2(passing single paramter and getting single row)

String  SELECT_TOTAL_FAMILY=" public final String SELECT_TOTAL_FAMILY="select *from user_enrollment_data where mail_status is null and mobile_no=?";


DAO

public List<FailedRecords> getFamilyMembers(String mobileNo);

DaoImpl

public List<FailedRecords> getFamilyMembers(String mobileNo) {  
return mysqlJdbcTemplate.query
(SELECT_TOTAL_FAMILY,
new Object[] { mobileNo }, 
new NullRecordRowMapper());  

}

same  NullRecordRowMapper and NullRecordsExtractor 










Tuesday, June 16, 2015

Jasper reports example with java beans without database


Use jasper reports library

<pre name="code" class="java">

DataBean.java

public class DataBean {
private String name;
private String occupation;
private String place;
private String country;
//setters and getters
}

DataBeanMaker.java

package com.report.javabean;
import java.util.ArrayList;
public class DataBeanMaker {

public ArrayList<DataBean> getDataBeanList() {

ArrayList<DataBean> dataBeanList = new ArrayList<DataBean>();

dataBeanList.add(produce("umar farooq", "Manager", "karnool", "india"));
dataBeanList.add(produce("mohan", "SSE", "vizag", "india"));
dataBeanList.add(produce("Srikanth tirumala", "CEO", "hyderabad", "India"));
dataBeanList.add(produce("ruby", "Co-Founder", "karnool", "India"));
dataBeanList.add(produce("subbu", "SSE" , "nelure", "india"));
dataBeanList.add(produce("mustak", "SE" , "karnool", "india"));
dataBeanList.add(produce("satya", "SE", "nalgonda", "india"));
dataBeanList.add(produce("kiran", "SSE" , "east", "india"));
dataBeanList.add(produce("sujatha", "HR" , "hyderabad", "india"));

return dataBeanList;
}

private DataBean produce(String name, String occupation, String place, String country) {

DataBean dataBean = new DataBean();
dataBean.setName(name);
dataBean.setOccupation(occupation);
dataBean.setPlace(place);
dataBean.setCountry(country);

return dataBean;
}



}

Repoter.java

package com.report.javabean;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRXmlLoader;
public class Reporter {

@SuppressWarnings("unchecked")
public static void main(String[] args) throws Exception {
InputStream inputStream = new FileInputStream ("reports/test_jasper.xml");

DataBeanMaker dataBeanMaker = new DataBeanMaker();
ArrayList<DataBean> dataBeanList = dataBeanMaker.getDataBeanList();

JRBeanCollectionDataSource beanColDataSource = new JRBeanCollectionDataSource(dataBeanList);

Map parameters = new HashMap();

JasperDesign jasperDesign = JRXmlLoader.load(inputStream);
JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, beanColDataSource);
JasperExportManager.exportReportToPdfFile(jasperPrint, "D:/demo.pdf");
}
}

test_jasper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!-- Created with Jaspersoft Studio version 6.1.0.final using JasperReports Library version 6.1.0  -->
<!-- 2015-06-17T10:42:17 -->
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="scriptlet" pageWidth="595" pageHeight="842" columnWidth="535" leftMargin="30" rightMargin="30" topMargin="30" bottomMargin="30" whenResourceMissingType="Empty" uuid="4a933c9b-78d7-426f-8fd8-e27159b11caa">
<property name="com.jasperassistant.designer.Grid" value="false"/>
<property name="com.jasperassistant.designer.SnapToGrid" value="false"/>
<property name="com.jasperassistant.designer.GridWidth" value="12"/>
<property name="com.jasperassistant.designer.GridHeight" value="12"/>
<queryString>
<![CDATA[]]>
</queryString>
<field name="country" class="java.lang.String">
<fieldDescription><![CDATA[country]]></fieldDescription>
</field>
<field name="occupation" class="java.lang.String">
<fieldDescription><![CDATA[occupation]]></fieldDescription>
</field>
<field name="name" class="java.lang.String">
<fieldDescription><![CDATA[name]]></fieldDescription>
</field>
<field name="place" class="java.lang.String">
<fieldDescription><![CDATA[place]]></fieldDescription>
</field>
<group name="dummy">
<groupExpression><![CDATA["dummy"]]></groupExpression>
<groupHeader>
<band height="23">
<staticText>
<reportElement mode="Opaque" x="0" y="5" width="535" height="15" backcolor="#70A9A9" uuid="d6b37903-6581-4be2-acd8-a34e03d4a65f"/>
<box>
<bottomPen lineWidth="5.0" lineColor="#CCCCCC"/>
</box>
<text><![CDATA[]]></text>
</staticText>
<staticText>
<reportElement x="136" y="5" width="150" height="15" uuid="bc77d454-a4ad-4acd-a45c-7781a1cc9db3"/>
<textElement textAlignment="Center" verticalAlignment="Middle">
<font isBold="true"/>
</textElement>
<text><![CDATA[Occupation]]></text>
</staticText>
<staticText>
<reportElement x="286" y="5" width="128" height="15" uuid="9a0b1647-7c70-46d2-9904-b6c8ec2516bc"/>
<textElement textAlignment="Center" verticalAlignment="Middle"/>
<text><![CDATA[Place]]></text>
</staticText>
<staticText>
<reportElement x="414" y="5" width="121" height="15" uuid="1d3dc13e-6844-4551-87c4-a84942396de6"/>
<textElement textAlignment="Center" verticalAlignment="Middle">
<font isBold="true"/>
</textElement>
<text><![CDATA[Country]]></text>
</staticText>
<staticText>
<reportElement x="0" y="5" width="136" height="15" uuid="35ea54b3-46ba-4a00-b209-0f0caae22199"/>
<textElement textAlignment="Center" verticalAlignment="Middle">
<font isBold="true"/>
</textElement>
<text><![CDATA[Name]]></text>
</staticText>
</band>
</groupHeader>
</group>
<detail>
<band height="16">
<staticText>
<reportElement mode="Opaque" x="0" y="0" width="535" height="14" backcolor="#E5ECF9" uuid="2b45dbc9-215c-453e-b263-22419173a2a6"/>
<box>
<bottomPen lineWidth="0.25" lineColor="#CCCCCC"/>
</box>
<text><![CDATA[]]></text>
</staticText>
<textField>
<reportElement x="136" y="0" width="150" height="15" uuid="2321034b-fef7-4c07-9605-0a40e48a0080"/>
<textElement textAlignment="Center" verticalAlignment="Middle"/>
<textFieldExpression><![CDATA[$F{occupation}]]></textFieldExpression>
</textField>
<textField>
<reportElement x="286" y="0" width="128" height="15" uuid="472e0b06-bb32-458f-8073-a637449a060f"/>
<textElement textAlignment="Center" verticalAlignment="Middle"/>
<textFieldExpression><![CDATA[$F{place}]]></textFieldExpression>
</textField>
<textField>
<reportElement x="414" y="0" width="121" height="15" uuid="6de7ba67-0d5c-48bb-9817-6390fc7a9e13"/>
<textElement textAlignment="Center" verticalAlignment="Middle">
<font size="9"/>
</textElement>
<textFieldExpression><![CDATA[$F{country}]]></textFieldExpression>
</textField>
<textField>
<reportElement x="0" y="0" width="136" height="15" uuid="d592ad48-a319-4939-860f-733d28e312a2"/>
<textElement textAlignment="Center" verticalAlignment="Middle"/>
<textFieldExpression><![CDATA[$F{name}]]></textFieldExpression>
</textField>
</band>
</detail>

</jasperReport>

</pre>

Simple Jasper report example with jdbc



main class


package net.sf.dynamicreports.examples;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import net.sf.dynamicreports.jasper.builder.JasperReportBuilder;
import net.sf.dynamicreports.report.builder.DynamicReports;
import net.sf.dynamicreports.report.builder.column.Columns;
import net.sf.dynamicreports.report.builder.component.Components;
import net.sf.dynamicreports.report.builder.datatype.DataTypes;
import net.sf.dynamicreports.report.constant.HorizontalAlignment;
import net.sf.dynamicreports.report.exception.DRException;

/**
 * SQL
 *

CREATE TABLE `customers` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `first_name` varchar(50) DEFAULT NULL,
  `last_name` varchar(50) DEFAULT NULL,
  `date` date DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=latin1;

  INSERT INTO `test`.`customers` (`first_name`, `last_name`, `date`) VALUES ('Ricardo', 'Mariaca', CURRENT_DATE);
INSERT INTO `test`.`customers` (`first_name`, `last_name`, `date`) VALUES ('YONG', 'MOOK KIM', CURRENT_DATE);

 */
public class SimpleReportExample {

public static void main(String[] args) {
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root", "root");
} catch (SQLException e) {
e.printStackTrace();
return;
} catch (ClassNotFoundException e) {
e.printStackTrace();
return;
}

JasperReportBuilder report = DynamicReports.report();//a new report
report
 .columns(
  Columns.column("Customer Id", "id", DataTypes.integerType())
  .setHorizontalAlignment(HorizontalAlignment.LEFT),
  Columns.column("First Name", "first_name", DataTypes.stringType()),
  Columns.column("Last Name", "last_name", DataTypes.stringType()),
  Columns.column("Date", "date", DataTypes.dateType())
  .setHorizontalAlignment(HorizontalAlignment.LEFT)
  )
 .title(//title of the report
  Components.text("SimpleReportExample")
  .setHorizontalAlignment(HorizontalAlignment.CENTER))
 .pageFooter(Components.pageXofY())//show page number on the page footer
 .setDataSource("SELECT id, first_name, last_name, date FROM customers", connection);

try {
report.show();//show the report
report.toPdf(new FileOutputStream("D:/Text.pdf"));//export the report to a pdf file
} catch (DRException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}

Sunday, June 14, 2015

Running console application(main program) using Maven(pom.xml)


The following pom.xml is suitable to run main programs in java using maven

pom.xml

 <build>
<plugins>
<plugin>
<artifactId>maven-plugin-plugin</artifactId>
<version>2.3</version>
<configuration>
<goalPrefix>clean</goalPrefix>
<goalPrefix>install</goalPrefix>
<goalPrefix>run</goalPrefix>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<executions>
<execution>
<phase>test</phase>
<goals>
<goal>java</goal>
</goals>
</execution>
</executions>
<configuration>
<mainClass>com.email.TestApp</mainClass>
</configuration>
</plugin>

</plugins>
</build>
    

Unknown Lifecycle Phase Error in Maven Build


Problem

[ERROR] Unknown lifecycle phase "test1". You must specify a valid lifecycle phase or a goal

in the format <plugin-prefix>:<goal> or <plugin-group-id>:<plugin-artifact-id>[:<plugin-

version>]:<goal>. Available lifecycle phases are: validate, initialize, generate-sources,

process-sources, generate-resources, process-resources, compile, process-classes, generate-

test-sources, process-test-sources, generate-test-resources, process-test-resources, test-

compile, process-test-classes, test, prepare-packagepackage, pre-integration-test,

integration-test, post-integration-test, verify, install, deploy, pre-clean, clean, post-clean,

 pre-site, site, post-site, site-deploy. -> [Help 1]

If you look at the above error “Unknown lifecycle phase”, your build could not detect the pre-defined lifecycle phase used by Maven. Maven has the following phases:
  • validate – validate the project is correct and all necessary information is available
  • compile – compile the source code of the project
  • test – test the compiled source code using a suitable unit testing framework. These tests should not require the code be packaged or deployed
  • package – take the compiled code and package it in its distributable format, such as a JAR.
  • integration-test – process and deploy the package if necessary into an environment where integration tests can be run
  • verify – run any checks to verify the package is valid and meets quality criteria
  • install – install the package into the local repository, for use as a dependency in other projects locally
  • deploy – done in an integration or release environment, copies the final package to the remote repository for sharing with other developers and projects
    Solution is: package

Friday, June 12, 2015

Simple restful service using jersey+json format


Resource class


package com.hps.resources;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hps.model.HelloRequest;
import com.hps.model.HelloResponse;

@Path("/admin")
public class MessageResource {
@GET
@Path("{parameter}")
public Response responseMsg( @PathParam("parameter") String parameter,
@DefaultValue("Nothing to say") @QueryParam("value") String value) throws JsonProcessingException, UnknownHostException {
String output = "Hello from: " + parameter + " : " + value;
return Response.status(200).entity(output).build();
}
@POST
@Path("/action")
@Produces(MediaType.APPLICATION_JSON)
public Response produceJson(HelloRequest helloRequest) throws JsonProcessingException, UnknownHostException{
String output = "Hello from: " + helloRequest.getParameter() + " : " +helloRequest.getMessage();

HelloResponse reponse = new HelloResponse(output);
reponse.setStatus(Response.Status.CREATED.getStatusCode());
return Response.status(200).entity(reponse).build();
}


}

HelloRequest.java



@XmlRootElement
public class HelloRequest {
private String message;
private String parameter;
//getters and setter methods
}

HelloResponse.java

public class HelloResponse {
private String message;
private int status;
//getters and setters
}


MyApplication.java(this will produce the json response)


import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
import org.glassfish.jersey.filter.LoggingFilter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;

@ApplicationPath("/")
public class MyApplication extends Application {

@Override
public Set<Class<?>> getClasses() {
final Set<Class<?>> classes = new HashSet<Class<?>>();
classes.add(MessageResource.class);
return classes;
}
@Override
public Set<Object> getSingletons() {
final Set<Object> instances = new HashSet<Object>();
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
instances.add(new JacksonJsonProvider(mapper));
instances.add(new LoggingFilter());
return instances;
}
}

web.xml



<servlet>
        <servlet-name>rest</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
          <param-name>javax.ws.rs.Application</param-name>
          <param-value>com.hps.resources.MyApplication</param-value>
        </init-param>
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
        <load-on-startup>1</load-on-startup>
        <async-supported>true</async-supported>
    </servlet>







Inserting and Retrieving images in MongoDB without GridFs Library

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.UnknownHostException;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;

public class SaveImageApp {
public static void main(String[] args)
{
SaveImageApp o = new SaveImageApp();
o.withoutUsingGridFS();
}
public  void withoutUsingGridFS()
{
try {
Mongo mongo = new Mongo("localhost", 27017);
DB db = mongo.getDB("imagedb");
DBCollection collection = db.getCollection("dummyColl");

String filename = "C:/TEOProjectWorkspace/Mongodb/hoopertext.png";
String empname ="hooper";
insert(empname,filename,collection);
String destfilename = "C:/TEOProjectWorkspace/Mongodb/hoopertext.png";
retrieve(empname, destfilename, collection);

} catch (UnknownHostException e) {
e.printStackTrace();
} catch (MongoException e) {
e.printStackTrace();
}
}

public   void insert(String empname, String filename, DBCollection collection)
{
try
{
File imageFile = new File(filename);
FileInputStream f = new FileInputStream(imageFile);
byte b[] = new byte[f.available()];
f.read(b);

//    Binary data = new Binary(b);
BasicDBObject o = new BasicDBObject();
o.append("name",empname).append("photo",b);
collection.insert(o);
System.out.println("Inserted record.");
f.close();

} catch (IOException e) {
e.printStackTrace();
}
}
void retrieve(String name, String filename, DBCollection collection)
{
byte c[];
try
{
DBObject obj = collection.findOne(new BasicDBObject("name", name));
String n = (String)obj.get("name");
c = (byte[])obj.get("photo");
FileOutputStream fout = new FileOutputStream(filename);
fout.write(c);
fout.flush();
System.out.println("Photo of "+name+" retrieved and stored at "+filename);
fout.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}

Friday, June 5, 2015

JSTl Important Tags

JSTL out tag

JSTL out tag is used to display information on JSP. It can also be used with properties of the bean.

JSTL c out tag Example:

To display the name of the product on JSP, you can use the <c:out> tag like:

<c:out value="${product.name}" default="Not Available" escapeXml="true"></c:out>

The above statement assumes that product object is available on this JSP and that product bean has a property name with setters and getters.
Attributes of <c:out> tag are:
   Required Attributes:
       1. value:This attribute needs expression to be evaluated.
  Optional Attributes:
       1. default: This attribute provides default value if the resulting value is null.
       2. escapeXml: This attribute determines whether characters &,'," in the resulting string should be converted to their corresponding character entity codes. Default value is set to true.

JSTL forEach Tag

JSTL forEach tag is used to iterate over the collection. It can be List, Set, ArrayList, HashMap or any other collection.
JSTL forEach Example:
To display the name of the product on JSP, you can use the <c:forEach> tag like:

<c:forEach items="${productList}" var="product" varStatus="status">
    <c:out value="${product.name}" default="Not Available" escapeXml="false"></c:out>
  </c:forEach>

The above statement assumes that productList object is available on this JSP and that product bean has a property name with setters and getters.
As you can see above, in the JSTL forEach tag, items attirbute is used to define the collection. It will iterate over productList. In each iteration, it will get a product variable defined with attribute var. status attirbute keeps track of iteration.
Withing starting and ending tag of forEach, you can display or apply other logic to each object in the collection. As shown in the above example, product name is displayed with index using c:out tag
Attributes of JSTL forEach tag are:
    1. items:This attribute provides collection of items to iterate over.
     2. 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.
     3. 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.
     4. 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.
     5. 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.
    6. step: Iteration will only process every step items of the collection, starting with the first one.
Iterate over HashMap:
Let's take another example which many people face during coding of real web application. Many times you get HashMap and need to iterate over it. In the example below, I take Map of Country Code and Currency, where country code is unique and selected as a key and currency is a value.

<c:forEach items="${countryCurrencyMap}" var="entry" varStatus="status>
    <c:out value="${entry.key}"> : <c:out value="${entry.value}">
 </c:forEach>

JSTL Set Tag

JSTL Set tag is used to create new variable and assign a value to new or existing variable. 

JSTL Set Tag Example,
 <c:set var="weight" value="10.05"/>
 <c:out value="${weight}"/> 

As you can see above, in the set tag, new variable "weight" is created and value is set to 10.05. In the next line, it prints the valued of weight variable using out tag.

JSTL IF Tag

JSTL c:if tag is used as a conditional statement in JSP. It is similar like If statement in JAVA. Based on condition evaluation within test attribute, if tag decides to run the code within JSTL IF tag

  <c:if test="${weight > 0}"/>
         <c:out value="${weight}"/>
     </c:if>

As you can see above, in the JSTL c:if tag, test attribute check the condition and if condition returns true, it executes the other statements within <c:if> and </c:if> statement.

JSTL If Else Statement Example

Like JAVA, JSTL has if statement. However, JSTL do not have if else statement like JAVA. JSTL provides same functionality using choose-when-otherwise statement. These tags are used as a conditional statement in JSP.
In this tutorial, you will see examples for both JSTL If statement and JSTL if else statement ( using choose-when-otherwise  statement ). 
JSTL c:if tag example:
Assume that you have a variable weight in your application. It is available in pound. You want to convert it to Kilograms. However you want to convert it only, if it is available and not null. You can use c:if tag in this case.

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

<!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 If Tag Example</title>
</head>

<body>

<c:set var="weight" value="10">
 <c:if test="${weight != null}">
 Weight of the product is ${weight * 0.453592} kgs. 
 <c:if> 
</body>
</html> 


Output: Weight of the product is 4.53592 kgs.
As you can see above, <c:if> tag in JSTL is similar to if statement in JAVA.
JSTL if else tag example:
Let's continue with same example shown above where you have a variable weight of the product available in pound and you want to convert it to Kilograms. However you want to show different messages for different condition.
If weight is null, you want to display "Weight is not provided for this product."
If weight is negative, you want to display "Incorrect weight. It can not be negative."
If weight is zero, you want to display "Incorrect weight. It can not be zero."
If weight is not null and above zero, you want to display "Weight of the product is XXXX kgs."
In this case you want to use if else statement in JAVA. But in JSTL, you can use c:choose - c:when - c:otherwiser tag.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>

<!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 If Tag Example</title>
</head>
<body>

    Scenario 1:
    <!--Weight is not available-->
    <c:choose>
        <c:when test="${weight == null}">
             Weight is not provided for this product.
        </c:when>
        <c:when test="${weight <= 0}">
             Incorrect weight. It can not be zero or negative.
        </c:when>
        <c:otherwise>
             Weight of the product is <c:out value="${weight}"/> lbs.
        <c:otherwise/>
    </c:choose>

   Scenario 2:
    <!--Weight is available but negative value-->
    <c:set var="weight" value="-6">
    <c:choose>
        <c:when test="${weight == null}">
             Weight is not provided for this product.
        </c:when>
        <c:when test="${weight <= 0}">
             Incorrect weight. It can not be zero or negative.
        </c:when>
        <c:otherwise>
             Weight of the product is <c:out value="${weight}"/> lbs.
        <c:otherwise/>
    </c:choose>

   Scenario 3:
    <!--Weight is available but zero value-->
    <c:set var="weight" value="0">
    <c:choose>
        <c:when test="${weight == null}">
             Weight is not provided for this product.
        </c:when>
        <c:when test="${weight <= 0}">
             Incorrect weight. It can not be zero or negative.
        </c:when>
        <c:otherwise>
             Weight of the product is <c:out value="${weight}"/> lbs.
        <c:otherwise/>
    </c:choose>

  Scenario 4:
    <!--Weight is available and it is 10 lbs.-->
    <c:set var="weight" value="10">
    <c:choose>
        <c:when test="${weight == null}">
             Weight is not provided for this product.
</c:when>
        <c:when test="${weight <= 0}">
             Incorrect weight. It can not be zero or negative.
        </c:when>
        <c:otherwise>
             Weight of the product is <c:out value="${weight}"/> lbs.
        <c:otherwise/>
    </c:choose>
    
</body> 
</html>


Output: 
Scenario 1:Weight is not provided for this product.
Scenario 2:Incorrect weight. It can not be negative..
Scenario 3:Incorrect weight. It can not be zero.
Scenario 4:Weight of the product is 4.53592 kgs.
Make sure that there is no condition evaluation in <c:choose> block. This is enclosing tag for <c:when> and <c:otherwise> blocks.
<c:when> tag has condition evaluation capability and you can have multiple <c:when> blocks within single <c:choose> block. Each condition can be evaluated using test attribute of this statement.
<c:otherwise> block do not have any condition evaluation capabiity. It represents all conditions which are not covered by <c:when> statements. <c:otherwise> statement must be present in <c:choose> block.

JSTL Choose When Otherwise Tag

These tags are used as a conditional statement in JSP. 

For Example,
 <c:choose>
          <c:when test="${weight > 0}">
              <c:out value="${weight}"/>
          </c:when>
          <c:otherwise>
              <c:out value="0"/>
          <c:otherwise/>
      </c:choose>

As you can see above, <c:choose>-<c:when>-<c:otherwise> tags JSP are similar to if-elesif-else blocks in JAVA. When you have multiple conditions and each of them produces different output, you can use <c:choose>-<c:when>-<c:otherwise>.
Make sure that there is no codition eveluation in <c:choose> block. This is enclosing tag for <c:when> and <c:otherwise> blocks.
<c:when> tag has condition evaluation capability and you can have multiple <c:when> blocks within single <c:choose> block. Each condition can be evaluated using test attribute of this statement.
<c:otherwise> block do not have any condition evaluation capabiity. It represents all conditions which are not covered by <c:when> statements. <c:otherwise> statement must be present in <c:choose> block.
JSTL Catch TagJSTL catch tag is used to catch the exception thrown at run time in JSP.

<c:catch var="exception">

    <c:out value="${firstNumber/ secondNumber}"/> 

  </c:catch>

  <c:if test="${exception != null}">

    Exception thrown is <c:out value="${exception}"/> 

  </c:if>

As you can see above, we are trying to display result of dividing firstNumber with secondNumber. It may be possible that secondNumber is 0. In that event, exception will be thrown at run time. <c:catch> block will handle this exception and print the exception in the next <c:if> block.

JSTL Remove Tag

Remove tag is being used in JSP to remove the variable from the scope.

 <c:set var="price" value="10.0" scope="session">
    <c:out value="${price}"/>
    <c:remove var="price">
    <c:out value="${price}"/>
As you can see above, <c:set> tag creates a new variable price with value of 10.0 and having scope for the current session. When tag <c:out> is used to print the value, first time it will print 10.0
In line 3, <c:remove> tag is removing the variable price from the session scope. In line 4, when <c:out> tag is printing value of variable price, it will not print anything as it is removed in line 2.

C:Import
JSTL Import tag is being used in JSP to include the content of other resource in the current JSP.

<c:import url="http://www.apekshit.com" var="tutorial" />
 <c:out value="${tutorial}"/> 

As you can see above, <c:import> tag imports the content of another resource specified in url attribute to the current JSP. It store the content to variable tutorial and prints it using <c:out> tag in the next line.
The <c:import> tag is similar to import action in JSP. However, <c:import> can import resouces from other applications also by providing absolute path to it.

<c:forTokens

  <c:forTokens delims=" {,}" items="{25,50,75,100}" var="number">
    <c:out value="${number}" default="25"></c:out>
  </c:forTokens>

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.