Posts

Showing posts from October, 2016

Map GET parameters to Object in Spring

It's possbile to map GET parameters to an object in Spring. It's really useful when we need to pass lots of parameters as query string e.g. submitting a search form with many parameters. The following controller demonstrates this.   @RestController @RequestMapping("hello") public class MyController {     @RequestMapping(value = "data", method = RequestMethod.GET)     public MyRequest getData(MyRequest request){             return request;     }     public static class  MyRequest {         private String name;          private int age;         public String getName(){return this.name;}         public int getAge(){return this.name;}         public void setName(String name){this.name=name;}          public void setAge(int age){this.age=age;}     } } Following GET request will create a MyRequest object with age=10 and name=Nayan GET hello/data?age=10&name=Nayan As we're sending the request object as response we'll get the follo

Pass state parameter from url in angular-ui-router

URL parameters are automatically sent as state parameters in angular-ui-router . All we need to do is declare the parameter names in state configuration. Here is an example of state configuration: .state('home.profile', {     url: '/profile?id',     templateUrl: 'templates/profile.html',     controller: 'ProfileCtrl' }) Here we've declared a parameter id in url attribute.  Now if we hit the url with parameter id e.g /profile?id=1234343 , w e'll be able to receive id=1234343 in state params.  We'll also be able to pass state parameter through ui-sre f lik e the following: <a ui-sref="home.profile({id: '1234343' })">Go to profile</a> Here is an example controller that demonstrates how to receive the parameter : .controller('ProfileCtrl', ['$scope', '$stateParams',     function ($scope, $stateParams) {         $scope.id = $stateParams.id; // id will be 1234343          } ])

Run tasks in background in Spring

Why background task? There are tons of examples where we often need to run a task in background e.g. sending an email, sms or notification, writing some log in file etc. If a task is not required to maintain atomicity and can be executed after some delay, it's a good candidate to run in background.   How to run tasks in background in Java? In Java, the easiest way to run a task in background is to create a new thread and execute it. It's quite simple. Here is how to do this: new Thread(new Runnable(){ @Override public void run(){ // your background task } }).start(); It's easy! But there are some maintenance problem with the above code. The major problem is - there is no way to control how many background tasks we want to run simultaneously. For example, if 1000 users registers in your application at a time and you create 1000 background threads to send them a confirmation email, maybe you'll be in trouble. So you ne