Wednesday, 31 October 2018

Introduction to Spring MVC

MVC stands for Model View Controller. Spring Web MVC is a web framework built on top of Servlet API. it is built on controller pattern and MVC guide lines.

Brief about MVC
In MVC, UI code is never mixed with business logic code.

In MVC, application is divided into 3 components.
         M - Model: Represents the data, a model can be any java object with properties, those can be accessed via getters and setters
         V - View: Represents the user interface (html, jsp)
         C - Controller: Manages the application flow

I would recommend you to go through my below tutorial on mvc pattern.

How Spring MVC works?
I depicted basic flow of spring mvc in below diagram.




1.   In Spring MVC, all the requests are initially redirected to DispatcherServlet. DispatcherServlet is responsible to handle an URI and find the appropriate handlers (i.e. methods declared in Controller classes) and render views (JSPs, html files). DispatcherServlet is also called as FrontController in spring MVC.

2.   Once the DispatcherServlet receives the request, it passes the request to specific handlers using handler mappings.  Handler mappers parse the request url and detect the controller method, that can abel to handle this request. Spring provides many handlers (BeanNameUrlHandlerMapping, RequestMappingHandlerMapping, RequestMappingInfoHandlerMapping, SimpleUrlHandlerMapping, WebSocketHandlerMapping) mapping implementations, you can choose the one that suits to your application needs.
3.   Controller class is responsible for generating the data, specifying the view that can render this data. Controller sends both the data, view information (ModelAndView) details to front controller (DispatcherServlet).
4.   Front controller send the view information to the ViewResoolver to know the actual location of the view page (html, jsp etc.,) that can render the view using this data.
5.   Now the front controller has the java object (that holds the data) and exact location of the view file(jsp, html etc;,). By using the data, view file, front controller send the response back to the user.


Is Spring MVC based on servlet/jsp technologies?
Yes

I am using below maven dependencies throughout the tutorial.

                  <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
                  <dependency>
                           <groupId>org.springframework</groupId>
                           <artifactId>spring-webmvc</artifactId>
                           <version>5.0.6.RELEASE</version>
                  </dependency>

                  <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator -->
                  <dependency>
                           <groupId>org.hibernate</groupId>
                           <artifactId>hibernate-validator</artifactId>
                           <version>6.0.10.Final</version>
                  </dependency>

                  <!-- https://mvnrepository.com/artifact/javax.validation/validation-api -->
                  <dependency>
                           <groupId>javax.validation</groupId>
                           <artifactId>validation-api</artifactId>
                           <version>2.0.1.Final</version>
                  </dependency>

Previous                                                 Next                                                 Home

Spring MVC Tutorial

Introduction to Spring MVC
Spring Web MVC: Hello World Application
Spring web mvc: Specify context configuration location to dispatcher servlet
Spring Web MVC: ModelAndView tutorial
Spring: Working with WebApplicationInitializer
Spring MVC: Get http status codes
Spring MVC: Handler Mapping Tutorial
Spring mvc: BeanNameUrlHandlerMapping
Spring mvc: BeanNameUrlHandlerMappingConfig annotation based example
Spring mvc: RequestMapping Handler example
Spring mvc: SimpleUrlHandlerMapping example
Spring mvc: SimpleUrlHandlerMapping annotation based configuration
Spring mvc: Multi Action controller class
Spring mvc: @RequestMapping annotation example
Spring mvc: @PathVariable tutorial
Spring mvc: @PathVariable: Handling multiple path variables
Spring web mvc: Map request parameters
Spring web mvc: @RequestParam form handling example
Spring web mvc: Map request parameters to a map object
Spring web mvc: read complex objects information
Spring web mvc: @ModelAttribute: Map the request parameters to java object
Spring web mvc: @ModelAttribute on method
Spring mvc: Data binding with collections
Spring web mvc: BindingResult : Handle data binding error
Spring web mvc: Bind Date type
Spring web mvc: property editors: customize properties binding
Spring web mvc: custom property editor
Spring web mvc: Form validation
Spring web mvc: Customize bean validation messages
Spring web mvc: customizing error messages using Spring MessageSource
Spring mvc: Reload the validation properties file dynamically
Spring mvc: place holders in validation messages properties
Spring mvc: Custom form validation annotation
Spring mvc: Parameters to custom validation annotation
Spring mvc: Interceptors
Spring mvc: Mapping urls to interceptors
Spring mvc: Internationaliztion, Localization support
Spring mvc: Internationalization support part-2
Spring mvc: Exception handling at controller level
Spring mvc: Exception handling at application level
Spring mvc: Exception handling using configurations
Spring mvc: Exception handling: http response codes

Monday, 29 October 2018

JavaScript: Monitor variables, expressions using watch

JavaScript debugger provides a watch section, where you can watch for the variables, expressions.

Let me explain with an example.

HelloWorld.html
<!DOCTYPE html>
<html>

<body>

    <script>
        function factorial(n) {
            if (n <= 0) {
                return 1;
            }
            var result = 1;

            for (var i = 1; i <= n; i++) {
                result *= i;
            }
            return result;
        }

        var fact = factorial(5);
        document.write("Factorial of 5 is : " + fact);
    </script>

</body>

</html>

Open ‘HelloWorld.html’ in browser.

Turn on debugger.

Add the debug point inside for loop.

Reload the page HelloWorld.html.
Click on + button in Watch section.

Type the variable result, to see the value of variable ‘result’.

Resume execution, you can observe value of result is changed to 2.


Previous                                                 Next                                                 Home

Saturday, 27 October 2018

JavaScript: Debugger: Working with call stack

Callstack is used to trace the flow of execution.

For example,

HelloWorld.html
<!DOCTYPE html>
<html>

<body>

    <script>
        function a() {
            var x = 10;
            document.write("Value of x is " + x + "<br />");
        }

        function b() {
            var y = 11;
            document.write("Value of y is " + y + "<br />");
            a();
        }

        function c() {
            var z = 12;
            document.write("Value of z is " + z + "<br />");
            b();
        }

        c();
    </script>

</body>

</html>

Open HelloWorld.html in chrome browser.

Turn on the debugger.

Add debug points on the lines 8, 13, 19 and 23.

Reload the page and control pauses at line 23.

Resume the execution by clicking on Resume button.
As you see the call stack, it is clearly telling the control is at line 19. You can observe local variable z is set to the value 12.

Click on the Resume button again.

As you see the Call Stack, control goes from function c to b and control is at line number 13.

As you see Local Scope section, variable y is set to 11.

Click on Resume button again.

As you see Call Stack section, control goes from function C to function b and from function b to function a. Control is at line number 8 now.

As you see local scope section, variable x is assigned with value 10.

While debugging real time applications, call stack helps developers a lot in identifying the issues.

Previous                                                 Next                                                 Home

Thursday, 25 October 2018

JavaScript: Continue Execution from any point

Once the debugger is turned on, you can continue execution from any point.

HelloWorld.html
<!DOCTYPE html>
<html>

<body>

    <script>
        document.write("Hello World<br />");
        document.write("Hi, How are you<br />");
        document.write("I am fine, Thank youe<br />");
        document.write("How is your JavaScript Learning<br />");
        document.write("Going cool!!!!!!<br />");
    </script>

</body>

</html>

Open HelloWorld.html in chrome browser.

Turn on the debugger.

Add the debug point in first line of JavaScript statement.


Now, right click on any further java script statement and continue the execution from there.

For example, I right click on line number 9, and click on the button ‘Continue to here’.


Statements till line number 9 are executed.


Previous                                                 Next                                                 Home

JavaScript: Deactivate all the breakpoints

You can deactivate all the breakpoints in one shot by clicking on deactivate button.




Previous                                                 Next                                                 Home

JavaScript: Adding Conditional break points

You can add conditional breakpoints to the application. Application pauses at the break point, when the condition evaluates to true, else not.

How to add conditional breakpoint?
HelloWorld.html
<!DOCTYPE html>
<html>

<body>

    <p>Click on the buttons to perform Arithmetic Operations</p>

    <button onclick="sum()">Add Numbers</button>

    <p id="demo"></p>

    <script>
        function sum() {
            var input1 = parseInt(prompt("Enter first Argument", 0));
            var input2 = parseInt(prompt("Enter Second Argument", 0));
            var result = input1 + input2;

            console.log("Sum of %d and %d is %d", input1, input2, result);
            document.getElementById("demo").textContent = "Result : " + result;
        }
    </script>

</body>

</html>

Open HelloWorld.html page in browser.

Turn on the debugger.

Add one break point, Right click on the breakpoint -> Edit breakpoint…


I added one conditional breakpoint (result >=100) while writing to the document. Application pauses its execution, when the result is > 100.









Previous                                                 Next                                                 Home

Wednesday, 24 October 2018

JavaScript: debugger statement

When the debugger is turned on, then debugger statement pauses the execution of JavaScript application.

HelloWorld.html
<!DOCTYPE html>
<html>

<body>

    <p>Click on the buttons to perform Arithmetic Operations</p>

    <button onclick="sum()">Add Numbers</button>

    <p id="demo"></p>

    <script>
        function sum() {
            var input1 = parseInt(prompt("Enter first Argument", 0));
            var input2 = parseInt(prompt("Enter Second Argument", 0));
            var result = input1 + input2;

            //When the debugger is turned on, then the application pauses here
            debugger;

            console.log("Sum of %d and %d is %d", input1, input2, result);
            document.getElementById("demo").textContent = "Result : " + result;
        }
    </script>

</body>

</html>

Load application in browser and turn on the debugger. After entering the inputs to the application, you can observe control stops at debugger statement.



Previous                                                 Next                                                 Home

Tuesday, 23 October 2018

Debug JavaScript Application in Chrome Browser

In this post, I am going to explain how to debug an application in Chrome Browser.

You are going to learn
a.   Key Terms in debugging the application
b.   How to add debug points and inspect the code

Key Terms in debugging the application
Breakpoint: It is the place, where you are informing debugger to stop execution. Once debugger stopped at breakpoint, you can inspect the data, stack traces etc.,

Step Over: When you click on this button, debugger move the control to next line.

Step Into: It is used to step into the function body.

Step out: Used to stepping out of the currently executing function.

How to add debug points and inspect the code?
Let me try to explain with an example.

HelloWorld.html
<!DOCTYPE html>
<html>

<body>

    <p>Click on the buttons to perform Arithmetic Operations</p>

    <button onclick="sum()">Add Numbers</button>

    <p id="demo"></p>

    <script>
        function sum() {
            var input1 = parseInt(prompt("Enter first Argument", 0));
            var input2 = parseInt(prompt("Enter Second Argument", 0));
            var result = input1 + input2;

            console.log("Sum of %d and %d is %d", input1, input2, result);
            document.getElementById("demo").textContent = "Result : " + result;
        }
    </script>

</body>

</html>

Open ‘HelloWorld.html’ in chrome browser.


Right click on the body of html page -> Inspect.

It opens developer tools on right side of the window. Click on Source tab, you can able to see the source code of the application.



Click on the file ‘HelloWorld.html’ under Page tab, it opens the source code.

Click on line numbers in the source code to add debug points.


For example, I added debug points on line 13 and 18.

Click on the button ‘Add Numbers’.

You can see that application stops at debugger point.


Click on ‘Step Over’ button to move to the new line.

After entering the user input, you can see the data at Scope section. This section displays all the local and global variable information. Beside scope section, there is a ‘Call Stack’ window, that gives information about application call stack.

At the bottom of Call Stack section, there is Breakpoints section, it shows all the breakpoints. You can disable the breakpoint by unchecking the checkbox.



Previous                                                 Next                                                 Home

Sunday, 21 October 2018

JavaScript: Map.prototype.values(): Get all the values in Map

Map.prototype.values()
This method return all the values in the map in insertion order.

Example
var values = countriesMap.values();

for(value of values){
  console.log(value);
}

Find the below working application.

HelloWorld.js
var countriesMap = new Map();

countriesMap.set("Bahrain", "Manama");
countriesMap.set("Cameroon", "Yaounde");
countriesMap.set("Norway", "Oslo");
countriesMap.set("India", "New Delhi");

var values = countriesMap.values();

for(value of values){
  console.log(value);
}


Output
Manama
Yaounde
Oslo
New Delhi




Previous                                                 Next                                                 Home

JavaScript: Map.prototype.set(key, value): Set the value for key

Map.prototype.set(key, value)
This method set the value for given key.

Find the below working application.

HelloWorld.js
var countriesMap = new Map();

countriesMap.set("Bahrain", "Manama");
countriesMap.set("Cameroon", "Yaounde");
countriesMap.set("Norway", "Oslo");
countriesMap.set("India", "New Delhi");

console.log("Is countriesMap has Norway : " + countriesMap.has("Norway"));
console.log("Is countriesMap has India : " + countriesMap.has("India"));
console.log("Is countriesMap has Australia : " + countriesMap.has("Australia"));


Output
Is countriesMap has Norway : true
Is countriesMap has India : true
Is countriesMap has Australia : false



Previous                                                 Next                                                 Home

JavaScript: Map.prototype.has(key): Check for existence of key

Map.prototype.has(key)
This method returns true, if the map cotains given key, else false.

Find the below working application.

HelloWorld.js
var countriesMap = new Map();

countriesMap.set("Bahrain", "Manama");
countriesMap.set("Cameroon", "Yaounde");
countriesMap.set("Norway", undefined);
countriesMap.set("India", "New Delhi");

console.log("Is countriesMap has Norway : " + countriesMap.has("Norway"));
console.log("Is countriesMap has India : " + countriesMap.has("India"));
console.log("Is countriesMap has Australia : " + countriesMap.has("Australia"));


Output
Is countriesMap has Norway : true
Is countriesMap has India : true
Is countriesMap has Australia : false




Previous                                                 Next                                                 Home

JavaScript: Map.prototype.keys(): Get all the keys of map

Map.prototype.keys()
This method returns an iterator, that contains all the keys of map.

  var keys = map.keys();
 
  for(var key of keys){
    console.log(key + " : " + map.get(key));
  }

Find the below working application.

HelloWorld.js
function printMap(map){
  console.log("***************************");
  console.log("Total elements in countriesMap are : " + map.size);
  
  var keys = map.keys();
  
  for(var key of keys){
    console.log(key + " : " + map.get(key));
  }
}

var countriesMap = new Map();

countriesMap.set("Bahrain", "Manama");
countriesMap.set("Cameroon", "Yaounde");
countriesMap.set("Norway", "Oslo");
countriesMap.set("India", "New Delhi");
countriesMap.set("Russia", "Moscow");
countriesMap.set("Spain", "Madrid");

printMap(countriesMap);

Output
***************************
Total elements in countriesMap are : 6
Bahrain : Manama
Cameroon : Yaounde
Norway : Oslo
India : New Delhi
Russia : Moscow
Spain : Madrid

Previous                                                 Next                                                 Home

JavaScript: Map.prototype.get(key): Return the value associated with key

Map.prototype.get(key)
This method returns the value associated with this key, or undefined, if there is not key present.

Example
  var keys = map.keys();
 
  for(var key of keys){
    console.log(key + " : " + map.get(key));
  }

Find the below working example.

HelloWorld.js
function printMap(map){
  console.log("***************************");
  console.log("Total elements in countriesMap are : " + map.size);
  
  var keys = map.keys();
  
  for(var key of keys){
    console.log(key + " : " + map.get(key));
  }
}

var countriesMap = new Map();

countriesMap.set("Bahrain", "Manama");
countriesMap.set("Cameroon", "Yaounde");
countriesMap.set("Norway", "Oslo");
countriesMap.set("India", "New Delhi");
countriesMap.set("Russia", "Moscow");
countriesMap.set("Spain", "Madrid");

printMap(countriesMap);


Output

***************************
Total elements in countriesMap are : 6
Bahrain : Manama
Cameroon : Yaounde
Norway : Oslo
India : New Delhi
Russia : Moscow
Spain : Madrid




Previous                                                 Next                                                 Home