From trainee to manager!

My last attempt in reciting a poem is something I would like to forget. I just couldn’t recollect the lines and ended up making a mess of the content. In spite of what transpired that day, I couldn’t stop but pen down the same poem. So here goes the final piece,

The day I walked across that gate,
It was time to put to test my fate,
As I stood there with my baggage in hand,
I remembered my parents, my friends and my homeland.

The long training program began with tests every week and results in a minute,
We realized its no longer about individuals but more of team spirit,
As the end drew near, increased our frustration,
Some enjoyed the celebration while some remained concerned about allocation!!

So after those years today here I am,
I own a cool phone and an expensive cam,
As I manager I have nothing to lose,
We celebrate each success with a party, that but obvious includes booze.

But then one fine day everything fell apart,
We couldn’t keep pace with that deadline chart,
We realized that when life really puts you to test,
It’s then that you need to come out and give your BEST – since that is what we promise!!

success_and_failure

Tutorial #99: Send e-mail using JavaMail in JSP

Hi everyone!

JavaMail is a well known Java API used to send and receive email via SMTP, POP3 and IMAP. It mainly provides a platform-independent and protocol-independent framework to build mail and messaging applications. In addition, the JavaMail API package is also included in the Java EE platform.

JavaMail facilitates the sending of an e-mail via Gmail SMTP server, using both TLS and SSL connection. Through this tutorial, we will learn how to send an e-mail using JavaMail in a sample JSP page.

Pre-requisites: Eclipse IDE for Java EE developers, Apache Tomcat 7

Step 1: Create new Dynamic web project

Launch Eclipse IDE and create a new Dynamic web project called SendEmailUsingJSP with target runtime as Apache Tomcat 7.

Step 2: Add external jar files

In order to implement the sending of an e-mail, developers need to download and use the latest version of the JavaMail API in their web projects. For this tutorial, I will be using the mail-1.4.7.jar version of the JavaMail API. Make sure you add the .jar file in the WEB-INF/lib folder of your web project.

Step 3: Create JSP page

Create a new index.jsp page inside the WebContent folder of your web project and write the following code.

index.jsp

<%@ pageimport="javax.servlet.http.*,javax.servlet.*" %>
<%@ page import="javax.mail.internet.*,javax.activation.*"%>
<%@ page import="java.io.*,java.util.*,javax.mail.*"%>
<%

    //username for abc@gmail.com will be "abc"
	String username = "sender_username";
	String password = "sender_password";
	String result = null;

	try {
		
        Properties props = System.getProperties();
		props.setProperty("mail.transport.protocol", "smtp");
		props.setProperty("mail.host", "smtp.gmail.com");
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.port", "465");
		props.put("mail.debug", "true");
		props.put("mail.smtp.socketFactory.port", "465");
		props.put("mail.smtp.socketFactory.class",
				"javax.net.ssl.SSLSocketFactory");
		props.put("mail.smtp.socketFactory.fallback", "false");

		Session emailSession = Session.getInstance(props,
				new javax.mail.Authenticator() {
					protected PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication("sender_username","sender_password");
				}
		});

		emailSession.setDebug(true);
		Message message = new MimeMessage(emailSession);
		message.setFrom(new InternetAddress(
				"sender_username@gmail.com"));
		message.setRecipients(Message.RecipientType.TO,
				InternetAddress.parse("xyz@hotmail.com"));
		message.setSubject("Test mail from Java");
		message.setText("Hello. this is a test");

		Transport transport = emailSession.getTransport("smtps");
		transport.connect("smtp.gmail.com", username, password);
		transport.sendMessage(message, message.getAllRecipients());

		result = "Successfully sent email";

	   } catch (MessagingException e) {
		result = "Unable to send email";
	}
%>
<html>
<head>
<title>Send Email using JSP</title>
</head>
<body>
	<center>
		<h1>Send Email using JSP</h1>
	</center>
	<p align="center">
		<%
			out.println("Result: " + result + "\n");
		%>
	</p>
</body>
</html>

Finally, save all changes and run the application on the Tomcat server. If no errors occur then you should see the following output!

output

Reference: JavaMail API

Tutorial #98: Calling web services using PL/SQL in Oracle

Web services are widely used to as a means of communication between two multiple devices. Oracle also allows developers to consume web services using certain built-in packages. Moreover, one can extend a relational database’s storage, indexing, and searching capabilities to include web services. Through this tutorial, we will learn how to call a simple web service using PL/SQL in Oracle. We would using a public testing platform for services utilizing JavaScript Object Notation (JSON).

Pre-requisites: Oracle 11gR2 database with *SQLPlus, Windows 7 (64 bit)

Step 1: Writing the PL/SQL query

Open the SQL Plus command prompt and login using your database credentials. Once logged in successfully execute the following command in order to enable DBMS_OUTPUT statements.

set serveroutput on

In order to call web services, Oracle provides the UTL_HTTP package. It helps make hyper-text transfer protocol (HTTP) callouts from PL/SQL and SQL. One can use it to access data on the Internet or to call Oracle Web Server cartridges. We would be creating a stored procedure to use the same. Our PL/SQL procedure would be as follows,

create or replace procedure call_webservice as
  t_http_req  utl_http.req;
  t_http_resp  utl_http.resp; 
  t_response_text VARCHAR2 (2000);

begin
 
  t_http_req:= utl_http.begin_request('http://date.jsontest.com/','GET','HTTP/1.1');
  t_http_resp:= utl_http.get_response(t_http_req);
  UTL_HTTP.read_text(t_http_resp, t_response_text);
  DBMS_OUTPUT.put_line('Response> status_code: "' || t_http_resp.status_code || '"');
  DBMS_OUTPUT.put_line('Response> reason_phrase: "' ||t_http_resp.reason_phrase || '"');    
  DBMS_OUTPUT.put_line('Response> data:' ||t_response_text); 
  utl_http.end_response(t_http_resp);
 
end;

create_procedure

Step 2: Executing the PL/SQL query

Now, execute the above PL/SQL procedure using the below command,

exec call_webservice

Once the procedure has executed successfully you will see the following output,

execute_procedure

Reference: UTL_HTTP in Oracle

Tutorial #97: Generate multi-language PDF using iText in Java

Hi everyone,

iText is a PDF software that can be used to create PDF documents dynamically using Java, .NET, Android etc. Based on the comments I received of late, iText can be used to generate multi-language PDF documents for Java, web and other applications.

iTextG is a special version of iText built for Android and Google App Engine.

Differences between the iText core library and the Android/GAE port are as follows,

1. iTextG uses SpongyCastle instead of Bouncy Castle. Make sure to download and include the right jars namely scprov-jdk15on and scpkix-jdk15on.

2. References to any of the classes not on the Google App Engine whitelist have been removed.

Through this tutorial, we will learn how to generate a multi-language PDF using the iText library in Java.

Pre-requisites: Eclipse IDE, Windows 7 (64 bit), iText software ( itext-2.1.7.jar)

Launch Eclipse IDE and create a new Java console application project called JavaPDFGeneration with package name com.app.generate. Create a new Java class called GeneratePDF and add the following code!

GeneratePDF.java

package com.app.pdfgenerate;

import java.io.FileOutputStream;
import com.lowagie.text.Chunk;
import com.lowagie.text.Document;
import com.lowagie.text.Font;
import com.lowagie.text.FontFactory;
import com.lowagie.text.HeaderFooter;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;

public class GeneratePDF {
	
    public static void main(String arg[]) throws Exception {
              
       try {
                       
            Document document = new Document();
			String encoding = "Identity-H";
			Font fontNormal = FontFactory.getFont(("F:/programs/pdf/fonts/Roboto-Black.ttf"), encoding,BaseFont.EMBEDDED, 8, Font.NORMAL);
			PdfWriter.getInstance(document, new FileOutputStream("F:/programs/pdf/test.pdf"));
			HeaderFooter header = new HeaderFooter(new Paragraph("Header", fontNormal), false);
			HeaderFooter footer = new HeaderFooter(new Paragraph("footer", fontNormal), false);
			document.setHeader(header);
			document.setFooter(footer);
			document.open();

			Chunk chunkEnglish = new Chunk("Hello World " + "\n", fontNormal);
			Chunk chunkBrazil = new Chunk("Olá Mundo " + "\n", fontNormal);

			PdfPTable table = new PdfPTable(2);
			table.addCell("Locale");
			table.addCell("Translated Text");

			PdfPCell cellEnglish = new PdfPCell(new Phrase(chunkEnglish));
			table.addCell(new PdfPCell(new Phrase(new Chunk("English",fontNormal))));
			table.addCell(cellEnglish);

			PdfPCell cellBrazil = new PdfPCell(new Phrase(chunkBrazil));
			table.addCell(new PdfPCell(new Phrase(new Chunk("Brazil",fontNormal))));
			table.addCell(cellBrazil);

			document.add(table);
			document.close();

			System.out.println("PDF generation complete....");
	
		  } catch (Exception e) {
			System.out.println("Error occurred while generating PDF" + e.getMessage());
			e.printStackTrace();
	      }
   }
}

Save all changes and run the application. If no errors occur then you should see the PDF file (test.pdf) created in the specified output directory.

output

Reference: iText library

Tutorial #96: Implement multi-language support in Android

Hey friends!

Today, Android has become one of the dominant mobile operating systems in the world. Android applications are now used by people living across the globe. It is important for developers to build applications that can support multiple languages. In order to reach maximum users, an application should handle text, audio files, numbers, currency, and graphics in ways appropriate to the locales where it will be used.

By default Android considers English as the primary language and loads the string resources from res/values/strings.xml file. In order to add support for another language, one needs to create a values folder by appending an hyphen and the ISO language code. For example if you want to add support for French, you should create a values folder named values-fr and keep a strings.xml file in it with all the strings translated into French language.

As mentioned on the developer’s page, it’s always a good practice to extract UI strings from your application code and keep them in an external file. Through this tutorial, we will learn how to implement multi-language support in Android.

Pre-requisites: Eclipse IDE, Android SDK

Step 1: Create Android project

Launch Eclipse IDE and create a new Android application project called AndroidMultiLanguageSupportDemo. Let’s keep the package name as com.app.multilanguage. Choose the target SDK as Android 4.4 (API level 19)

Step 2: Add multi-language support

As mentioned earlier, we need to create multiple values folder for the appropriate language depending on the language code as follows!

res/values/strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello_world">Hello world!</string>
</resources>

res/values-fr/strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
   <string name="hello_world">bonjour le monde!</string>
</resources>

MainActivity.java

package com.app.multilanguage;

import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}
}

res/layout/activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="${relativePackage}.${activityClass}">

    <TextView
        android:id="@+id/txtView"
        android:layout_centerInParent="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="24sp"
        android:textColor="#FE2E2E"
        android:text="@string/hello_world" />

</RelativeLayout>

Finally, save all changes. Make sure no errors are present. Run the application on an Android device and you should see the following output for the respective languages.

English

English

Japanese

Japanese

Hindi

Hindi

French

French

That’s it for this tutorial. Hope it helps! :)

Reference: Supporting different languages

Tutorial #95: Resolving the Dalvik compiler limitation on 65K methods

Hello everyone!

In previous versions of the Android operating system, as applications grew in size one would encounter build errors that would indicate that the application has reached a limit of the Android application build architecture. The error would be as follows,

Conversion to Dalvik format failed:
Unable to execute dex: method ID not in [0, 0xffff]: 65536

If you observe the error closely, it specifies the number 65536. As mentioned on the developer’s page, this number is significant as it represents the total number of references that can be invoked by the code within a single Dalvik Executable (dex) bytecode file.

Developers hence need to resolve this error by adding multidex support to their application. From Android 5.0 (Lollipop) onwards, Android uses a runtime called ART which natively supports loading multiple dex files from application APK files. However, through this tutorial, we will learn one of the ways to resolve the Dalvik compiler limitation in previous (older) versions of Android.

Pre-requisites: Android Studio (version 1.0.0-rc4), Gradle plugin (version 2.2.1), latest Android SDK (with build tools installed for version 21)

Step 1: Configure application to add multidex support

Launch the Android Studio IDE and open any of your existing Android projects that contain more than 65K methods due to external libraries (.jar) files. Open the build.gradle file of your project and add the following lines of code,

apply plugin: 'com.android.application'
....
....

    compileSdkVersion 21
    buildToolsVersion '21.1.1'

    defaultConfig {
        applicationId "com.app.multidex"
        minSdkVersion 19
        targetSdkVersion 20
        versionCode 1
        versionName "1.0"

        // Enabling multidex support.
        multiDexEnabled true
    }
    buildTypes {
        release {
            runProguard true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile 'com.android.support:multidex:1.0.0'
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile files('libs/my_large_file1.jar')
    compile files('libs/my_large_file2.jar')
}

As seen above, it is important to specify the multiDexEnabled setting in the defaultConfig, buildType, or productFlavor sections of your Gradle build file. In addition, one needs to add the multidex support library as a dependency in the dependencies section.

Step 2: Edit AndroidManifest.xml file

In the manifest file one needs to add the MultiDexApplication class from the multidex support library to the application element as follows,

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.app.multidex">
    <application
        ...
        android:name="android.support.multidex.MultiDexApplication">
        ...
    </application>
</manifest>

Finally, save all changes. Make sure no errors are present. Once the project has compiled successfully the Android build tools construct a primary dex (classes.dex) and supporting (classes2.dex, classes3.dex) as needed.

multidex_support_android

Alternatively, one can also use an opensource GitHub project that when downloaded provides a custom_rules.xml build script that can be easily integrated in any Android application.

Reference: Building apps with over 65K methods

Tutorial #94: Using Retrofit for Android

Hello friends!

In one of my previous tutorials, I had talked about using the Volley networking library in Android. However, Volley is less documented and is totally focused on handling individual, small HTTP requests.

Retrofit on the other hand makes it incredibly easy to download JSON or XML data from a web API and parse it into a Plain Old Java Object (POJO). It’s released by Square and offers very easy to use REST API’s. Through this tutorial, we will learn how to use Retrofit for Android.

Pre-requisites: Eclipse IDE, Android SDK

Step 1: Create Android project

Create a new Android application project called AndroidRetrofitExample with package name com.app.retrofit. Choose the target SDK as Android 4.4 (API level 19)

Step 2: Create REST service interface

Create a new interface called GithubApiService that will help fetch the list of contributors for a particular repository as follows,

GithubApiService.java

package com.app.retrofit;

import java.util.List;
import retrofit.http.GET;
import retrofit.http.Path;

public interface GithubApiService {
	@GET("/repos/{owner}/{repo}/contributors")
	List<Contributor> contributors(
			@Path("owner") String owner,
			@Path("repo") String repo
	);
}

Step 3: Create Activity class

Now, let’s implement our MainActivity class. We will create an AsyncTask in order to call the public Github API service.

MainActivity.java

package com.app.retrofit;

import java.util.List;
import retrofit.RestAdapter;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		new GetUserInfo().execute();
	}

	private class GetUserInfo extends AsyncTask<String, Void, String>{

		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub	
			try{ 
				RestAdapter restAdapter = new RestAdapter.Builder()
				.setEndpoint("https://api.github.com") 
				.build();

				GithubApiService github = restAdapter.create(GithubApiService.class);
				List<Contributor> contributors = github.contributors("pscholl", "glass_snippets");

				for (Contributor contributor : contributors) {
					Log.i("App", contributor.login + " - " + contributor.contributions);
				}

			}catch(Exception e){
				e.printStackTrace();
				return "failure";
			}	
           return "success";
	    }
      }
}

The RestAdapter is the class through which your API interfaces are turned into callable objects. By default, Retrofit will give you sane defaults for your platform but it allows for customization.

Contributor.java

package com.app.retrofit;

//POJO class
public class Contributor {
	
	// GitHub username
	public String login; 
	// Commit count
	public int contributions;
	
	public String getLogin() {
		return login;
	}
	public void setLogin(String login) {
		this.login = login;
	}
	public int getContributions() {
		return contributions;
	}
	public void setContributions(int contributions) {
		this.contributions = contributions;
	} 
}

Note: Make sure you have added the android.permission.INTERNET feature in the AndroidManifest.xml file. One also needs to add the following .jar files in the libs folder of the Android project.

  • retrofit-1.4.1.jar
  • okhttp-1.3.0-jar-with-dependencies.jar
  • gson-2.2.4.jar

Finally, save all changes. Make no errors are present. Run the application on an Android device and you should the following output in the Logcat window!

output

That’s it for this tutorial. Stay tuned for more! :)

Reference: Retrofit for Android

A date with Java 8!

[This is a long overdue post…]

Hello everyone!

Java is a pure object oriented programming language. Over the years, there have been many enhancements including some of the features like Annotations, Generics etc. Prior to Java 8, it was difficult to pass plain methods as arguments. Java 8 helps overcome this limitation by introducing a new feature called Lambda expressions. This addition to the language brings Java in line with other functional JVM-based languages such as Scala and Clojure.

Java 8 has introduced a lot more features including parallel operations, new date/time API’s, internationalization, concurrency etc. Through this post, we will learn how to implement two of the new features in Java 8 with the help of sample programs.

Pre-requisites: Java SE Development Kit 8, Notepad

1. Lambda expressions

Lambda Expressions, a new language feature, has been introduced in this release. They enable you to treat functionality as a method argument, or code as data. Lambda expressions let you express instances of single-method interfaces (referred to as functional interfaces) more compactly.

Create a new Java file called JavaEightTest and write the following code!

JavaEightTest.java

import java.io.*;
import java.lang.*;
import java.util.*;

public class JavaEightTest{

   public static void main(String args[]){
       
      //the old way 
      List<String> names = Arrays.asList("orange", "apples", "grapes", "bananas");
      Collections.sort(names, new Comparator<String>() {
              @Override
              public int compare(String a, String b) {
               return b.compareTo(a);
              }
      });

      //the new way
      Collections.sort(names, (String a, String b) -> b.compareTo(a));

      new Thread(
            () -> System.out.println("Hello from thread")
      ).start();

    }
}

2. Date/Time API’s

The Date-Time APIs, introduced in JDK 8, are a set of packages that model the most important aspects of date and time. The core classes in the java.time package use the calendar system defined in ISO-8601 (based on the Gregorian calendar system) as the default calendar. Other non-ISO calendar systems can be represented using the java.time.chrono package.

Create a new Java file called JavaEightDate and write the following code!

JavaEightDate.java

import java.time.LocalDate;
import java.time.Month;
import java.time.ZoneId;
 
public class JavaEightDate {
 
    public static void main(String[] args) {
         
        //show the current date
        LocalDate today = LocalDate.now();
        System.out.println("Current Date is="+today);
         
        //create LocalDate 
        LocalDate firstDay_2014 = LocalDate.of(2014, Month.JANUARY, 1);
        System.out.println("Specific Date="+firstDay_2014);
                  
        //current date in a specific zone, say "Asia/Kolkata"
        LocalDate todayKolkata = LocalDate.now(ZoneId.of("Asia/Kolkata"));
        System.out.println("Current Date in IST="+todayKolkata);
     
        //getting date from the base date i.e 01/01/1970
        LocalDate dateFromBase = LocalDate.ofEpochDay(365);
        System.out.println("365th day from base date= "+dateFromBase);
       
    }
}

Finally, save all changes. Compile the above Java class using the javac command. If no errors occur then you should see the following output!

output

Reference: What’s New in JDK 8?

Tutorial #93: Implement CardView in Android

Hello everyone!

Prior to Android 5.0 Lollipop, developers would use open source libraries in order to implement a Card based view in Android. However, the latest release of Android now provides a CardView widget to show information inside cards that have a consistent look across the platform. In general, CardView widgets can have shadows and rounded corners.

As mentioned on the developer’s page, in order to create a card with a shadow, one can use the card_view:cardElevation attribute. CardView uses real elevation and dynamic shadows on Android 5.0 (API level 21) and above and falls back to a programmatic shadow implementation on earlier versions. Through this tutorial, we will learn how to implement a CardView in Android.

Pre-requisites: Eclipse IDE, Android SDK 5.0

Step 1: Create Android project

Launch the Eclipse IDE and create a new Android application project called AndroidLollipopNewExamples with package name com.app.lollipop.test. Let the target SDK be Android 5.0 (API level 21)

Step 2: Create Card layout

Now, let’s create our card layout using XML. Create a new XML file called activity_cardview and add the following code!

activity_cardview.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:gravity="center_horizontal"
    android:layout_height="match_parent">

    <android.support.v7.widget.CardView
        xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:id="@+id/card_view"
        android:layout_marginTop="20dp"
        android:layout_width="200dp"
        android:layout_height="100dp"
        card_view:cardCornerRadius="8dp"
        card_view:cardBackgroundColor="#C92A2A">

        <TextView
            android:id="@+id/info_text_header"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="@string/sample_text_header" />

        <ImageView
            android:id="@+id/info_image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:contentDescription="@string/sample_text_image"
            android:layout_gravity="center"
            android:layout_marginTop="2dp"
            android:src="@drawable/ic_launcher" />

        <TextView
            android:id="@+id/info_text_footer"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:paddingTop="80dp"
            android:text="@string/sample_text_footer" />
    </android.support.v7.widget.CardView>

</LinearLayout>

To set the corner radius in your layouts, use the card_view:cardCornerRadius attribute. To set the corner radius in your Java code, use the CardView.setRadius method. Finally, in order to set the background color of a card, use the card_view:cardBackgroundColor attribute.

strings.xml

<resources>
    <string name="app_name">AndroidLollipopNewExamples</string>
    <string name="sample_text_header">Sample card header</string>
    <string name="sample_text_footer">Sample card footer</string>
    <string name="sample_text_image">Sample image</string>
</resources>

Step 3: Create Activity class

Our Activity class called TestCardActivity would be as follows,

TestCardActivity.java

package com.app.lollipop.test;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;

public class TestCardActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_cardview);
	}	
}

No changes are to be made to the AndroidManifest.xml file. Run the application on an emulator and you should see the following output!

output

Reference: Creating Cards in Android

AngularJS: Routing

In any web application, navigation is crucial. If users can’t navigate through your application easily, you will quickly lose them. AngularJS provides an out of the box service provider called $routeProvider. Through AngularJS, developers can use routes to create different URLs for different content in an application.

As mentioned in the documentation, the routing functionality in Angular is due to the ngRoute module, which is distributed separately from the core Angular framework. The application’s module needs to declare this dependency in order to use the features provided by the ngRoute module. Through this post, we will learn how to implement routing using AngularJS.

Pre-requisites: Eclipse IDE (for Java EE developers), Apache Tomcat

Step 1: Launch Eclipse IDE and create a new Dynamic Web Project called AngularRouting. Choose the target runtime as Apache Tomcat 7.0

Step 2: Create HTML page

Create a new HTML page called index.html and place it inside the WebContent folder of your web project. In order to implement routing, the first thing to do is add the extra JavaScript inside the head section as follows!

index.html

....
  <head>
    <title>AngularJS Routing tutorial </title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular-route.min.js"></script>
  </head>
....

Next, let’s implement our $routeProvider. The $routeProvider is configured in the module’s config() function via calls to the when() and otherwise() functions.

index.html

....
var app = angular.module("demo",['ngRoute']);
app.config(['$routeProvider',
		  function($routeProvider) {
			$routeProvider.
				when('/ShowResult/:id', {
					templateUrl: 'templates/show_result.html',
					controller: 'ShowResultController'
				}).
				otherwise({
					redirectTo: '/'
				});
		}]);
....

We also need to register the ShowResultController and hence navigate to the new page depending upon the request parameter (in this case id). Here’s how our HTML page finally looks,

index.html

<!DOCTYPE html>
<html ng-app="demo">
  <head>
    <title>AngularJS Routing tutorial </title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
	<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular-route.min.js"></script>
  </head>
  <body>
	
	<div ng-controller="TableController">

	    <h2>Student data</h2>
		
		<table>
		    <tr>
			  <th> Id </th>
			  <th> Name </th>
			  <th> Age </th>
			  <th> Email </th>
			  <th> City </th>
			  <th> Action </th>
			</tr>
		   <tr ng-repeat="student in students">
		      <td>{{ student.id }} </td>
		      <td>{{ student.name | uppercase}} </td>
			  <td>{{ student.age }} </td>
			  <td>{{ student.email | lowercase }} </td>
		      <td>{{ student.city | uppercase}} </td>
			  <td> <a href="#ShowResult/{{student.id}}">Show Result</a></td>
		  </tr>	   
		</table>
	 	
		<div ng-view></div>

		
	</div>

	<script type="text/javascript">
		
		var app = angular.module("demo",['ngRoute']);
		app.controller("TableController", function($scope){
		    $scope.students = [
				{ id:"101", name: 'Hari', city: 'Mumbai', email:'hari@gmail.com',age:'16'},
				{ id:"102", name: 'Alexander', city: 'Paris', email:'alex@gmail.com',age:'18'}
			];
		});
		
		app.config(['$routeProvider',
		  function($routeProvider) {
			$routeProvider.
				when('/ShowResult/:id', {
					templateUrl: 'templates/show_result.html',
					controller: 'ShowResultController'
				}).
				otherwise({
					redirectTo: '/'
				});
		}]);
		
		app.controller('ShowResultController', function($scope, $routeParams) {
		    $scope.id = $routeParams.id;
		    
		    if($scope.id == 101){
		    	$scope.message = 'The result for student is passed';
		    }else{
		    	$scope.message = 'The result for student is failed';
		    }
		});
	
	</script>
	
  </body>
</html>

Important: Notice the ngView directive in the above page. Inside the div with the ngView directive (can also be written ng-view) the HTML template specific to the given route will be displayed.

show_result.html

<h2>Show Result</h2>
 
{{ message }}

Finally, save all changes and make sure no errors are present. Run the application on the Tomcat server and you should see the following output!

output

Reference: Routing in AngularJS