Node js Web application Development Part 3


Here is the sourcecode for the project :

Writing to the database is not particularly difficult. Essentially we need to set up a route that takes a POST, rather than a GET. We could use AJAX here, and honestly that’s my preference most of the time … but that’s really a whole different tutorial, so we’ll stick to a standard post-and-show-results approach. Once again, though, it’s not too hard to adapt things to work that way if you want.


We’re going quick and dirty here: two ugly, unstyled text inputs and a submit button. 1996-style. Just like before, we’ll start with app.get(); and then give it something to get. Open up app.js and find the part with all of those app.get() calls, and add this to the bottom of them:

app.get('/newuser', routes.newuser);

So that you get:

app.get('/', routes.index);
app.get('/users', user.list);
app.get('/helloworld', routes.helloworld);
app.get('/userlist', routes.userlist(db));

// New Code
app.get('/newuser', routes.newuser);

As with all app.get requests, we need to adjust the route to know what to serve up. Open up /routes/index.js and add the following:

exports.newuser = function(req, res){
  res.render('newuser', { title: 'Add New User' });

Now we just need a template, as newuser.jade, and replace the whole file contents with this:

extends layout

block content
    h1= title
        input#inputUserName(type="text", placeholder="username", name="username")
        input#inputUserEmail(type="text", placeholder="useremail", name="useremail")
        button#btnSubmit(type="submit") submit

Here we’re creating a form with the ID “formAddUser” (I like to preface my IDs with the type of thing we’re ID’ing. It’s a personal quirk). Method is post, action is adduser. Pretty straightforward. Under that we’ve defined our two inputs and our button.

If you restart your node server and go to http://localhost:3000/newuser you’ll see your form in all its glory.


Go ahead and submit. Enjoy the “can’t post to /adduser” error. We’re about to fix that.


OK, same process as before. First we edit app.js, then our route file, and then our Jade template. Except there’s no Jade template here because we’re posting and then forwarding. See below. It’ll all make sense! Let’s start: Open app.js and once again find your stack of app.get calls:

Now add the following at the bottom of the app.js:'/adduser', routes.adduser(db));

Note that that’s an, not an app.get. If you want to separate it from the app.gets with a comment or newline, I won’t stop you. Let’s set up our route.

Go back to /routes/index.js and let’s create our insertion function. This is a big one, so I’ve commented the code pretty thoroughly. Here it is:

exports.adduser = function(db) {
    return function(req, res) {

        // Get our form values. These rely on the "name" attributes
        var userName = req.body.username;
        var userEmail = req.body.useremail;

        // Set our collection
        var collection = db.get('usercollection');

        // Submit to the DB
            "username" : userName,
            "email" : userEmail
        }, function (err, doc) {
            if (err) {
                // If it failed, return error
                res.send("There was a problem adding the information to the database.");
            else {
                // If it worked, set the header so the address bar doesn't still say /adduser
                // And forward to success page


Assuming your server is running, which it should be, return to your web browser and point it at http://localhost:3000/newuser again. There’s our exciting form, just like before. Except now let’s fill in some values before we hit submit. I went with username “noderocks” and email “” … you can go with whatever you’d like.


It will redirect to userslist.


Reference :


Node js Web application Development Part 2



Here is the first part of this post. This post will demonstrate on how to connect your node js application into mongodb database.

Database :


Content :

 _id: ObjectId("52bbc6a47e197b1e8d00004a"),
 username: "testuser1",
 email: ""

Here is the modified app.js file

 * Module dependencies.

var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');

// New Code
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('mongodb://<username>:<password>');  // remote mongodb databse

//var db = monk('localhost:27017/nodeexpress1');   this is for the local db connections.

var app = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.cookieParser('your secret here'));
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' == app.get('env')) {

app.get('/', routes.index);
app.get('/users', user.list);
app.get('/userlist', routes.userlist(db));    // this will load the db data to html

http.createServer(app).listen(app.get('port'), function(){
 console.log('Express server listening on port ' + app.get('port'));

Now create userlist.jade as follows.

extends layout
block content
 User List
 each user, i in userlist
 a(href="mailto:#{}")= user.username

This will display the username with the attached link with email address.

Now run the app using node app.js command

Go to http://localhost:3000/userlist link. Here is the result



And this is how jade works.


doctype html
 title= pageTitle
 if (foo) {
 bar(1 + 5)
 h1 Jade - node template engine
 if youAreUsingJade
 p You are amazing
 p Get on it!
 Jade is a terse and simple
 templating language with a
 strong focus on performance
 and powerful features.

equivalent html file


<!DOCTYPE html>
<html lang="en">
 <script type="text/javascript">
 if (foo) {
 bar(1 + 5)
 <h1>Jade - node template engine</h1>
 <div id="container" class="col">
 <p>You are amazing</p>
 Jade is a terse and simple
 templating language with a
 strong focus on performance
 and powerful features.

cheers 🙂

Node js Web application Development Part 1



Nodejs  is a platform built on Chrome’s JavaScript runtime for easily building fast, scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.

This project will run on the node.js server with express and jade frameworks. The database is backed by mongodb :).

Installing nodejs.

This is really easy. Hit the Node.js website and click the big green Install button. It’ll detect your OS and give you the appropriate installer (if for some reason it doesn’t, click the downloads button and grab the one you need). Run the installer. That’s it, you have installed Node.js and, equally important, NPM – Node Package Manager – which lets you add all kinds of great stuff to Node quickly and easily.

  • Open a command prompt
  • cd to the directory in which you wish to keep your test apps
    (for the purposes of this example, C:\node).

Installing Express.

Express is a framework which is capable of turning the raw node into an application that behaves more like web servers.

To get express, type this command

C:\node>npm install -g express

This installs some core Express functionality right into our Node installation, making it available globally so we can use it anywhere we want. That’s handy. You’ll see a bunch of text in your command prompt, mostly a lot of http 304’s and GETs. That’s fine. Express is now installed and available.

Create an express project

We’re going to use Express and Jade, but not the Stylus CSS preprocessor (which people often use in this stack). We’re just going to use straight CSS for right now. We have to use Jade or another templating engine to gain access to our Node/Express-based data. Jade’s not hard to learn if you already know HTML. Just remember that you really have to pay attention to indentation or things will go badly wrong.

Anyway, still in c:\node or wherever you’re storing your node apps, type this:

C:\node>express –sessions nodetest1

This will generate something like this.

create : nodetest1
create : nodetest1/package.json
create : nodetest1/app.js
create : nodetest1/routes
create : nodetest1/routes/index.js
create : nodetest1/routes/user.js
create : nodetest1/views
create : nodetest1/views/layout.jade
create : nodetest1/views/index.jade
create : nodetest1/public/images
create : nodetest1/public/javascripts
create : nodetest1/public
create : nodetest1/public/stylesheets
create : nodetest1/public/stylesheets/style.css

install dependencies:
$ cd nodetest1 && npm install

run the app:
$ node app

Edit dependencies

open package.json according to this.

 "name": "application-name",
 "version": "0.0.1",
 "private": true,
 "scripts": {
 "start": "node app.js"
 "dependencies": {
 "express": "3.4.7",
 "jade": "*",
 "mongodb": "*",
 "monk": "*"

now do this command.

C:\node\nodetest1>npm install

Now run the application using following command.

C:\node\nodetest1>node app.js

Awesome! Open a browser and head for http://localhost:3000 where you will see a welcome to Express page.


Here is the sample Project on github.

JSP Custom Tags Example



A custom tag is a user-defined JSP language element. When a JSP page containing a custom tag is translated into a servlet, the tag is converted to operations on an object called a tag handler. The Web container then invokes those operations when the JSP page’s servlet is executed.

JSP tag extensions let you create new tags that you can insert directly into a JavaServer Page just as you would the built-in tags you learned about in earlier chapter. The JSP 2.0 specification introduced Simple Tag Handlers for writing these custom tags.

To write a customer tab you can simply extend SimpleTagSupport class and override the doTag()method, where you can place your code to generate content for the tag.

Create “Hello” Tag:

Consider you want to define a custom tag named <ex:Hello> and you want to use it in the following fashion without a body:

<ex:Hello />

To create a custom JSP tag, you must first create a Java class that acts as a tag handler. So let us create HelloTag class as follows:

package com.technodyne;

import javax.servlet.jsp.tagext.*;
import javax.servlet.jsp.*;

public class HelloTag extends SimpleTagSupport {

public void doTag() throws JspException, IOException {
 JspWriter out = getJspContext().getOut();
 out.println("Hello Custom Tag!");

Above code has simple coding where doTag() method takes the current JspContext object using getJspContext() method and uses it to send “Hello Custom Tag!” to the current JspWriter object.

Let us compile above class and copy it in a directory available in environment variable CLASSPATH. Finally create following tag library file: <Tomcat-Installation-Directory>webapps\ROOT\WEB-INF\custom.tld.

 <short-name>Example TLD</short-name>

Now it’s time to use above defined custom tag Hello in our JSP program as follows:

<%@ taglib prefix="ex" uri="WEB-INF/custom.tld"%>
 <title>A sample custom tag</title>

Try to call above JSP and this should produce following result:

Hello Custom Tag

Accessing the Tag Body:

You can include a message in the body of the tag as you have seen with standard tags. Consider you want to define a custom tag named <ex:Hello> and you want to use it in the following fashion with a body:

 This is message body

Let us make following changes in above our tag code to process the body of the tag:

package com.technodyne;

import javax.servlet.jsp.tagext.*;
import javax.servlet.jsp.*;

public class HelloTag extends SimpleTagSupport {

StringWriter sw = new StringWriter();
 public void doTag()
 throws JspException, IOException


In this case, the output resulting from the invocation is first captured into a StringWriter before being written to the JspWriter associated with the tag. Now accordingly we need to change TLD file as follows:

 <short-name>Example TLD with Body</short-name>

Now let us call above tag with proper body as follows:

 <%@ taglib prefix="ex" uri="WEB-INF/custom.tld"%>
 <title>A sample custom tag</title>
 This is message body

This will produce following result:

This is message body

Adding multiple markers and infoWindows to Google Map


First create your html page.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">

<html xmlns="">
 <title>Google Maps Example</title>
 <script src='' type='text/javascript'></script>
<script type="text/javascript" src=""></script>
<script type="text/javascript" src="map.js"></script>
<div id="map_canvas" style="width: 600px; height: 600px;"></div>

Now add the following javaScript.


var infowindow = null;
$(document).ready(function () { initialize(); });

function initialize() {

var centerMap = new google.maps.LatLng(39.828175, -98.5795);

var myOptions = {
zoom: 4,
center: centerMap,
mapTypeId: google.maps.MapTypeId.ROADMAP

var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

setMarkers(map, sites);
infowindow = new google.maps.InfoWindow({
content: "loading..."

//var bikeLayer = new google.maps.BicyclingLayer();

var sites = [
['Mount Evans', 39.58108, -105.63535, 4, 'This is Mount Evans.'],
['Irving Homestead', 40.315939, -105.440630, 2, 'This is the Irving Homestead.'],
['Badlands National Park', 43.785890, -101.90175, 1, 'This is Badlands National Park'],
['Flatirons in the Spring', 39.99948, -105.28370, 3, 'These are the Flatirons in the spring.']

function setMarkers(map, markers) {

for (var i = 0; i < markers.length; i++) {
var sites = markers[i];
var siteLatLng = new google.maps.LatLng(sites[1], sites[2]);
var marker = new google.maps.Marker({
position: siteLatLng,
map: map,
title: sites[0],
zIndex: sites[3],
html: sites[4]

var contentString = "Some content";

google.maps.event.addListener(marker, "click", function () {
infowindow.setContent(this.html);, this);

This is the output.

Google Map

Unit testing with JUnit



unit test is a piece of code written by a developer that executes a specific functionality in the code which is tested. The percentage of code which is tested by unit tests is typically called test coverage.

Unit tests target small units of code, e.g. a method or a class, (local tests) whereas component and integration tests targeting to test the behavior of a component or the integration between a set of components or a complete application consisting of several components.

Unit tests ensure that code works as intended. They are also very helpful to ensure that the code still works as intended in case you need to modify code for fixing a bug or extending functionality. Having a high test coverage of your code allows you to continue developing features without having to perform lots of manual tests.

Typically unit tests are created in their own project or their own source folder to avoid that the normal code and the test code is mixed.

To integrate the unit testing to your application you need to use unit testing library. Here are couple of annotations used in the unit testing.

Annotation Description
public void method()
The annotation @Test identifies that a method is a test method.
public void method()
This method is executed before each test. This method can prepare the test environment (e.g. read input data, initialize the class).
public void method()
This method is executed after each test. This method can cleanup the test environment (e.g. delete temporary data, restore defaults). It can also save memory by cleaning up expensive memory structures.
public static void method()
This method is executed once, before the start of all tests. This can be used to perform time intensive activities, for example to connect to a database. Methods annotated with this annotation need to be defined as static to work with JUnit.
public static void method()
This method is executed once, after all tests have been finished. This can be used to perform clean-up activities, for example to disconnect from a database. Methods annotated with this annotation need to be defined as static to work with JUnit.
@Ignore Ignores the test method. This is useful when the underlying code has been changed and the test case has not yet been adapted. Or if the execution time of this test is too long to be included.
@Test (expected = Exception.class) Fails, if the method does not throw the named exception.
@Test(timeout=100) Fails, if the method takes longer than 100 milliseconds.


JUnit provides static methods in the Assert class to test for certain conditions. These assertion methods typically start with asserts and allow you to specify the error message, the expected and the actual result. An assertion method compares the actual value returned by a test to the expected value, and throws an AssertionException if the comparison test fails.

The following table gives an overview of these methods. Parameters in [] brackets are optional.

Statement Description
fail(String) Let the method fail. Might be used to check that a certain part of the code is not reached. Or to have a failing test before the test code is implemented.
assertTrue([message], boolean condition) Checks that the boolean condition is true.
assertsEquals([String message], expected, actual) Tests that two values are the same. Note: for arrays the reference is checked not the content of the arrays.
assertsEquals([String message], expected, actual, tolerance) Test that float or double values match. The tolerance is the number of decimals which must be the same.
assertNull([message], object) Checks that the object is null.
assertNotNull([message], object) Checks that the object is not null.
assertSame([String], expected, actual) Checks that both variables refer to the same object.
assertNotSame([String], expected, actual) Checks that both variables refer to different objects.

Lets create a simple java application with the Junit integration.

First create the class which should be tested.

package com.vogella.junit.first;

public class MyClass {

public int multiply(int x, int y){

 throw new IllegalArgumentException("X should be less than 1000");

 return x*y;

Then create a separate source folder to place the unit testing class to the application. This can be added by New->Junit class option in the eclipse.

package com.vogella.junit.first;

import static org.junit.Assert.*;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

public class MyClassTest {

 public static void testSetup() {


 public static void testCleanup() {

 public void testExceptionIsThrown(){
 MyClass tester = new MyClass();
 tester.multiply(1000, 5);

 public void testMultiply() {
 MyClass tester = new MyClass();
 assertEquals("10 x 5 must be 50", 50, tester.multiply(10, 5));


Now run the application as a junit test.


These results show that the functionalities are working properly.

Developing Web Services Using Apache Axis2


These are the tools used in the tutorial.

1) Java Development Kit 1.4.2.x (Download)

2) Eclipse SDK 3.2.x (Download)

3) Apache Tomcat 4.1.x (Download)

4) Axis2 Web Application (Download)

5) Axis2 Eclipse Plugins (Download)

First download this two eclipse plugins and place them inside the dropins folder in eclipse. Other than the two plugins, we need the Axis2 runtime to deploy the developed Web services. We use the Axis2 Web Application which can be deployed in any popular servlet container. (You can download the Axis2 Web Application from the Axis2 Download page.) You have to just place it in the repository of the servlet container and run it. For example, if you are using Apache Tomcat, just copy the downloaded .war file, put it in the webapp folder, and start the servlet container.

PART 1 – The Bottom Up Approach in Web Services Development Using the Apache Axis2 Eclipse Plugin

  1. Start Eclipse SDK. First we need to create a JAVA project in Eclipse. (Follow the instruction on Eclipse SDK help.) You can give any name to the JAVA project, but for clarity, let us create a JAVA project called “TemperatureWebService”.In the Bottom Up Approach, we start with the service implementation and then build the deployable Web service component. We will be using the TemperatureConverter class definition as the logic for developing, deploying, and testing the Web service.
  2. Create a custom package ws.example appropriately and include the file in that package. Compile and build the project.
    package ws.example;
     * Temperature Converter Implementation Class
    public class TemperatureConverter {
     * util method to convert Celsius to Fahrenheit
     * @param cValue : double value of celsius
     * @return calculated value of fahrenheit
     public double c2fConvertion(double cValue) {
     return ((cValue * 9.0)/5.0 )+ 32.0;
     * util method to convert fahrenheit to celsius
     * @param fValue : double value of fahrenheit
     * @return calculated value of celsius
     public double f2cConvertion(double fValue) {
     return ((fValue - 32.0) * 5.0) / 9.0;
  3.  After successfully building the project, we will create the service archive using the Axis2 Eclipse Service Archiver Plugin. On the File menu, click New and then click Other to access the Axis2 wizards. Else, you can press Ctrl+N.
    Note : At any given time, you can go back through the wizards, change the settings, and even start the wizards all over again to create a different Web service on another JAVA project available in your workspace.image001
  4. Select the Axis2 Service archiver and click Next. You will see the Axis2 service definition selection page.image002On this page, select the output location of the “TemperatureWebService” Java project that we previously developed. Here we point to the service implementation classes. If there is more than one class, you only have to point to the JAVA project build location. The wizard includes all the implementation files. To be on the safe side, if you are going to expose a complex project as a Web service, it’s better to select the include .class files check box to omit unnecessary resource files that will increase the size of the deployable service archive that we are going to create.
  5. After selecting the correct output location, click Next.After selecting the correct output location, click Next.image003
    On this page, you can browse for the WSDL file. If you do not want to add a WSDL file to the service archive, select the Skip WSDL check box. Else you can select the Select WSDL check box, and specify the location of the WSDL file. We will skip the WSDL for the moment.
  6. Click NEXT
    image004This page is to add the libraries. The library name (with the full path) can be specified by either typing it or browsing for it. Once the library name with the full path is entered, click Add to add the library to the list. The added libraries should be displayed in the Added libraries list. You can add as many external libraries as you wish.If any added library has to be removed, select it from the Added libraries list and click Remove.
  7. For this example, we do not need any external libraries added to the generated service. Therefore, click Next to proceed to the next stepimage005This page is about the services.xml generation. If you have a custom services.xml file, you can select the services.xml file on this page by browsing for it or you can generate the service XML automatically. The browsing option is disabled when the Generate service xml automatically check box is selected.
  8. For this example, we use the automatically generated services.xml rather than a custom written one. Therefore, select the Generate service xml automatically check box, and then click Next.image006
    Note that this page will appear only if you selected to generate the services.xml automatically in the previous step. (If you selected a services.xml file, then you will be directed to the last page of the wizard.) After entering the correct service name and a valid fully qualified class name, load the existing methods of that class by clicking Load. If it is successfully loaded, you will see a table at the bottom of the page with the details of the loaded class. You can specify the methods to include in the services.xml by selecting the corresponding check boxes.
  9. Select the Search declared method only check box, to remove the inherited methods from the class. We do not need the inherited methods to be exposed and our only interest is in temperature conversion logic. Click Next to proceed to the last page of the wizard.image007
    On the last page of the wizard, specify the output file location and the output archive file name to complete the wizard. Note the location given in the example above. After specifying a name to identify the service that we will be deploying, we can directly guide the wizard to deploy this newly created Web service on any available Web service repository.Since we already have the Apache Axis2 Web application deployed on the servlet container, we can easily guide the wizard to deploy the service in the Axis2 Webapp (Axis2.war) inside Apache Tomcat. After deploying the Web application, the service repository will be available in the <TOMCAT_HOME>/webapp/axis2/WEB-INF/services folder.
  10. Click Finish to complete the steps in the wizard.
  11. Start the servlet container (in this case the Apache Tomcat), and navigate to http://localhost:8080/axis2 This will lead to the Axis2 Web application home page.image_b001image_b002