Log4j logging API example in java


The Log4j API tutorial in java provides the interface that applications should code to and provides the adapter components required for implementers to create a logging implementation. The basic Log4j API tutorial in java: import org.apache.log4j.Logger; public class LogExample { public LogExample() { } static Logger log = Logger.getLogger(LogExample.class); public static void main(String argsp[]) { log.debug(“projectname-modulename-Class-method-Here…

Convert IP into Decimal Number in Java

In this tutorial, we show you how to convert an IP address to its decimal equivalent in Java, and vice versa.

For examples :  <->  4294967295      <->  3232235778

1. IP Address to Decimal

We show you two ways to convert an IP address to a decimal number

  1. Normal power of 256
  2. Bit shifting

Read more


JSF 2.0 Tutorial

JavaServer Faces(JSF) 2. 0, is usually an MVC web framework which usually concentrate on simplifies constructing User interfaces (comes with 100+ ready USER INTERFACE tags) for Java web app as well as create reusable USER INTERFACE component simple to put into practice. Not like JSF 1.x back button, every little thing is expressed inside faces-config. xml, together with JSF 2. 0, you might be allowed to make use of annotation to be able to state navigating, manage bean or maybe CDI bean, which can make ones development much easier as well as faster.

In this particular short tutorial, it offers a superior quite a few comprehensive good examples as well as explanations in applying JavaServer Faces(JSF) 2. 0 framework.

Some quick start examples for JSF 2.0

Quick Start JSF 2.0

Managed Bean



Load ImageView with bitmap from internet

It’s a simple way to load ImageView with a bitmap from internet, via http connection.

Load ImageView with bitmap from internet

In order to load something from internet, the AndroidManifest.xml have to be modified to grand permission for internet access.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   <application android:icon="@drawable/icon" android:label="@string/app_name">
       <activity android:name=".AndroidWebImage"
               <action android:name="android.intent.action.MAIN" />
               <category android:name="android.intent.category.LAUNCHER" />

   <uses-sdk android:minSdkVersion="4" />
 <uses-permission android:name="android.permission.INTERNET" />

Modify main.xml to include a ImageView

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

java code:

package com.exercise.AndroidWebImage;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;

public class AndroidWebImage extends Activity {

String image_URL=

   /** Called when the activity is first created. */
   public void onCreate(Bundle savedInstanceState) {

       ImageView bmImage = (ImageView)findViewById(R.id.image);
    BitmapFactory.Options bmOptions;
    bmOptions = new BitmapFactory.Options();
    bmOptions.inSampleSize = 1;
    Bitmap bm = LoadImage(image_URL, bmOptions);

   private Bitmap LoadImage(String URL, BitmapFactory.Options options)
    Bitmap bitmap = null;
    InputStream in = null;       
       try {
           in = OpenHttpConnection(URL);
           bitmap = BitmapFactory.decodeStream(in, null, options);
       } catch (IOException e1) {
       return bitmap;               

private InputStream OpenHttpConnection(String strURL) throws IOException{
 InputStream inputStream = null;
 URL url = new URL(strURL);
 URLConnection conn = url.openConnection();

  HttpURLConnection httpConn = (HttpURLConnection)conn;

  if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
   inputStream = httpConn.getInputStream();
 catch (Exception ex)
 return inputStream;

Enhanced by Zemanta

Struts 2 Tiles Plugin Tutorial with Example in Eclipse

Welcome to Part-4 of the 7-part series where we will go through different aspects for Struts2 Framework with some useful examples. In previous part we went through Struts2 Validation Framework. We saw how easy it is to integrate validation in your struts2 application.

In this part we will discuss about Tiles Framework and its Integration with Struts2. We will add Tiles support to our HelloWorld Struts application that we created in previous parts. I strongly recommend you to go through previous articles and download the source code of our sample application.

Struts 2 Tutorial List

Introduction to Tiles 2

Nowadays, website are generally divided into pieces of reusable template that are being rendered among different web pages. For example a site containing header, footer, menu etc. This items remains same through out the website and give it a common look and feel. It is very difficult to hard code this in each and every webpage and if later a change is needed than all the pages needs to be modified. Hence we use templatization mechanism. We create a common Header, Footer, Menu page and include this in each page.

Tiles Plugin allow both templating and componentization. In fact, both mechanisms are similar: you
define parts of page (a “Tile”) that you assemble to build another part or a full page. A part can
take parameters, allowing dynamic content, and can be seen as a method in JAVA language. Tiles is a templating system used to maintain a consistent look and feel across all the web pages of a web application. It increase the reusability of template and reduce code duplication.

A common layout of website is defined in a central configuration file and this layout can be extended across all the webpages of the web application.

Our Application Layout

Our goal is to add Header, Footer and Menu to our StrutsHelloWorld application. Following will be the layout of the same.

Required JAR files

In order to add Tiles support to our Struts2 application, we will need few jar files. Following is the list of JARs in our example. Add these JARs in WEB-INF/lib folder.

Configuring Tiles in web.xml

To configure Tiles, an entry for listener has to be made in web.xml. Open the web.xml from WEB-INF folder and add following code into it.


The above code configure Tiles listener in web.xml. An input configuration file /WEB-INF/tiles.xml is passed as argument. This file contains the Tiles definition for our web application.

Create a file tiles.xml in WEB-INF folder and copy following code into it.

01.<?xml version="1.0" encoding="UTF-8" ?>
03.<!--DOCTYPE tiles-definitions PUBLIC-->
04."-//Apache Software Foundation//DTD Tiles Configuration 2.0//EN"
07.<definition name="baseLayout" template="/BaseLayout.jsp">
08.<put-attribute name="title" value="" />
10.<put-attribute name="header" value="/Header.jsp" />
11.<put-attribute name="menu" value="/Menu.jsp" />
13.<put-attribute name="body" value="" />
14.<put-attribute name="footer" value="/Footer.jsp" />
17.<definition name="/welcome.tiles" extends="baseLayout">
18.<put-attribute name="title" value="Welcome" />
20.<put-attribute name="body" value="/Welcome.jsp" />
22.<definition name="/customer.tiles" extends="baseLayout">
24.<put-attribute name="title" value="Customer Form" />
25.<put-attribute name="body" value="/Customer.jsp" />
28.<definition name="/customer.success.tiles" extends="baseLayout">
29.<put-attribute name="title" value="Customer Added" />
31.<put-attribute name="body" value="/SuccessCustomer.jsp" />

Here in tiles.xml we have define a template baseLayout. This layout contains attributes such as Header, Title, Body, Menu and Footer. The layout is then extended and new definitions for Welcome page and Customer page is defined. We have override the default layout and changed the content for Body and Title.

Creating JSPs

struts-2-tiles-layout-jspWe will define the template for our webapplication in a JSP file called BaseLayout.jsp. This template will contain different segments of web page (Header, Footer, Menu etc). Create 4 new JSP files BaseLayout.jsp, Header.jsp, Menu.jsp and Footer.jsp and copy following content in each of them.

01.<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%>
02.<!--DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"-->
07.<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
08.<title><tiles:insertAttribute name="title" ignore="true" /></title>
12.<table border="1" cellpadding="2" cellspacing="2" align="center">
15.<td height="30" colspan="2"><tiles:insertAttribute name="header" />
20.<td height="250"><tiles:insertAttribute name="menu" /></td>
21.<td width="350"><tiles:insertAttribute name="body" /></td>
25.<td height="30" colspan="2"><tiles:insertAttribute name="footer" />


1.<%@ page contentType="text/html; charset=UTF-8"%>
3.<%@ taglib prefix="s" uri="/struts-tags"%>
4.<h2>Struts2 Example - ViralPatel.net</h2>


1.<%@ page contentType="text/html; charset=UTF-8"%>
3.<%@ taglib prefix="s" uri="/struts-tags"%>
4.<s:a href="customer-form">Customer</s:a>


1.<%@ page contentType="text/html; charset=UTF-8"%>
3.<%@ taglib prefix="s" uri="/struts-tags"%>
4.Copyright &copy; ViralPatel.net

Modifications in Struts.xml

In struts.xml we defined result tag which maps a particular action with a JSP page. Now we will modify it and map the result with Tiles. Following will be the content of struts.xml file.

01.<?xml version="1.0" encoding="UTF-8" ?>
03.<!--DOCTYPE struts PUBLIC-->
04."-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
08.<constant name="struts.enable.DynamicMethodInvocation"
09.value="false" />
11.<constant name="struts.devMode" value="false" />
12.<constant name="struts.custom.i18n.resources"
13.value="ApplicationResources" />
15.<package name="default" extends="struts-default" namespace="/">
17.<result-type name="tiles"
19.class="org.apache.struts2.views.tiles.TilesResult" />
21.<action name="login"
24.<result name="success" type="tiles">/welcome.tiles</result>
25.<result name="error">Login.jsp</result>
28.<action name="customer"
30.<result name="success" type="tiles">/customer.success.tiles</result>
32.<result name="input" type="tiles">/customer.tiles</result>
34.<action name="customer-form">
35.<result name="success" type="tiles">/customer.tiles</result>

The struts.xml now defines a new Result type for Tiles. This result type is used in tag for different actions. Also note that we have define a new action customer-form. This is just an empty declaration to redirect user to Customer form page when she clicks Customer link from menu.

That’s All Folks

Compile and Execute the application in Eclipse and see that the header, menu and footer are properly applied.
Welcome Page with Tiles
Customer Page with Tiles
Customer Success Page with Tiles

Download Source Code

Click here to download Source Code without JAR files (11KB)

How To Create QR Codes in Java & Servlet

Nowadays, Quick Response (QR) Codes are becoming more and more useful as they have gone mainstream, thanks to the smart phones. Right from the bus shelter, product packaging, home improvement store,

automobile, a lot of internet websites are integrating QR Codes on their pages to let people quickly reach them. With increase in number of users of smart phones day by day, the QR codes usage is going up exponentially.

Let us see a quick overview of Quick Response (QR) codes and also how to generate these codes in Java.

Introduction to QR Codes

A QR code (abbreviated from Quick Response code) is a type of matrix barcode (or two-dimensional code) first designed for the automotive industry. More recently, the system has become popular outside of the industry due to its fast readability and comparatively large storage capacity. The code consists of black modules arranged in a square pattern on a white background. The information encoded can be made up of four standardized kinds (“modes”) of data (numeric, alphanumeric, byte/binary, Kanji), or by supported extensions virtually any kind of data.

Created by Toyota subsidiary Denso Wave in 1994 to track vehicles during the manufacturing process, the QR code is one of the most popular types of two-dimensional barcodes. It was designed to allow its contents to be decoded at high speed.

Hello World QR Code in Java

Zebra Crossing (ZXing) is an awesome open source library that one can use to generate / parse QR Codes in almost all the platforms (Android, JavaSE, IPhone, RIM, Symbian etc). But if you have to generate simple QR Codes, I found it a bit clumsy to implement.

However QRGen is a good library that creates a layer on top of ZXing and makes QR Code generation in Java a piece of cake. It has a dependency on ZXing, so you would need ZXing jar files along with QRGen to create QR Codes in Java.

On the download page of ZXing, you will not find the JAR files. Instead we have to create JAR files using the source code. I have already generated these JAR files. Here are the links:

zxing-core-1.7.jar (346 KB)
zxing-javase-1.7.jar (21 KB)

Also download the QRGen JAR File from their download page.

Include these JAR files in your Classpath and execute following Java code to generate QR Code.

package net.viralpatel.qrcode;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import net.glxn.qrgen.QRCode;
import net.glxn.qrgen.image.ImageType;
public class Main {
    public static void main(String[] args) {
        ByteArrayOutputStream out = QRCode.from("Hello World")
        try {
            FileOutputStream fout = new FileOutputStream(new File(
        } catch (FileNotFoundException e) {
            // Do Logging
        } catch (IOException e) {
            // Do Logging

The code is pretty straight forward. We used QRCode class to generate QR Code Stream and write the byte stream to a file C:QR_Code.JPG.

Download Source Code

QR_Code_Java.zip (339 KB)

If you open this JPEG file and scan using your iPhone or Android QR scanner, you’ll find a cool “Hello World” in it :)

Apart from generating Sterams of data using QRGen API, we can also use below APIs to create QR Codes:

// get QR file from text using defaults
File file = QRCode.from("Hello World").file();
// get QR stream from text using defaults
ByteArrayOutputStream stream = QRCode.from("Hello World").stream();
// override the image type to be JPG
QRCode.from("Hello World").to(ImageType.JPG).file();
QRCode.from("Hello World").to(ImageType.JPG).stream();
// override image size to be 250x250
QRCode.from("Hello World").withSize(250, 250).file();
QRCode.from("Hello World").withSize(250, 250).stream();
// override size and image type
QRCode.from("Hello World").to(ImageType.GIF).withSize(250, 250).file();
QRCode.from("Hello World").to(ImageType.GIF).withSize(250, 250).stream();

Website Link (URLs) QR Code in Java

One of the most common use of a QR Code is to bring traffic to a particular webpage or download page of website. Thus QR Code encodes a URL or website address which a user can scan using phone camera and open in their browser. URLs can be straight forward included in QR Codes. In above Java Hello World example, just replace “Hello World” string with the URL you want to encode in QR Code. Below is the code snippet:

ByteArrayOutputStream out = QRCode.from("http://viralpatel.net")

QR Code in Servlet

Most of the time you would need to generate QR Codes dynamically in some website. We already saw how easy it is to generate QR code in Java. Now we will see how to integrate this QR Code generation in a Java Servlet.

Following is a simple Http Servlet that creates QR Code using QRGen and ZXing library. User provides the text for which QR Code is generated.

The index jsp file contains a simple html form with a textbox and submit button. User can enter the text that she wishes to generate QR code of and presses submit.

File: index.jsp

<title>QR Code in Java Servlet - viralpatel.net</title>
    <form action="qrservlet" method="get">
        <p>Enter Text to create QR Code</p>
        <input type="text" name="qrtext" />
        <input type="submit" value="Generate QR Code" />

The magic happens in QRCodeServlet.java. Here we uses QRGen library along with ZXing and generates QR Code for given text (Text we get from request.getParameter). Once the QR Stream is generated, we write this to response and set appropriate content type.

File: QRCodeServlet.java

package net.viralpatel.qrcodes;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.glxn.qrgen.QRCode;
import net.glxn.qrgen.image.ImageType;
public class QRCodeServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        String qrtext = request.getParameter("qrtext");
        ByteArrayOutputStream out = QRCode.from(qrtext).to(
        OutputStream outStream = response.getOutputStream();

The below web.xml simply maps QRCodeServlet.java with /qrservlet URL.

File: web.xml

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

Download Source Code

QR_Code_Servlet.zip (340 KB)






Generating QR Codes in Java is not only easy, but quite straight forward. Integrating this functionality with any existing Java based app is just a piece of cake! In this tutorial we saw how to generate these QR codes in Java and also with Servlet.

Hope you’ll like this :)

Enhanced by Zemanta

Spring MVC: Multiple Row Form Submit using List of Beans

Recently I had a requirement where using Spring MVC we had to take inputs multiple rows of data from user. The form had many rows which user can edit and submit. Spring MVC provides very simple yet elegant way of collecting data from multiple rows from HTML form and store them in List of Beans in Java.

18% Price Drop: Samsung 51" Black Plasma 720P HDTV – PN51E450

Lets look at the requirement first. We have a screen where data for multiple Contacts is displayed. The Contact data is displayed in an HTML table. Each row in the table represents a single contact. Contact details consist of attributes such as Firstname, Lastname, Email and Phone number.

Related: Spring 3 MVC Tutorial Series (Must Read)

The Add Contact form would look like following:

Lets see the code behind this example.

Tools and Technologies used:

  1. Java 5 or above
  2. Eclipse 3.3 or above
  3. Spring MVC 3.0

Step 1: Create Project Structure

Open Eclipse and create a Dynamic Web Project.

Enter project name as SpringMVC_Multi_Row and press Finish.

Step 2: Copy Required JAR files

Once the Dynamic Web Project is created in Eclipse, copy the required JAR files under WEB-INF/lib folder. Following are the list of JAR files:


Step 3: Adding Spring MVC support

Once the basic project setup is done, we will add Spring 3 MVC support. For that first modify default web.xml and add springs DispatcherServlet.

File: /WebContent/WEB-INF/web.xml

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

Related: Tutorial: Learn Spring MVC Lifecycle

Now add spring-servlet.xml file under WEB-INF folder.

File: /WebContent/WEB-INF/spring-servlet.xml

<?xml  version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <context:annotation-config />
    <context:component-scan base-package="net.viralpatel.spring3.controller" />  
    <bean id="jspViewResolver"
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />

Note that in above spring-servlet file, line 10, 11 defines context:annotation-config and component-scan tags. These tags let Spring MVC knows that the spring mvc annotations are used to map controllers and also the path from where the controller files needs to be loaded. All the files below package net.viralpatel.spring3.controller will be picked up and loaded by spring mvc.

Step 4: Add Spring Controller and Form classes

File: /src/net/viralpatel/spring3/form/Contact.java

package net.viralpatel.spring3.form;
public class Contact {
    private String firstname;
    private String lastname;
    private String email;
    private String phone;
    public Contact() {
    public Contact(String firstname, String lastname, String email, String phone) {
        this.firstname = firstname;
        this.lastname = lastname;
        this.email = email;
        this.phone = phone;
    // Getter and Setter methods

File: /src/net/viralpatel/spring3/form/ContactForm.java

package net.viralpatel.spring3.form;
import java.util.List;
public class ContactForm {
    private List<Contact> contacts;
    public List<Contact> getContacts() {
        return contacts;
    public void setContacts(List<Contact> contacts) {
        this.contacts = contacts;

Note line 7 in above code how we have defined a List of bean Contact which will hold the multi-row data for each Contact.

File: /src/net/viralpatel/spring3/controller/ContactController.java

package net.viralpatel.spring3.controller;
import java.util.ArrayList;
import java.util.List;
import net.viralpatel.spring3.form.Contact;
import net.viralpatel.spring3.form.ContactForm;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
public class ContactController {
    private static List<Contact> contacts = new ArrayList<Contact>();
    static {
        contacts.add(new Contact("Barack", "Obama", "barack.o@whitehouse.com", "147-852-965"));
        contacts.add(new Contact("George", "Bush", "george.b@whitehouse.com", "785-985-652"));
        contacts.add(new Contact("Bill", "Clinton", "bill.c@whitehouse.com", "236-587-412"));
        contacts.add(new Contact("Ronald", "Reagan", "ronald.r@whitehouse.com", "369-852-452"));
    @RequestMapping(value = "/get", method = RequestMethod.GET)
    public ModelAndView get() {
        ContactForm contactForm = new ContactForm();
        return new ModelAndView("add_contact" , "contactForm", contactForm);
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public ModelAndView save(@ModelAttribute("contactForm") ContactForm contactForm) {
        List<Contact> contacts = contactForm.getContacts();
        if(null != contacts && contacts.size() > 0) {
            ContactController.contacts = contacts;
            for (Contact contact : contacts) {
                System.out.printf("%s t %s n", contact.getFirstname(), contact.getLastname());
        return new ModelAndView("show_contact", "contactForm", contactForm);

In above ContactController class, we have defile two methods: get() and save().

get() method: This method is used to display Contact form with pre-populated values. Note we added a list of contacts (Contacts are initialize in static block) in ContactForm bean object and set this inside a ModelAndView object. The add_contact.jsp is displayed which in turns display all contacts in tabular form to edit.

save() method: This method is used to fetch contact data from the form submitted and save it in the static array. Also it renders show_contact.jsp file to display contacts in tabular form.

Step 5: Add JSP View files

Add following files under WebContent/WEB-INF/jsp/ directory.

File: /WebContent/WEB-INF/jsp/add_contact.jsp

<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    <title>Spring 3 MVC Multipe Row Submit - viralpatel.net</title>
<h2>Spring MVC Multiple Row Form Submit example</h2>
<form:form method="post" action="save.html" modelAttribute="contactForm">
    <c:forEach items="${contactForm.contacts}" var="contact" varStatus="status">
            <td align="center">${status.count}</td>
            <td><input name="contacts[${status.index}].firstname" value="${contact.firstname}"/></td>
            <td><input name="contacts[${status.index}].lastname" value="${contact.lastname}"/></td>
            <td><input name="contacts[${status.index}].email" value="${contact.email}"/></td>
            <td><input name="contacts[${status.index}].phone" value="${contact.phone}"/></td>
<input type="submit" value="Save" />

In above JSP file, we display contact details in a table. Also each attribute is displayed in a textbox. Note that modelAttribute=”contactForm” is defined in <form:form /> tag. This tag defines the modelAttribute name for Spring mapping. On form submission, Spring will parse the values from request and fill the ContactForm bean and pass it to the controller.

Also note how we defined textboxes name. It is in form contacts[i].a. Thus Spring knows that we want to display the List item with index i and its attribute a.

contacts[${status.index}].firstname will generate each rows as follows:

contacts[0].firstname // mapped to first item in contacts list
contacts[1].firstname // mapped to second item in contacts list
contacts[2].firstname // mapped to third item in contacts list

Spring 3 MVC and path attribute and square bracket

One thing here is worth noting that we haven’t used Spring’s
tag to render textboxes. This is because Spring MVC 3 has a unique way of handling path attribute for
tag. If we define the textbox as follows:

<form:input path="contacts[${status.index}].firstname" />

Then instead of converting it to following HTML code:

<input name="contacts[0].firstname" />
<input name="contacts[1].firstname" />
<input name="contacts[2].firstname" />

It converts it into following:

<input name="contacts0.firstname" />
<input name="contacts1.firstname" />
<input name="contacts2.firstname" />

Note how it removed square brackets [ ] from name attribute. In previous versions of Spring (before 2.5) the square bracket were allowed in name attribute.

It seems w3c has later changed the HTML specification and removed [ ] from html input name.
Read the specification http://www.w3.org/TR/html4/types.html#type-name. It clearly says that:

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens (“-”), underscores (“_”), colons (“:”), and periods (“.”).

Thus, square brackets aren’t allowed in name attribute! And thus Spring 3 onwards this was implemented.

So far I haven’t got any workaround to use springs <form:input /> tag instead of plain html <input /> to render and fetch data from multiple rows.

File: /WebContent/WEB-INF/jsp/show_contact.jsp

<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    <title>Spring 3 MVC Multipe Row Submit - viralpatel.net</title>
<h2>Show Contacts</h2>
<table width="50%">
    <c:forEach items="${contactForm.contacts}" var="contact" varStatus="status">
<input type="button" value="Back" onclick="javascript:history.back()"/>

File: /WebContent/index.jsp

<jsp:forward page="get.html"></jsp:forward>


Final Project Structure

Once we have added all relevant source files and jar files, the project structure should look like following:


Step 6: Execute it

Execute the web application Right click on project > Run As > Run on Server.

Add Contact page

Show Contact page

Download Source Code

Spring-MVC-Multiple-Row-List-example.zip (2.9 MB)

Enhanced by Zemanta

Deploying Java Servlet applications on Windows with IIS


Java platform is extremely successful in building robust and high performance web applications. Platform independence is one of the strength of Java engine and Helicon Zoo now provides a convenient way to deploy and run Java web applications on Windows platform with Microsoft IIS. To deploy Java Servlet application on IIS 7 you will only need to follow this simple instruction:

Platfrom installation

  1. Download and install Web Platform Installer.
  2. Run Web Platform Installer and click “Options”.
  3. Add Helicon Zoo feed into Display additional scenarios box:  http://www.helicontech.com/zoo/feed. New “Zoo” tab will appear.
  4. Go to the Zoo, Packages and install Java Hosting Package.
  5. Accept licenses to start installation process.

Alternatively, instead of installing Java Hosting Package you can install Modules –> Helicon Zoo Module and Engines –> Jetty separately. This is minimal requirement to run Java Servlet applications under Microsoft IIS web server. If you want to run Java Servlets under IIS Express and WebMatrix in your development environment, then you will also need to install Helicon Zoo Module for IIS Express form Engines section.

This is enough configuration to run most of Java Servlet applications directly form IIS.

Installing application

Launch IIS Manager and create new web-site or an application within a web-site. Copy your Java application into the root folder of this IIS application. Java application could be either a single .war file or set of unpacked files with directory structure, including web-inf folder. Then just create the following web.config:

 <?xml version="1.0" encoding="UTF-8"?>
      <application name="jetty.project" >
          <!-- Uncomment line below if you want to set contexts directory -->
          <!--  <add name="CONTEXTS_DIR" value="%APPL_VIRTUAL_PATH%" /> -->

          <!-- Optional variables: -->
          <!-- <add name="CONTEXT_PATH" value="%APPL_VIRTUAL_PATH%" /> -->
          <!-- <add name="WAR_EXTRACT_PATH" value="%APPL_PHYSICAL_PATH%" /> -->

          <!-- A WAR file or start directory to run -->
          <add name="WAR_FILE" value="my_application.war" />

          <add name="jetty.project#x86" scriptProcessor="java.jetty"
            path="*" verb="*" modules="HeliconZoo_x86"
            preCondition="bitness32" resourceType="Unspecified"
            requireAccess="Script" />
          <add name="jetty.project#x64" scriptProcessor="java.jetty"
            path="*" verb="*" modules="HeliconZoo_x64"
            preCondition="bitness64" resourceType="Unspecified"
            requireAccess="Script" />

Please take a look at <environmentVariables> section.

  • CONTEXTS_DIR — optional path to directory with .xml files which describe Jetty contexts. If this variable isn’t set, Zoo looks for “contexts” folder in the root of application. If no such folder found, Zoo presumes the application has single context and uses variables described below.
  • CONTEXT_PATH — optional virtual path of the application. Default value is taken from APPL_VIRTUAL_PATH variable.
  • WAR_FILE — optional path to a .war file or directory with extracted application.
  • WAR_EXTRACT_PATH — optional .war file extraction path. Is set to application’s root folder by default.

Here is an example of context.xml file that you may use instead of setting WAR file name explicitly. This allows to run multiple applications and contexts in a single IIS web site.


<?xml version="1.0"?>
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" "http://www.eclipse.org/jetty/configure.dtd">

<Configure class="org.eclipse.jetty.webapp.WebAppContext">

   <Set name="contextPath">/application</Set>
   <Set name="war">my_application.war</Set>
   <Set name="tempDirectory">application_dir</Set>


WARNING: Since WAR files need to be extracted before execution you will need to have a folder with write permissions.  In default IIS installation all application pools are executed with permissions of IIS_IUSRS group which does not have write permissions to the web application folders. You will need to provide write permissions to the user running Application Pool or IIS_IUSRS group to the folder containing Java application or specify other folder using WAR_EXTRACT_PATH variable with write permissions provided.Now you can open IIS web site in the browser and see your Java web application running.

That’s it! Installation process is clear and automatic and will only take several minutes.

5 Responses to Deploying Java Servlet applications on Windows with IIS

  1. Peter says:

    Downloaded and installed as described in the article (http://www.helicontech.com/articles/deploying-java-servlet-applications-on-windows-with-iis/).

    However for some weird reason I can successfully view the Java app via IIS when using http://localhost/appname but if I do the same thing http:///appname on another machine I get a a 404 from IIS and if I do it on the server itself I get a 404 from Jetty instead.

    This is running on a 64bit Win2008R2 Std server VM with an IIS app set up to use a ASP.NET 4.0 integrated app pool.
    The folder the IIS app points to contains the contents of the WAR file, i.e. \web-inf and \xforms-jsp and the web.config with the described contents from the article.

    Any ideas on what could be wrong would be much appreciated.

    • Slavik says:

      Please try and use CONTEXT_PATH variable as follows:
      <add name=”CONTEXTS_PATH” value=”/appname” />

      Make sure “appname” is an application. If it’s not, open IIS manager, navigate to that folder and in the context menu click “Convert to Application”.

  2. jules says:

    I installed on a Windows 7 64 bit machine and then downloaded the jenkins.war file and tried to deploy it:
    But I get:
    HTTP ERROR: 503
    Problem accessing /test. Reason:
    Service Unavailable
    Powered by Jetty://


    • Slov says:

      I think installing Jenkins on IIS may deserve a separate article.
      First you will need to upgrade your Jetty installation as we have fixed some functions. Just delete C:\jetty folder and install again using Helicon Zoo feed.
      Then you will need to use contexts folder, instead of setting WAR file explicitly as Jenkins require additional configurations.
      Please remove all “environmentVariables” from web.config, create contexts folder, and create context.xml file in this folder with the following content:

      < ?xml version=”1.0″?>
      < !DOCTYPE Configure PUBLIC “-//Jetty//Configure//EN” “http://www.eclipse.org/jetty/configure.dtd”&gt;

      Test Realm

      After that navigate to http://localhost/jenkins (not to the root folder). It should work now.

      • Slov says:

        A bug with tags. Try again:

        <?xml version=”1.0″?>
        <!–DOCTYPE Configure PUBLIC “-//Jetty//Configure//EN” “http://www.eclipse.org/jetty/configure.dtd”>–>

        <Configure class=”org.eclipse.jetty.webapp.WebAppContext”>
        <Get name=”securityHandler”>
        <Set name=”loginService”>
        <New class=”org.eclipse.jetty.security.HashLoginService”>
        <Set name=”name”>Test Realm</Set>

        <Set name=”contextPath”>/jenkins</Set>
        <Set name=”war”>jenkins.war</Set>
        <Set name=”tempDirectory”>jenkins</Set>

Reference :http://www.helicontech.com/articles/deploying-java-servlet-applications-on-windows-with-iis/

Program to develop a Mail Client in Java.

English: SMTP transfer model Blue arrows can b...

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.net.*;
import java.io.*;
import javax.swing.*;

public class MailClient
public static void main(String []args)
JFrame frame = new MailClientFrame();
class MailClientFrame extends JFrame implements ActionListener

private BufferedReader in;
private PrintWriter out;
private JTextField from;
private JTextField to;
private JTextField smtpServer;
private JTextArea message;
private JTextArea response;
private JLabel fromLbl;
private JLabel toLbl;
private JLabel serverLbl;

public MailClientFrame()
setTitle(“Mail Client”);

addWindowListener(new WindowAdapter()
public void windowClosing(WindowEvent e)

getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));

fromLbl = new JLabel(“From: “);

from = new JTextField(20);

toLbl = new JLabel(“To: “);

to = new JTextField(20);

serverLbl = new JLabel(“SMTP Server:”);

smtpServer = new JTextField(20);

message = new JTextArea(5,20);

JScrollPane p = new JScrollPane(message);

response = new JTextArea(5,20);

JScrollPane p1 = new JScrollPane(response);

JButton sendButton  = new JButton(“Send”);

JPanel buttonPanel = new JPanel();



public void actionPerformed(ActionEvent evt)
SwingUtilities.invokeLater(new Runnable()
public void run()

public void sendMail()
Socket s = new Socket(smtpServer.getText(),25);
out  = new PrintWriter(s.getOutputStream());
in = new BufferedReader(new InputStreamReader(s.getInputStream()));

String hostName = InetAddress.getLocalHost().getHostName();
send(“HELO” + hostName);
send(“MAIL FROM:”+ from.getText());
send(“RCPT TO:” + to.getText());
catch(IOException e)
response.append(“Error:” + e);

public void send(String s) throws IOException
String line;
if ( (line = in.readLine())!=null)

Bounded Type Parameters

1101_Get $25 off $200 + Free Shipping Any Order at CHEFS Catalog

Java (programming language)

In this section, you will learn how we can bound the type parameter.

We can bound the types which are permitted to be passed to type parameter section. For example, we can create a method that operates only on number or its subclasses like Integer, Float etc.

Restricting type parameters section is known as Bounded Type Parameters.

You can declare bounded type parameter as follows :

public class AnimalActions<A extends Animal>

“A extends Animal” means whatever type we pass for the substitution of type parameter must extend/implement the Animal class/interface.

Here we can use only extends for both classes as well as for interface. Given below declaration is not valid :

public class AnimalActions<A implements Animal>

Given below the complete example :

Example :

public class BoundedTypeParamDemo<A> {

private A a;

public void set(A a) {
this.a = a;

public A get() {
return a;

public <U extends Number> void inspect(U u) {
System.out.println("T: " + a.getClass().getName());
System.out.println("U: " + a.getClass().getName());

public static void main(String[] args) {
BoundedTypeParamDemo integerBox = new BoundedTypeParamDemo();
integerBox.set(new Integer(10));
// The below line will give error
integerBox.inspect("some text");

Output :

The above code will give error because the generic method inspect(U u)  is not applicable for the arguments  of String type. The String type  is not a valid substitute for the bounded parameter :

Exception in thread “main” java.lang.Error: Unresolved compilation problem:
Bound mismatch: The generic method inspect(U) of type BoundedTypeParamDemo<A> is not applicable for the arguments (String). The inferred type String is not a valid substitute for the bounded parameter <U extends Number> at BoundedTypeParamDemo.main(BoundedTypeParamDemo.java:25)

Download Source Code