Monday, December 28, 2020

Lazy Initialization in Spring Using lazy-init And @Lazy Annotation

In Spring framework, by default all the singleton beans are eagerly created and configured by ApplicationContext as part of the initialization process. Though this behavior of pre-instantiation is desirable most of the time as you can detect errors in the configuration immediately. But sometimes you may have a large object graph and loading all those beans in the beginning itself may be expensive. In that kind of scenario you can prevent pre-instantiation of a singleton bean by configuring the Spring bean to be initialized lazily.

If you mark a bean as lazy-initialized in Spring that means IoC container will create a bean instance when it is first requested, rather than at startup.

Here note that when a lazy-initialized bean is a dependency of a singleton bean that is not lazy initialized, the ApplicationContext creates the lazy-initialized bean at startup, because it must satisfy the singleton’s dependencies.

Saturday, December 26, 2020

Injecting Inner Beans in Spring

This post shows how to inject inner beans in Spring and what are the scenarios when you would need to inject a bean as an inner bean.

Let’s say you have a Java class which refers to another class object and the access type for that object is private. In that case what do you think is the best way to provide bean definition in Spring. Let me provide class (Employee.java) here so you can understand what I am saying.

Friday, December 25, 2020

ServiceLocatorFactoryBean in Spring Framework

ServiceLocatorFactoryBean in Spring framework as the name suggests is an implementation of service locator design pattern and helps with locating the service at run time.

ServiceLocatorFactoryBean helps if you have more than one implementation of the same type and want to use the appropriate implementation at the run time i.e. you have an interface and more than one class implementing that interface and you want to have a factory that will return an appropriate object at run time.

registerShutdownHook() Method in Spring Framework

In the post Spring Bean Life Cycle we have already seen that you can provide destroy methods for your beans to do clean up. One problem is that these destroy callback methods are not executed automatically you do have to call AbstractApplicationContext.destroy or AbstractApplicationContext.close before shutting down the IOC container. There is another option to ensure graceful shutdown, you can register a shutdown hook with the JVM using registerShutdownHook() method in Spring.

Note that this problem is only with non-web applications. Spring’s web-based ApplicationContext implementations already have code in place to shut down the Spring IoC container gracefully when the relevant web application is shut down.

Thursday, December 24, 2020

Batch Processing in Java JDBC - Insert, Update Queries as a Batch

If you have a large number of similar queries it is better to process them in a batch rather than as individual queries. Processing them as a batch provides better performance as you send a group of queries in a single network communication rather than sending individual queries one by one.

Batch support in JDBC

JDBC provides batch support in the form of addBatch() and executeBatch() methods.

If you are using Statement interface then use addBatch(String Sql) method to add queries to the batch.

For PreparedStatement and CallableStatement use addBatch() method as parameters for the query are provided later.

Once you have added queries to a batch you can call executeBatch() method to execute the whole batch of queries.

DB you are using may not support batch updates. You should use the supportsBatchUpdates() method of the DatabaseMetaData interface to check whether the target database supports batch updates or not.

The method returns true if this database supports batch updates; false otherwise.

Wednesday, December 23, 2020

Transaction Management in Java-JDBC

This post provides detail about JDBC transaction management with examples for starting a transaction in JDBC, committing and rolling back a transaction, setting savepoint for transaction rollback.


Tuesday, December 22, 2020

Java Lambda Expressions Interview Questions And Answers

In this post some of the Java Lambda Expressions interview questions and answers are listed. This compilation will help the Java developers in preparing for their interviews especially when asked interview questions about Java 8.

  1. What is lambda expression?

    Lambda expression in itself is an anonymous method i.e. a method with no name which is used to provide implementation of the method defined by a functional interface.

    A new syntax and operator has been introduced in Java for Lambda expressions.

    General form of lambda expression

    (optional) (Arguments) -> body
    

Monday, December 21, 2020

Connection Pooling Using Apache DBCP in Java

In this post we’ll see how to configure connection pooling in your Java application using Apache DBCP datasource. The DB we are connecting to is MySQL.

Jars needed

If you are using Maven then you can add the following dependency.

<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-dbcp2</artifactId>
  <version>2.8.0</version>
</dependency>

Sunday, December 20, 2020

Spring WebFlux Example Using Functional Programming - Spring Web Reactive

In this post we’ll see a Spring web reactive example using Spring WebFlux functional programming model. The application built here is a RESTful web service with Spring Webflux and also includes a WebClient consumer of that service. Application uses Spring Boot and run on the default Netty server.

Saturday, December 19, 2020

Spring Web Reactive Framework - Spring WebFlux Tutorial

This Spring WebFlux tutorial gives an overview of the new reactive web framework- Spring WebFlux added in Spring version 5.0. It is fully non-blocking, helps you to write event driven, asynchronous logic and supports Reactive Streams back pressure.


Friday, December 18, 2020

Spring WebFlux Example Using Annotation-Based Programming - Spring Web Reactive

The post Spring Web Reactive Framework - Spring WebFlux Tutorial gives an overview of Spring web reactive. Building on that knowledge in this post we’ll see a Spring web reactive example using Spring WebFlux annotation-based programming model where @Controller and @RestController components use annotations to express request mappings, request input, exception handling, and more. The application built here is a RESTful web service with Spring Webflux and also includes a WebClient consumer of that service. Application uses Spring Boot and runs on the default Netty server.

Class And Object in Python

Python being an object oriented programming language works on the concept of creating classes and using objects of the class to access the properties and methods defined by the class.

What is a class

In object oriented programming class defines a new type. Class encapsulates data (variables) and functionality (methods) together. Once a class is defined it can be instantiated to create objects of that class. Each class instance (object) gets its own copy of attributes for maintaining its state and methods for modifying its state.

You can create multiple class instances, they all will be of the same type (as defined by the class) but they will have their own state i.e. different values for attributes.

Wednesday, December 16, 2020

Connection Pooling Using C3P0 Spring Example

This post shows how to provide JDBC connection pooling using C3P0 data source in Spring framework. DB used in this example is MySQL.

Maven dependency for C3P0

<dependency>
  <groupId>com.mchange</groupId>
  <artifactId>c3p0</artifactId>
  <version>0.9.5.2</version>
</dependency>
Alternatively you can download the following jars and put them in the application’s classpath.
c3p0-0.9.5.2.jar
mchange-commons-java-0.2.11.jar

Tuesday, December 15, 2020

Spring JdbcTemplate With ResultSetExtractor Example

In the post Select Query Using JDBCTemplate in Spring Framework we have already seen an example of extracting data from ResultSet using RowMapper. A RowMapper is usually a simpler choice for ResultSet processing, mapping one result object per row but there is another option in Spring framework known as ResultSetExtractor which gives one result object for the entire ResultSet. In this post we’ll see an example of Spring JdbcTemplate with ResultSetExtractor.

Since ResultSetExtractor is a callback interface used by JdbcTemplate's query methods so you can use an instance of ResultSetExtractor with JdbcTemplate’s query method.

Monday, December 14, 2020

Spring JdbcTemplate Insert, Update And Delete Example

In the post Data access in Spring framework we have already seen how Spring provides templates for various persistence methods and how templates divide the data access code into fixed part and variable part. Where Spring framework manages the fixed part and custom code which is provided by the user is handled through callbacks. In this post we’ll see how to use Spring JdbcTemplate to insert, update and delete data from the database.

Note that JdbcTemplate needs a DataSource in order to perform its management of fixed part like getting a DB connection, cleaning up resources.
In this post Apache DBCP is used for providing pooled datasource and MYSQL is used as the back end.

Async Pipe in Angular With Examples

Of all the built-in pipes in Angular, Async pipe is a little different as it subscribes to an Observable or Promise and returns the latest value it has emitted. When the component gets destroyed, the async pipe unsubscribes automatically to avoid any memory leaks.


Friday, December 11, 2020

Connection Pooling With Apache DBCP Spring Example

This post shows how to provide JDBC connection pooling using Apache DBCP data source in Spring framework. DB used in this example is MySQL.

Maven dependency for DBCP

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-dbcp2</artifactId>
    <version>2.1</version>
</dependency>

Alternatively you can download the following jars and put them in the classpath.

commons-dbcp2-2.1.1.jar
commons-pool2-2.5.0.jar
commons-logging-1.2.jar

Thursday, December 10, 2020

Pure and Impure Pipes in Angular

When you create a custom pipe in Angular there is one more attribute of @Pipe decorator which you can assign a value as true or false, that attribute is pure. In this tutorial we’ll see what are pure and impure pipes in Angular and what are the differences between pure and impure pipes.

@Pipe({
  name: 'myCustomPipe', 
  pure: false/true
})
export class MyCustomPipe {

}

By default, pipes are defined as pure so you don't explicitly need to assign value of pure as true.

Wednesday, December 9, 2020

Custom Pipe in Angular With Example

Though there are many Angular built-in pipes for data transformation but Angular framework also gives you an option to create a custom pipe to cater to custom data transformation. In this tutorial we’ll see how to create a custom pipe in Angular.

Creating custom pipe in Angular

To mark a class as a pipe apply the @Pipe decorator to the class. In the name attribute of the of @Pipe provide the name of the pipe. Use name in template expressions as you would for a built-in pipe.

Your custom pipe class should also implement the PipeTransform interface.

Tuesday, December 1, 2020

Using Angular Pipes in Component or Service Classes

In this tutorial we’ll see how to use Angular pipe in Component classes and Service classes in Angular.

Steps to use angular pipes in component classes (or Service)

If you want to use the pipe in more than one component class then configure it in app.module.ts class-

  1. Import the required Angular pipe and add it to the providers array.
  2. In the Component class inject the pipe and use it.

You can do these steps in Component class itself if specific Angular pipe is used in that class only.

Using Angular pipes in component class example

We’ll create a simple reactive form with fields to enter date and amount. Date has to be transformed using the DatePipe and amount using the CurrencyPipe in Component. For DatePipe configuration is done in App module where as for CurrencyPipe it is done in the Component class itself.

Tuesday, November 24, 2020

Custom Async Validator in Angular Template-Driven Form

In this tutorial we’ll see how to create a custom asynchronous validator to be used with Angular Template-Driven form.

For custom async validator in Reactive form refer this post - Custom Async Validator in Angular Reactive Form

Custom Asynchronous validator for Template-Driven form

If you want to write a custom async validator for a template-driven form that has to be written as an Angular directive which should implement the AsyncValidator interface.

interface AsyncValidator extends Validator {
  validate(control: AbstractControl): Promise<ValidationErrors | null> | Observable<ValidationErrors | null>

  // inherited from forms/Validator
  validate(control: AbstractControl): ValidationErrors | null
  registerOnValidatorChange(fn: () => void)?: void
}

Your Async validator class has to implement the validate() function which must return a Promise or an Observable.

Monday, November 23, 2020

Custom Async Validator in Angular Reactive Form

In this tutorial we’ll see how to create a custom asynchronous validator to be used with Angular Reactive form.

For custom async validator in Template-Driven form refer this post- Custom Async Validator in Angular Template-Driven Form


Types of Validator functions

Validator functions can be either synchronous or asynchronous.

  • Sync validators: Synchronous validator functions are passed a FormControl instance as argument and immediately return either a set of validation errors or null. You can pass these in as the second argument when you instantiate a FormControl.
  • Async validators: Asynchronous validator functions are passed a FormControl instance as argument and return a Promise or Observable that later emits a set of validation errors or null. You can pass these in as the third argument when you instantiate a FormControl.

Saturday, November 21, 2020

Name Mangling in Python

In Python there are no explicit access modifiers so you can’t mark a class member as public/private. Then the question is how to restrict access to a variable or method outside the class, if required. Class member can be made private (Close to private actually) using a process called name mangling in Python.


Name mangling (Making member private)

In Python name mangling process any identifier with at least two leading underscores, at most one trailing underscore is textually replaced with _classname__identifier where classname is the current class name. For example if there is a variable __var it is rewritten by the Python interpreter in the form _classname__var.

Since the name of any such class member (with at least two leading underscores, at most one trailing underscore) changes internally thus it can’t be accessed using the given name. That is the closest Python goes for making a class member private.

Python Name mangling example

Let’s try to clarify name mangling process with examples.

class Person:
  def __init__(self, name, age=0):
    self.name = name
    self.__age = age

  def display(self):
    print(self.name)
    print(self.__age)

person = Person('John', 40)
#accessing using class method
print('Displaying values using class method')
person.display()
#accessing directly from outside
print('Trying to access variables from outside the class ')
print(person.name)
print(person.__age)

Output

Displaying values using class method
John
40
Traceback (most recent call last):
File "F:/NETJS/NetJS_2017/Python/Test/Person.py", line 21, in <module>
Trying to access variables from outside the class 
John
    print(person.__age)
AttributeError: 'Person' object has no attribute '__age'

As you can see variable __age (having two leading underscores) is not accessible from outside the class. Using a method with in the class it can still be accessed.

Same way for a method with two leading underscores.

class Person:
  def __init__(self, name, age=0):
    self.name = name
    self.__age = age

  def __displayAge(self):
    print(self.name)
    print(self.__age)

person = Person('John', 40)
person.__displayAge()

Output

Traceback (most recent call last):
  File "F:/NETJS/NetJS_2017/Python/Test/Person.py", line 15, in <module>
    person.__displayAge()
AttributeError: 'Person' object has no attribute '__displayAge'

As you can see method is not accessible from outside the class.

How does name change in Name mangling

If you want to verify the rewriting of name in Python name mangling process you can do so using the dir() function.

When a class object is passed as an argument to dir() function, it returns a list of valid attributes for that object.

class Person:
  def __init__(self, name, age=0):
    self.name = name
    self.__age = age

person = Person('John', 40)
print(dir(person))

Output

['_Person__age', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', 
'__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', 
'__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', 
'__str__', '__subclasshook__', '__weakref__', 'name']

From the output of dir() function for Person object you can see that the __age is rewritten as _Person__age.

Name mangling and method overriding

As per Python docs stated objective of name mangling is to avoid name clashes of names with names defined by subclasses. Name mangling is helpful for letting subclasses override methods without breaking intraclass method calls.

For example consider the following scenario where Parent class is subclassed and there is an overridden method test is the Child class too. From the constructor of Parent class there is a call to test method- self.test()

class Parent:
  def __init__(self):
    print('in init')
    self.test()
  def test(self):
    print('In Parent test method')

class Child(Parent):
  def test(self):
    print('In Child test method')

obj = Child()
obj.test()

Output

in init
In Child test method
In Child test method

As you can see Child test method is getting called both of the times. To avoid that name clash you can create a private copy of the original method.

class Parent:
  def __init__(self):
    print('in init')
    self.__test()
  def test(self):
    print('In Parent test method')

  # private copy
  __test = test

class Child(Parent):
  def test(self):
    print('In Child test method')

obj = Child()
obj.test()

Output

in init
In Parent test method
In Child test method

Accessing name mangled class members

As already stated Python name mangling process rewrites the member name by adding _classname to the member. Thus it is still possible to access the class member from outside the class by using the rewritten name. That is why it is said that Name mangling is the closest to private not exactly private.

class Person:
  def __init__(self, name, age=0):
    self.name = name
    self.__age = age

  def display(self):
    print(self.name)
    print(self.__age)

person = Person('John', 40)
print('Trying to access variables from outside the class ')
print(person.name)
print(person._Person__age)

Output

Trying to access variables from outside the class 
John
40

As you can see private class member is accessed from outside the class by using the name mangled form _ClassName__var.

That's all for this topic Name Mangling in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Python Installation on Windows
  2. Encapsulation in Python
  3. Method Overriding in Python
  4. Multiple Inheritance in Python
  5. Python for Loop With Examples

You may also like-

  1. Passing Object of The Class as Parameter in Python
  2. Local, Nonlocal And Global Variables in Python
  3. Python count() method - Counting Substrings
  4. Python Functions : Returning Multiple Values
  5. Marker Interface in Java
  6. Functional Interfaces in Java
  7. Difference Between Checked And Unchecked Exceptions in Java
  8. Race Condition in Java Multi-Threading

Thursday, November 19, 2020

Custom Validator in Angular Template-Driven Form

Angular framework provides many built-in validators that can be used with forms but sometimes you may need a validation in your application that can’t be catered by a built-in validators. For such scenario Angular also gives the option to create a custom validator. In this tutorial we’ll see how to create a custom validator to be used with Angular template-driven form.

Custom validator for Template-Driven form

If you want to write a custom validator for a template-driven form that has to be written as an Angular directive which should implement the Validator interface. This Validator interface is implemented by classes that perform synchronous validation.

interface Validator {
  validate(control: AbstractControl): ValidationErrors | null
  registerOnValidatorChange(fn: () => void)?: void
}

Wednesday, November 18, 2020

Custom Validator in Angular Reactive Form

Angular framework provides many built-in validators that can be used with forms but sometimes these built-in validators may not match the requirement of your use case. For such scenario Angular also gives the option to create a custom validator. In this tutorial we’ll see how to create a custom validator and how to use it with Angular reactive form.

Creating custom validator

Custom validators are also like any other function that you can write in a component class. A custom validator takes FormControl as an argument and returns a key, value pair where key is string and value is boolean. Following pseudo code shows how custom validator can be written to validate a control in Angular form.

Thursday, September 17, 2020

What is Client Side Routing in Angular

While working with any modern JS frameworks like Angular, React, Vue you would have definitely come across two terms Single Page Application (SPA) and client side routing. In this post we’ll see what is client side routing using Angular as example framework.

Client side routing

In a traditional web application every request for displaying a page goes to the server and results in a full page load. Whereas in a Single page application each request doesn’t go to the server. Web server gives a single page, any further rendering is done locally by the Java script. So, in a SPA you will get a single page and part of the page is updated dynamically for further requests.

Tuesday, September 15, 2020

Location Strategies in Angular Routing

In Angular routing we have two location strategies that we can use to implement client side routing.

  1. PathLocationStrategy
  2. HashLocationStrategy

In this post we’ll see what is location strategy, which routing strategy to chose for your SPA and what are the differences between the HashLocationStrategy and PathLocationStrategy.

Friday, September 11, 2020

How to Create a Custom Observable in Angular

In this post we’ll see how to create a custom Observable in Angular. Observables are based on Observer design pattern in which an object, called the subject, maintains a list of observers and notifies them automatically of state changes. Some thing like this-

public interface Subject {
  public void register(Observer obj);
  public void unregister(Observer obj);

  public void notifyObservers();
}

Tuesday, September 8, 2020

Angular Route Resolver - Passing Data Dynamically

In the posts route parameters and Angular query parameters we have seen examples of passing data in the route and using it in the component as it is or to retrieve more data. This process happens once you have navigated to a route but you can also get data before you have navigated to a route. That is done using Angular Resolve interface that classes can implement to be a data provider. A data provider class can be used with the router to act as a resolver and it can resolve data during navigation. Using Resolve interface in Angular gives you one way to get data dynamically before navigating to a route.

Angular Resolve interface

Resolve interface has a single method resolve() that is invoked when the navigation starts. The router waits for the data to be resolved before the route is finally activated.

Monday, September 7, 2020

Angular Route - Passing Static Data

We have already seen how to pass data to a route using route parameters and using Angular query parameters. In this post we’ll see how to pass static data to an Angular route. Static data is configured at the time of defining a route using data property.

For example, here is a route definition with data property-

{path: 'wrongpath', component: PageNotFoundComponent, data :{ message:'Page not found'}},

As you can see with data property you can pass an object having key, value pairs.

Monday, August 31, 2020

CanDeactivate Guard in Angular With Example

In this post we’ll see an example of CanDeactivate guard in Angular which helps in handling unsaved changes.

CanDeactivate interface in Angular

Any class implementing CanDeactivate interface can act as a guard which decides if a route can be deactivated. If you configure this class to be a canDeactivate guard for any route then if you try to navigate away from that route you can show a dialog box to confirm whether user really want to move away.

CanDeactivate interface has a single method canDectivate and the interface is defined as given below-

interface CanDeactivate<T> {
  canDeactivate(component: T, currentRoute: ActivatedRouteSnapshot, currentState: RouterStateSnapshot, nextState?: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree
}

Tuesday, August 25, 2020

Angular CanActivateChild Guard to protect Child Routes

In the post Angular Access Control CanActivate Route Guard Example we saw an example of canActivate guard and how it protects a route including its child routes. You can also protect child routes with the CanActivateChild guard in Angular. If you want to guard only the child component then you can use the CanActivateChild guard which is similar to the CanActivate guard with the difference that it runs before any child route is activated.

CanActivateChild interface in Angular

A class implementing CanActivateChild interface can act as a guard deciding if a child route can be activated. If all guards return true, navigation continues. If any guard returns false, navigation is cancelled.

There is one method canActivateChild in the interface.

interface CanActivateChild {
  canActivateChild(childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree
}

Tuesday, August 18, 2020

Nested Route (Child Route) in Angular

All the Angular routing examples we have seen so far have routes that are relative to the root component. But in a big application you would want to contain the route with in another route that is creating routes that are relative to component other than root component. These types of routes with in a route are called nested route or child route in Angular routing.


How to create a child route in Angular routing

You place child routes in a children array within the parent route. For example if you want to create two nested routes relative to ParentComponent then it can be done as follows-

Monday, August 17, 2020

Setting Wild Card Route in Angular

In the post Angular Routing Concepts With Example we saw an example of setting up routes for navigation. One question though is what if user navigates to a path that does not exist. Ideally you should also handle such scenario and show a page not found or navigate to home page when user tries to navigate to a non-existent path. In this post we’ll see how to set up wild card route in Angular to handle any case when the requested URL doesn’t match any router path.

In this example wild card route is set up to show page not found message.

Wild card route in Angular

For setting up a wild card route in Angular you use ‘**’ (double asterisk). This wild card route catches all routes that are not configured with in the route definition.

{ path: '**', component: COMPONENT_NAME}

Do ensure that the wildcard route is the last one in the route definition ordering as wild card route matches every URL.

This order of routes is important because the Router uses a first-match wins strategy. When matching routes if wildcard route, which matches every URL, is at the top then the component paired with wildroute will be the one always called. Follow the order of-

  • List routes with a static path first.
  • Empty path route (with a possible redirection).
  • The wildcard route comes last.

Wild card route Angular Example

Routing module with route definitions including wild card route (app-routing.module.ts).

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AccountsComponent } from './accounts/accounts.component';
import { AccountComponent } from './accounts/account/account.component';
import { HomeComponent } from './home.component';
import { ServiceComponent } from './service.component';

const routes: Routes = [
                      {path: 'home', component: HomeComponent},                  
                      {path: 'account', component: AccountsComponent},
                      {path: 'account/:acctno', component: AccountComponent},
                      {path: 'service', component: ServiceComponent},
                      {path: '', redirectTo:'/home', pathMatch: 'full'}, 
                      {path: '**', component: PageNotFoundComponent}                
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Do notice the route order, static paths first, then the default route redirect using empty path and then the wild card route.

PageNotFoundComponent (pagenotfound.component.ts)

@Component({
  selector: 'app-pagenotfound',
  templateUrl: './pagenotfound.component.html'
})
export class PageNotFoundComponent{

}

pagenotfound.component.html

<h3>404 Page Not Found!!</h3>

For other component’s code please refer this post- Angular Routing Concepts With Example

Now if you try to navigate any URL that doesn’t match any of the configured routes you will be sent to PageNotFoundComponent.

wild card route in Angular


That's all for this topic Setting Wild Card Route in Angular. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Angular Tutorial Page


Related Topics

  1. Path Redirection in Angular Routing
  2. Using RouterLinkActiveOptions to Fix Link Highlighted Problem
  3. Nested Route (Child Route) in Angular
  4. Angular Route Parameters - Setting and Fetching
  5. Passing Query Parameters in Angular Routing

You may also like-

  1. Angular ngFor Directive With Examples
  2. Angular One-Way Data Binding Using String Interpolation
  3. Angular Two-Way Data Binding With Examples
  4. Angular - Call One Service From Another
  5. ConcurrentHashMap in Java With Examples
  6. Var type in Java - Local Variable Type Inference
  7. What Are JVM, JRE And JDK in Java
  8. How to Write a Map Only Job in Hadoop MapReduce

Friday, August 14, 2020

Passing Query Parameters in Angular Routing

In this post we’ll how to pass query parameters in Angular routing and how to retrieve the passed query parameters.


Query parameters in Angular

Using query parameters you can pass optional parameters across the routes in your application. Query parameters are separated by a question mark from the URL and any route parameters. You can have more than one query parameter in the URL which are separated by &.

For example- localhost:4200/services?accttype=s&allowaccess=1

Here accttype and allowaccess are query parameters.

Passing query parameters in Angular routing

1. You can pass query parameters with RouterLink directive. RouterLink directive has a property queryParams that is used to pass query parameters.

<a [routerLink]="['/account', accountnumber]"  
            [queryParams]="{accttype: 's'}"           
             class="list-group-item"   
            *ngFor="let accountnumber of accountnumbers">
            {{ accountnumber }}
</a>

Which results in a URL like- http://localhost:4200/account/A1001?accttype=s

2. You can also pass query parameters programmatically using Router.navigate() method. In navigate method you can pass query parameters as a Javascript object.

this.router.navigate(['/account', accountno], {queryParams:{accttype: 's'}});

You can of course pass more than one query parameter in both of these ways as comma separated values.

this.router.navigate(['/account', accountno], {queryParams:{accttype: 's', allowaccess: 1}});

Accessing query parameters in Angular

For retrieving query parameters in Angular you can use the queryParams property of the ActivatedRoute class.

this.route.queryParams
          .subscribe((queryParams: Params)=> {
            this.acctType = queryParams['accttype']
          });
or you can use the current snapshot of the route to get query parameters from that.
this.acctType = this.route.snapshot.queryParams['accttype'];

Query parameters in Angular routing example

Let’s see a full Angular example to understand passing and retrieving of query parameters. In the example there is-

AccountsComponent to display account numbers.

AccountComponent to display details of the clicked account.

In the AccountComponent there is a button to navigate to ServiceComponent which displays the offered services only if account type is saving. Account type is passed as a query parameter.

1. Routing module (app-routing.module.ts)

import { Routes, RouterModule } from '@angular/router';
import { AccountsComponent } from './accounts/accounts.component';
import { AccountComponent } from './accounts/account/account.component';
import { HomeComponent } from './home.component';
import { ServiceComponent } from './service.component';

const routes: Routes = [
                    {path: 'home', component: HomeComponent},                  
                    {path: 'account', component: AccountsComponent},
                    {path: 'account/:acctno', component: AccountComponent},
                    {path: 'service', component: ServiceComponent},
                    {path: '', redirectTo:'/home', pathMatch: 'full'}             
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

2. Adding routing module to AppModule.

import { AppRoutingModule } from './app-routing.module';

imports: [
  BrowserModule,
  AppRoutingModule
],

3. Route links (app.component.html)

<nav class="navbar navbar-expand-md bg-dark navbar-dark">
  <div class="container-fluid">
    <div class="collapse navbar-collapse" id="collapsibleNavbar">
      <ul class="nav navbar-nav">
        <li class="nav-item" routerLinkActive="active">
          <a class="nav-link" routerLink="/home">Home</a>
        </li>
        <li class="nav-item" routerLinkActive="active">
          <a class="nav-link" routerLink="/account">Accounts</a>
        </li>
        <li class="nav-item" routerLinkActive="active">
          <a class="nav-link" [routerLink]="['/service']">Services</a>
        </li>
      </ul>
    </div>
  </div>
</nav>
<div class="container">
  <div class="row"><p></p></div>
  <div class="row">
    <div class="col-md-12">
      <router-outlet></router-outlet>
    </div>
  </div>
</div>

4. Creating components.

AccountsComponent (accounts.component.ts)

In this component there are some hardcoded account numbers.

import { Component } from '@angular/core';

@Component({
  selector: 'app-accounts',
  templateUrl: './accounts.component.html'
})
export class AccountsComponent {
  accountnumbers = ['A1001', 'A1002'];
}

accounts.component.html

This template displays the account numbers and also creates route link for account numbers.

<div class= "row">
  <div class="col-xs-4 col-md-6">
    <h2>Account Numbers</h2>
    <div class="list-group">
      <a [routerLink]="['/account', accountnumber]"           
        class="list-group-item"   
        *ngFor="let accountnumber of accountnumbers">
        {{ accountnumber }}
      </a>
    </div>
  </div>
</div>

AccountComponent (account.component.ts)

In this component we display details for the account number which is sent as route parameter. To extract the parameter route.params observable is used and we subscribe to it so that when ever there is a change the parameter is extracted into a acctNo variable. This is done in ngOnInit().

Using the fetched account number we find the related object in the array using the find() method.

There is also a onSelectedAccount(acct) method where the query parameter is attached to the URL in the router.navigate() method.

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Params, Router } from '@angular/router';

@Component({
  selector: 'app-account',
  templateUrl: './account.component.html'
})
export class AccountComponent implements OnInit{
  acctNo: string;
  account: {accountnumber: string, type: string, balance: number};
  constructor(private router: Router, private route: ActivatedRoute){ }
  accountDetails = [
    {
      accountnumber: 'A1001',
      type: 'Saving', 
      balance: 22000
    },
    {
      accountnumber: 'A1002',
      type: 'Checking',
      balance: 1000
    }
  ];

  ngOnInit() {
    this.route.params.subscribe((params: Params)=> this.acctNo = params['acctno']);
    this.account = this.accountDetails.find(e=>e.accountnumber === this.acctNo);
  }

  onSelectedAccount(acct){
    this.router.navigate(['/service'], {queryParams:{accttype: acct.type === 'Saving'? 's':'c'}})
  }
}

account.component.html

This template displays the account details for the selected account number. There is also a button to navigate to the offered services for the selected account number.

<h2>Account Details</h2>
<div class="row">
  <div class="col-xs-6">
    <label>Account Number: </label> {{ account.accountnumber }}
  </div>
</div>
<div class="row">
  <div class="col-xs-6">
    <label>Account Type: </label> {{ account.type }}
  </div>
</div>
<div class="row">
  <div class="col-xs-6">
    <label>Balance: </label> {{account.balance}}
  </div>
</div>
<button class="btn btn-primary" (click)="onSelectedAccount(account)">Offered Services</button>

ServiceComponent (service.component.ts)

In this component we have the offered services stored in an array. In the ngOnInit() method passed query parameter (accttype) is retrieved using route.queryParams observable.

Boolean variable showServices is assigned the value true or false based on whether the passed query parameter is ‘s’ or ‘c’.

import { Component, OnInit } from "@angular/core";
import { ActivatedRoute, Params } from '@angular/router';

@Component({
    selector: 'app-service',
    templateUrl:'./service.component.html'
})
export class ServiceComponent implements OnInit{
  showServices = false;
  services = [
    'Deposit Money',
    'Open FD',
    'Mail Customer Care'
  ];
  constructor(private route : ActivatedRoute){ }
  ngOnInit() {
    this.route.queryParams
              .subscribe((queryParams: Params) => {
                  this.showServices = queryParams['accttype'] === 's'? true:false
               });
  }
}

service.component.html

Using ngIf directive value of showServices is checked and if it is false then the messsage ‘No services for checking account’ is displayed otherwise offered services are displayed.

<h2>Services Offered</h2>
<h4 *ngIf="!showServices">No services for checking account</h4>
<div *ngIf="showServices">
  <div class="row">
    <div class="col-xs-12 col-sm-6">
      <div class="list-group">
        <a
          href="#"
          class="list-group-item"
          *ngFor="let service of services">
          {{ service }}
        </a>
      </div>
    </div>
  </div>
</div>

Showing account numbers-

Display account details-

Offered services-

When URL is- http://localhost:4200/service?accttype=s

When URL is- http://localhost:4200/service?accttype=c

Preserving or Merging Query Parameters with queryParamsHandling

If you navigate away from the route with query parameters to any other route, by default the query parameters are lost. If you want to retain them set queryParamsHandling to-

  • preserve- If you want to preserve the original query parameters.
  • merge- If you want to merge the original query parameters with the new one.

For example if you want to move from service to other-page and still want to keep the query parameters-

onClickOtherPage(){
  this.router.navigate(['/other-page'], {queryParamsHandling:'preserve'});
}

Resulting in a URL- http://localhost:4200/other-page?accttype=s

If you want to add more query parameters and want to retain the previous one too-

onClickOtherPage(){
  this.router.navigate(['/other-page'], {queryParams: {param1: 'value', queryParamsHandling:'merge'});
}

Resulting in a URL- http://localhost:4200/other-page?param1=value&accttype=s

That's all for this topic Passing Query Parameters in Angular Routing. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Angular Tutorial Page


Related Topics

  1. Path Redirection in Angular Routing
  2. Navigate to a Route Programmatically in Angular
  3. Angular Route - Passing Static Data
  4. Location Strategies in Angular Routing
  5. Angular Custom Property Binding Using @Input Decorator

You may also like-

  1. Angular Custom Two-Way Data Binding
  2. Angular ngSwitch Directive With Examples
  3. Angular Cross Component Communication Using Subject Observable
  4. FormBuilder in Angular Example
  5. PriorityBlockingQueue in Java Concurrency
  6. Difference Between StackOverflowError and OutOfMemoryError in Java
  7. Predefined Mapper And Reducer Classes in Hadoop
  8. Passing Arguments to getBean() Method in Spring

Friday, August 7, 2020

Using RouterLinkActiveOptions to Fix Link Highlighted Problem

In the post Highlight Currently Selected Menu Item Angular Routing Example we saw how you can highlight the selected menu option but there may be one problem with that, menu option configured with root path route always remain highlighted. In this post we’ll see how to fix the problem of root path route always remaining highlighted in Angular using routerLinkActiveOptions.

Link remaining highlighted problem

If you have configured your routes arrays something like as given below-

const routes: Routes = [
                        {path: '', component: HomeComponent},                  
                        {path: 'account', component: AccountComponent},
                        {path: 'service', component: ServiceComponent}
                       ];

And the routeLink as given here-

<nav class="navbar navbar-expand-md bg-dark navbar-dark">
  <div class="container-fluid">
    <div class="collapse navbar-collapse" id="collapsibleNavbar">
      <ul class="nav navbar-nav">
        <li class="nav-item" routerLinkActive="active">
          <a class="nav-link" routerLink="/">Home</a>
        </li>
        <li class="nav-item" routerLinkActive="active">
          <a class="nav-link" routerLink="/account">Accounts</a>
        </li>
        <li class="nav-item" routerLinkActive="active">
          <a class="nav-link" routerLink="/service">Services</a>
        </li>
      </ul>
    </div>
  </div>
</nav>
<div class="container">
  <div class="row"><p></p></div>
    <div class="row">
      <div class="col-md-12">
        <router-outlet></router-outlet>
      </div>
    </div>
</div> 

Then you will see the problem of link associated with the root ("/") always remain highlighted.

Using routerLinkActiveOptions in Angular

You can see in the image even if Services menu link is clicked, ‘Home’ remains highlighted.

This problem occurs because Angular considers root path segment to be the part of all the paths. Even if path is either http://localhost:4200/service or http://localhost:4200/account, root path segment “/” is always there. That is the reason the Link associated with empty path (“/”) is always highlighted.

Using routerLinkActiveOptions

In order to solve this problem using routerLinkActiveOptions. With routerLinkActiveOptions you can pass a javascript object {exact:true} to direct Angular to make link active only when exact path matches.

<li class="nav-item" routerLinkActive="active" [routerLinkActiveOptions]="{exact: true}">
  <a class="nav-link" routerLink="/">Home</a>
</li>

With this configuration change ‘Home’ menu will only be highlighted when it is selected, as soon as you move away from this option it won’t remain highlighted anymore.

That's all for this topic Using RouterLinkActiveOptions to Fix Link Highlighted Problem. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Angular Tutorial Page


Related Topics

  1. Angular Routing Concepts With Example
  2. Path Redirection in Angular Routing
  3. Navigate to a Route Programmatically in Angular
  4. Setting and Fetching Route Parameters in Angular
  5. Angular Two-Way Data Binding With Examples

You may also like-

  1. Angular ngClass Directive With Examples
  2. Angular Custom Event Binding Using @Output Decorator
  3. How to Add Bootstrap to Angular Application
  4. Angular - Call One Service From Another
  5. What is In-place Algorithm
  6. getPath(), getCanonicalPath() and getAbsolutePath() Methods in Java
  7. Switch Expressions in Java 12
  8. Python Exception Handling Tutorial

Thursday, August 6, 2020

Highlight Currently Selected Menu Item Angular Routing Example

In this article we’ll see how to highlight the currently selected menu item when using Angular routing and routerLink.

Note that Angular example shown here uses Angular 9 and Bootstrap 4.

RouterLink Directive in Angular

Angular RouterLink directive tracks whether the linked route of an element is currently active, it allows you to specify one or more CSS classes to add to the element when the linked route is active.

You can assign a CSS class as given below-

routerLinkActive="CSS_CLASS"
You can specify more than one CSS class using a space-separated string or an array.
routerLinkActive="CSS_CLASS1 CSS_CLASS2"

or

[routerLinkActive]="['CSS_CLASS1', 'CSS_CLASS2']"

Highlight currently selected menu item – Angular + Bootstrap example

In Bootstrap framework there is a CSS class active that can be used with routerLinkActive for the purpose of highlighting the selected menu item. Here is an example menu code.

<nav class="navbar navbar-expand-md bg-dark navbar-dark">
  <div class="container-fluid">
    <div class="collapse navbar-collapse" id="collapsibleNavbar">
      <ul class="nav navbar-nav">
        <li class="nav-item" routerLinkActive="active">
          <a class="nav-link" routerLink="/home">Home</a>
        </li>
        <li class="nav-item" routerLinkActive="active">
          <a class="nav-link" routerLink="/account">Accounts</a>
        </li>
        <li class="nav-item" routerLinkActive="active">
          <a class="nav-link" routerLink="/service">Services</a>
        </li>
      </ul>
    </div>
  </div>
</nav>

That's all for this topic Highlight Currently Selected Menu Item Angular Routing Example. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Angular Tutorial Page


Related Topics

  1. Path Redirection in Angular Routing
  2. Using RouterLinkActiveOptions to Fix Link Highlighted Problem
  3. Navigate to a Route Programmatically in Angular
  4. Nested Route (Child Route) in Angular
  5. Angular Two-Way Data Binding With Examples

You may also like-

  1. Angular Custom Two-Way Data Binding
  2. Angular @Input and @Output Example
  3. Angular - Call One Service From Another
  4. Creating New Component in Angular
  5. Pre-defined Functional Interfaces in Java
  6. Difference Between StackOverflowError and OutOfMemoryError in Java
  7. Writing a File Asynchronously Java Program
  8. Passing Arguments to getBean() Method in Spring

Wednesday, August 5, 2020

Path Redirection in Angular Routing

In this article we'll see how to redirect to a component (URL path) in Angular routing.


Setting redirect in Angular Routing

To set up a redirect in an Angular route definition you will have to use redirectTo property.

For redirection you need to configure a route with the following three things-

  1. path you want to redirect from
  2. The component you want to redirect to
  3. A pathMatch value to tell the router how to match the URL.

For example if you want to set a default route to the home page. When the initial URL in the browser is- localhost:4200 it should redirect automatically to localhost:4200/home.

{path: '', redirectTo:'/home', pathMatch: 'full'}

Here path you want to redirect from is '' meaning nothing after the base URL.

redirectTo has a value ‘/home’ which tells the Angular router when we visit path localhost:4200 redirect to the /home route.

Here pathMatch value is full which means redirection happens only if the full path after the base URL is ''.

Angular routing redirect example

Suppose we have three components Home, Account and Service and the app routing module is as given below.

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AccountComponent } from './account.component';
import { HomeComponent } from './home.component';
import { ServiceComponent } from './service.component';


const routes: Routes = [
                        {path: 'home', component: HomeComponent},                  
                        {path: 'account', component: AccountComponent},
                        {path: '', redirectTo:'/home', pathMatch: 'full'},                   
                        {path: 'service', component: ServiceComponent}
                       ];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

As per route definition specified in routing module when URL has /home as path it will be handled by this route definition. HomeComponent is the component that will be called to handle this route.

{path: 'home', component: HomeComponent},

Following route definition sets up a redirect to the above definition for home route if path matches '' (i.e. nothing after the base URL).

{path: '', redirectTo:'/home', pathMatch: 'full'},

Different path matching values

In the above route definition pathMatch value is used as ‘full’ which means value specified with path will be matched fully with the path after the base URL.

Another value for pathMatch is ‘prefix’ which tells the Angular to check if the path in the URL starts with the value given with path or not.

If you change the route definition to have pathMatch as prefix here-

{path: '', redirectTo:'/home', pathMatch: 'prefix'}

Now every path matches this route definition because technically every path starts with ''.

If you change the pathMatch to ‘prefix’, as per the route definitions given in the routing module in this example you will never be able to reach ServiceComponent because localhost:4200/service will always be matched by the redirect route. Other two routes above the redirect route will work fine because of the route ordering followed by Angular.

Route order in Angular

Angular uses the first-match wins strategy when matching routes so more specific routes should be placed above less specific routes.

  • Routes with a static path should be placed first.
  • Then an empty path route which matches the default route.
  • The wildcard route should be placed last because it matches every URL.

That's all for this topic Path Redirection in Angular Routing. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Angular Tutorial Page


Related Topics

  1. Highlight Currently Selected Menu Item Angular Routing Example
  2. Navigate to a Route Programmatically in Angular
  3. Setting Wild Card Route in Angular
  4. Nested Route (Child Route) in Angular
  5. Setting and Fetching Route Parameters in Angular

You may also like-

  1. Angular Custom Property Binding Using @Input Decorator
  2. Injector Hierarchy and Service Instances in Angular
  3. Angular Disable Button Example
  4. FormGroup in Angular With Examples
  5. Executor And ExecutorService in Java Concurrency
  6. Interface Default Methods in Java
  7. Bucket Sort Program in Java
  8. File Read in HDFS - Hadoop Framework Internal Steps

Monday, August 3, 2020

Angular Routing Concepts With Example

While writing any application we split it into different areas, UI is no different and you will have different web pages for different functionalities that will be derived, relative to the current URL, as an action to the event like clicking a button or a link. In Angular it is done using Angular routing where router enables navigation detecting change in browser URL as an instruction to change the view.

In this post we’ll go through an Angular routing example to understand how to configure routing and to understand different concepts related to the router.

Client side routing

In client side routing you don’t necessarily go to the server to get a new page. In Angular apps which are known as Single Page Apps (SPA) server gives us a single page and you change what the user sees by showing or hiding portions of the display that correspond to particular components. Read more about client side routing in this post- What is Client Side Routing in Angular.

Building blocks of Angular routing

  1. Import RouterModule and Routes into your routing module. Using Routes you configure the routes for your application.
  2. <router-outlet> element is a placeholder to inform Angular where to put the content for the selected route.
  3. RouterLink directive is used to create a link to navigate to a route.

Angular routing example

With the help of this Angular routing example we’ll see how to configure routing paths. There is a menu as shown below and you have to show the corresponding component on click of the menu option.

Angular routing

1. Creating routing module

We’ll create a separate routing file app-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AccountComponent } from './account.component';
import { HomeComponent } from './home.component';
import { ServiceComponent } from './service.component';


const routes: Routes = [{path: '', redirectTo:'/home', pathMatch: 'full'},
                        {path: 'home', component: HomeComponent},
                        {path: 'account', component: AccountComponent},
                        {path: 'service', component: ServiceComponent}
                       ];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

In this RoutingModule class you can notice the following things for routing-

  1. Import RouterModule and Routes into your routing module.
    import { Routes, RouterModule } from '@angular/router';
    
  2. Configure your routes in a Routes array by specifying the path and the component they are mapped to.
    const routes: Routes = [{path: '', redirectTo:'/home', pathMatch: 'full'},
                            {path: 'home', component: HomeComponent},
                            {path: 'account', component: AccountComponent},
                            {path: 'service', component: ServiceComponent}
                           ];
    

    Each route in this array is a JavaScript object containing two properties-

    • First property, path, defines the URL path for the route.
    • The second property, component, defines the component Angular should use for the corresponding path.

    There is also a redirect setup where path: '' means to use the initial relative URL and it defaults to the home route.

  3. Configures the imports and exports arrays for @NgModule(). In the RouterModule.forRoot() method you pass the routes array. This method creates and configures an NgModule with all the router providers and directives.

2. Import the AppRoutingModule into AppModule (app.module.ts) and add it to the imports array.

import { AppRoutingModule } from './app-routing.module';
imports: [
  BrowserModule,
  AppRoutingModule
],

3. Adding the configured routes to the application.

Code for menu and adding link for routes is done in the app.component.html template itself for this example.

<nav class="navbar navbar-expand-md bg-dark navbar-dark">
  <div class="container-fluid">
    <div class="collapse navbar-collapse" id="collapsibleNavbar">
      <ul class="nav navbar-nav">
        <li class="nav-item" routerLinkActive="active"><a class="nav-link" routerLink="/home">Home</a></li>
        <li class="nav-item" routerLinkActive="active"><a class="nav-link" routerLink="/account">Accounts</a></li>
        <li class="nav-item" routerLinkActive="active"><a class="nav-link" routerLink="/service">Services</a></li>
      </ul>
    </div>
  </div>
</nav>
<div class="container">
  <div class="row"><p></p></div>
  <div class="row">
    <div class="col-md-12">
      <router-outlet></router-outlet>
    </div>
  </div>
</div>

For menu styling Bootstrap 4 is used in the template.

To create a link to navigate to a given route, routerLink is used in Angular routing application rather than href. If you use href then clicking a link results in a page reload and that’s something you don't want in your single page apps. Using RouterLink directive to create a link to route doesn't cause full page reload.

<a class="nav-link" routerLink="/account">Accounts</a>

Value given here for routerLink should be same as how route path is configured in routes array in routing module.

routerLinkActive="active" ensures that the currently selected menu option is highlighted. Bootstrap framework is used in the example which already provides this active class so you don’t need to write this CSS class yourself.

In your single page apps you don’t want a full page reload you just want to substitute the content with the content of the selected route’s component. To inform Angular where do we want to render the contents for the selected, we use the RouterOutlet directive.

Placement of <router-outlet></router-outlet> defines where content will be rendered.

Another way to define routerLink

There is one more way to define a routerLink using property binding. If used this way you can pass the path segments as array elements. For example, if you want to define route to service using routerLink with property binding.

<a class="nav-link" [routerLink]="['/service']">Services</a>

Creating components

We are done with the configuration for Angular routing now we’ll go through the mapped components. Here focus is on understanding routing so data is hardcoded in the components.

Home Component (home.component.ts)

import { OnInit, Component } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html'
})
export class HomeComponent implements OnInit {
  userId = 'UID0023';
  constructor() { }

  ngOnInit() {
  }
}

home.component.html

<h4>Welcome to XYZ Bank</h4>
<p>{{ userId }} logged in.</p>

Account Component (account.component.ts)

import { Component } from '@angular/core';

@Component({
  selector: 'app-account',
  templateUrl: './account.component.html'
})
export class AccountComponent {
  accounts = [
    {
      accountnumber: 1001,
      type: 'Saving'
    },
    {
      accountnumber: 1002,
      type: 'Checking'
    }
  ];
}

account.component.html

<div class= "row">
  <div class="col-xs-4 col-md-6">
  <h2>Account Details</h2>
  <table class="table table-sm table-bordered m-t-4">
    <tr>
      <th>Account Number</th>
      <th>Account Type</th>
    </tr>
    <tr *ngFor="let account of accounts">
      <td>{{account.accountnumber}}</td>
      <td>{{account.type}}</td>
    </tr>
  </table>
  </div>
</div>

Service Component (service.component.ts)

import { Component } from "@angular/core";

@Component({
  selector: 'app-service',
  templateUrl:'./service.component.html'
})
export class ServiceComponent{
  services = [
    'Deposit Money',
    'Open FD',
    'Mail Customer Care'
  ]; 
}

service.component.html

<h2>Services Offered</h2>
<div class="row">
  <div class="col-xs-12 col-sm-6">
    <div class="list-group">
      <a
        href="#"
        class="list-group-item"
        *ngFor="let service of services">
        {{ service }}
      </a>
    </div>
  </div>
</div>

Add these components in the declarations array of the AppModule.

Running the application

Once the application is successfully compiled and you access it using http://localhost:4200 that redirects to the http://localhost:4200/home. Clicking on Home menu option also displays the same component.

Angular routing example

Clicking on Account menu option


Same way clicking on Service menu option displays the Service component.

That's all for this topic Angular Routing Concepts With Example. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Angular Tutorial Page


Related Topics

  1. Path Redirection in Angular Routing
  2. Highlight Currently Selected Menu Item Angular Routing Example
  3. Setting Wild Card Route in Angular
  4. Using RouterLinkActiveOptions to Fix Link Highlighted Problem
  5. Passing Query Parameters in Angular Routing

You may also like-

  1. Angular Custom Two-Way Data Binding
  2. Angular @Input and @Output Example
  3. Angular - Call One Service From Another
  4. Creating New Component in Angular
  5. Pre-defined Functional Interfaces in Java
  6. Difference Between StackOverflowError and OutOfMemoryError in Java
  7. Writing a File Asynchronously Java Program
  8. Passing Arguments to getBean() Method in Spring

Monday, July 13, 2020

Spring JdbcTemplate Select Query Example

In the post Spring JdbcTemplate Insert, Update And Delete Example I have already discussed how JdbcTemplate can be used for inserting and updating data in the DB. I left behind the part to read from Database using Select query. Purpose for doing that is to discuss in detail the callback part of the JdbcTemplate. This post shows how to use Select query using JdbcTemplate in Spring framework and also talks about the callback methods in detail which shows how you can do resultset to model mapping using RowMapper implementation.

In the post Data access in Spring framework it has been discussed in detail how Spring framework provides templates to manage the fixed part and uses call back to handle the variable part. Fetching data from DB using select query has, as usual, the fixed part like getting connection, cleaning up, handling exception but at the same time Spring framework does need help to map the fetched data to the model. That’s where callback comes into picture.

Technologies used

  • Spring 5.0.4
  • Apache DBCP2
  • MYSQL 5.1.39
  • Java 8
  • Apache Maven 3.3.3

In this Spring JdbcTemplate select query example Apache DBCP is used for providing pooled datasource and MYSQL is used as the back end.


Maven dependencies

If you are using maven then you can provide dependencies in your pom.xml.

With all the dependencies your pom.xml should look something like this -

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>org.netjs.prog</groupId>
  <artifactId>maven-spring</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>maven-spring</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <spring.version>5.0.4.RELEASE</spring.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>
    
    <dependency>
      <groupId>javax.inject</groupId>
      <artifactId>javax.inject</artifactId>
      <version>1</version>
    </dependency>
    
    <!-- Spring JDBC Support -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    
    <!-- MySQL Driver -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.39</version>
    </dependency>
    
    <!--  Apache DBCP connection pool -->
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-dbcp2</artifactId>
      <version>2.1</version>
    </dependency>
  </dependencies>
</project>

Alternatively you can download the jars and add them to the class path.

Database table for example

For this example I have created a table called employee with the columns id, name and age in the MYSQL DB. Column id is configured as auto increment checked so no need to pass id from your query as DB will provide value for it.

CREATE TABLE `employee` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(35) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;

Configuring datasource dependency

First thing is to set up DataSource as a bean. I have used properties file to configure datasource where all the properties are there in the db.properties file.

<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
    <property name="driverClassName" value = "${db.driverClassName}" />
    <property name="url" value = "${db.url}" />
    <property name="username" value = "${db.username}" />
    <property name="password" value = "${db.password}" />
    <property name="initialSize" value = "${pool.initialSize}" />
</bean>

Where as db.properties file which is under the config folder has all the properties.

db.properties

db.driverClassName=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/netjs
db.username=
db.password=
pool.initialSize=5

Description of the properties is as-

driver class name is the JDBC driver for the DB used. Since MYSQL is used here so the jdbc driver for the same (com.mysql.jdbc.Driver) is provided.

Url – You need to provide url to access your DB server. I have created a schema called netjs and DB is running on the same system so url is jdbc:mysql://localhost:3306/netjs.

Username and password for the DB.

IntialSize is the initial size of the connection pool. It is given as 5 so initially 5 connections will be created and stored in the pool.

To use properties file you need to put following configuration in your XML.

<context:property-placeholder location="classpath:config/db.properties" />

Spring JDBCTemplate configuration

DataSource bean has to be provided as a reference in JdbcTemplate.

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">  
    <property name="dataSource" ref="dataSource"></property>  
</bean>

Java Classes

Since Spring always promotes to use interfaces and there is also a JEE design pattern for database layer called DAO which also says the same thing - Separate low level data access code from the business layers.

So we have a EmployeeDAO interface with find methods and its implementing class EmployeeDAOImpl. There is also a model class Employee with all the getters/setters.

Employee.java class

public class Employee {
 private int empId;
 private String empName;
 private int age;
 
 public int getEmpId() {
  return empId;
 }
 public void setEmpId(int empId) {
  this.empId = empId;
 }
 public String getEmpName() {
  return empName;
 }
 public void setEmpName(String empName) {
  this.empName = empName;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
}

EmployeeDAO interface

import org.netjs.model.Employee;

public interface EmployeeDAO {
  public List<Employee> findAllEmployees();
  
  public Employee findEmployee(int empId);
}

EmployeeDAOImpl class

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.netjs.dao.EmployeeDAO;
import org.netjs.model.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

@Repository
public class EmployeeDAOImpl implements EmployeeDAO {
  @Autowired
  private JdbcTemplate jdbcTemplate; 
  
  final String SELECT_BY_ID_QUERY = "SELECT id, name, age from EMPLOYEE where id = ?";
  final String SELECT_ALL_QUERY = "SELECT id, name, age from EMPLOYEE";
  
  public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {  
    this.jdbcTemplate = jdbcTemplate;  
  }
    
  public Employee findEmployee(int empId) {
    return this.jdbcTemplate.queryForObject(SELECT_BY_ID_QUERY, new EmployeeMapper(), 
    empId);
  }

  public List<Employee> findAllEmployees() {
    return this.jdbcTemplate.query(SELECT_ALL_QUERY, new EmployeeMapper());
  }

  private static final class EmployeeMapper implements RowMapper<Employee> {
    public Employee mapRow(ResultSet rs, int rowNum) throws SQLException {
      Employee emp = new Employee();
      emp.setEmpId(rs.getInt("id"));
      emp.setEmpName(rs.getString("name"));
      emp.setAge(rs.getInt("age"));
      return emp;
    }
  }  
}

Notice how you are not writing any code for getting or closing connection, exception handling. All that fixed part is managed by the JdbcTemplate class. Its the JdbcTemplate which is getting the connection using the DataSource provided to it, creating and executing the statement and closing the connection.

If there is any SQLException thrown that is also caught by JdbcTemplate and translated to one of the DataAccessException and rethrown.

Spring RowMapper

Main thing to demonstrate in this Spring JdbcTemplate select query example is how callback works. Here template callbacks are used to query the DB and then map the returned result set to the model (Employee) object(s).

If you have noticed in findEmployee(int empId) method queryForObject method of JdbcTemplate is used which takes 3 parameters-

  • SQL query String
  • RowMapper object that maps a single result row to a Java object via a RowMapper
  • varargs to bind parameters to the query

Whereas in findAllEmployees() method query method is used which takes only two parameters –

  • SQL query String
  • RowMapper object

as there are no parameters to be passed to the SQL so varargs are not needed in this case.

Main thing here is RowMapper object which in this example is the object of class EmployeeMapper implementing the RowMapper interface.
RowMapper interface has a single method mapRow which takes two arguments -

  1. ResultSet - A table of data representing a database result set
  2. int - the number of the current row
and this method returns the result object for the current row.

For every row in the result set, JdbcTemplate calls the mapRow() method of the RowMapper interface implementing class. Arguments passed are ResultSet and an integer which is the number of the current row in the result set. Using that row number cursor is moved to the given row in the result set.

XML Configuration

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">
    
    <context:component-scan base-package="org.netjs.daoimpl" />
    <!--  For reading properties files --> 
    <context:property-placeholder location="classpath:config/db.properties" />
    
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">  
        <property name="dataSource" ref="dataSource"></property>  
    </bean>  
    <!-- <bean id="employeeDAO" class="org.netjs.daoimpl.EmployeeDAOImpl">
        <property name="jdbcTemplate" ref="jdbcTemplate"></property>  
    </bean> -->
    
    <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
        <property name="driverClassName" value = "${db.driverClassName}" />
        <property name="url" value = "${db.url}" />
        <property name="username" value = "${db.username}" />
        <property name="password" value = "${db.password}" />
        <property name="initialSize" value = "${pool.initialSize}" />
    </bean>

</beans>

If you are not using component scanning, then you can uncomment the bean definition for the EmployeeDAO.

Test class

You can use the following code in order to test the code -

import java.util.List;
import org.netjs.dao.EmployeeDAO;
import org.netjs.model.Employee;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {
  public static void main(String[] args) {
    
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext
     ("appcontext.xml");
    EmployeeDAO dao = (EmployeeDAO)context.getBean("employeeDAOImpl");  
    
    // Uncomment this to find employee by ID
    /*Employee emp = dao.findEmployee(5);
    System.out.println("Name - "+ emp.getEmpName() + " Age - " + emp.getAge());*/
    
    List<Employee> empList = dao.findAllEmployees();
    System.out.println("Name - "+ empList.get(1).getEmpName() + " Age - " 
      + empList.get(1).getAge());
  }
}

RowMapper implementation as Lambda Expression

RowMapper interface has only single method mapRow which means it is a functional interface. Starting Java 8 it can be implemented as a lambda expression. Since same implementation is used by two methods findEmployee() and findAllEmployees() so it is better to implement it as a lambda block rather than as an inline lambda.

In that case findEmployee() and findAllEmployees() methods will change like this -

public Employee findEmployee(int EmpId) {
  return this.jdbcTemplate.queryForObject(SELECT_BY_ID_QUERY, getMap(), EmpId);
}

public List<Employee> findAllEmployees() {
  return this.jdbcTemplate.query(SELECT_ALL_QUERY, getMap());
}
    
private RowMapper<Employee> getMap(){
  // Lambda block
  RowMapper<Employee> empMap = (rs, rowNum) -> {
      Employee emp = new Employee();
      emp.setEmpId(rs.getInt("id"));
      emp.setEmpName(rs.getString("name"));
      emp.setAge(rs.getInt("age"));
      return emp;
  };
  return empMap;
}

Here it can be seen that lambda block is implemented inside method getMap(). Here lambda is assigned to a functional interface (RowMapper in this case) variable. It has two arguments rs and rowNum, since it is implementing mapRow() method of the RowMapper class so compiler will infer that rs and rowNum are of type ResultSet and int respectively.

That's all for this topic Spring JdbcTemplate Select Query Example. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Spring Tutorial Page


Related Topics

  1. Configuring DataSource in Spring Framework
  2. Spring NamedParameterJdbcTemplate Insert, Update And Delete Example
  3. Spring NamedParameterJdbcTemplate Select Query Example
  4. How to Inject Prototype Scoped Bean into a Singleton Bean in Spring
  5. Spring Profiles With Examples

You may also like-

  1. Spring Component Scan Example
  2. Excluding Bean From Autowiring in Spring
  3. @Resource Annotation in Spring Autowiring
  4. interface default methods in Java 8
  5. Is String Thread Safe in Java
  6. Difference Between Thread And Process in Java
  7. AtomicInteger in Java With Examples
  8. Java BlockingDeque With Examples