Saturday, February 9, 2013

How Spring MVC works

MVC is a very good design pattern which is widely used in applications with UI(Desktop or web).   In this pattern M is Model, V is the View and C is controller.   The advantage of design pattern is to separate the different responsibilities into 3 parts when dealing UI.   In general terms  Model represents the business data and logic, View is visual part where the data in Model is displayed and Controller is the link of Model and View.  Controller is the brain which decides what data is used and how data is viewed.    Each part in MVC has the clear and dedicated responsibly.   By using MVC pattern the applications with UI become easier to develop, modify and maintain. 


SpringMVC is a web framework provided by Spring based on MVC pattern.   This framework is built on top of JEE/Servlet and is request-driven.  So it means that some servelts will listen on some ports for the incoming request and each request will trigger the whole process of serving this request in MVC and the data or resources that the request asks for is presented.
The below shows the categories of SpringMVC using MVC terms.



In Spring MVC DispatcherServlet and Controllers act as the Controller and they receive the requests and decide how the request will be served and also decide which view is used.  Business objects and domain objects are the Model and the business objects are invoked by the controllers and the all data are in domain objects.   The domain objects will be passed to some JSP which are the View part.  The JSP will render the data in the domain objects.

DisptacherServlet

DispatcherServlet is the front controller in Spring MVC.   It is a HttpServlet that will receive the request and return the response.  DispatcherServlet is the key player in SpringMVC.  From the below brief work flow of SpringMVC you can see DispatcherServlet is the driving force that make the request served with the right response sent back to the client.    


  1. Receive the request from client
  2. Consult HandleMapping to decide which controller processes the request
  3. Dispatch the request to the controller   
  4. Controller processes the request and returns the logical view name and model back to DispatcherServlet
  5. Consult ViewResolver for appropriate View for the logical view name from Controller
  6. Pass the model to View implementation for rendering
  7. View renders the model and returns the result to DispatcherServlet
  8. Return the rendered result from view to the client
It is obvious that DispatcherServlet has a heavy workload.  It needs many other strategy objects and configuration to perform these work.   Each DispatcherServlet has its own specialized ApplicationContext: WebApplicationContext.


MappingHandler


One important work to be done before DispatcherServlet can dispatch the request to the Controller is to find out which controller is right one for this request.  DispatcherServlet uses MappingHandler strategy object to do so.   There are many MappingHandler implementations which uses different strategies to map the request to Controller.   By default DispatcherServlet will use BeanNameUrlHandlerMapping and DefaultAnnotationHandlerMapping.

public interface HandlerMapping {
      HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception;
}


Controller

After the mapping is resolved DispatcherServlet will dispatch the request to the Controller.  Controller does the real work of processing the request.  Also Controller is where programmers need to work most in developing SpringMVC applications.  Controller has the knowledge of processing the request and what logical view be used for different result of request processing.  Usually Controller doesn't do the real processing and it delegates the request processing to the service layer.   Another thing the Controller to do is to package the result of the processing into the Model, which will be rendered in the View finally.


ViewResolver

After the Controller finish the processing of request it will return the logical view name and the data to DispatcherServlet, which will decide the actual view to be used since the view name from Controller is logical name.   With the help of ViewResolver strategy object DispatcherServlet can find out physical view from the logical view name.   Similar to MappingHandler there are also many different strategies  for resolving the view based on the different view technologies.    Most commonly used implementation of ViewResolver is InternalResourceViewResolver.  

public interface ViewResolver {
      View resolveViewName(String viewName, Locale locale) throws Exception;
}


View

View is where the data in the Model is rendered as the required output for the client.   SpringMVC provides many implementations of View to generate different output such as JSP,Excel, PDF, XML and etc.   DispatcherServlet will invoke render method from selected View implementation to generate the output to be returned to the client.

public interface View {
      String getContentType();
      void render(Map<String, ?> model, HttpServletRequest request,  HttpServletResponse response) throws Exception;
}

Friday, February 8, 2013

Root WebApplicationContext and Child WebApplicationContext

SpringMVC uses one special ApplicationContext: WebApplicationContext in web application.   WebApplicationContext is the extension of ApplicationContext.   It has ServletContext and and beans in WebApplicationContext can access ServletContext if they implement the interface ServletContextAware.

In Spring ApplicationContext can be hierarchical.  One ApplicationContext can have multiple child ApplicationContext and can only have one parent.   Beans in child ApplicationContext can access the beans in parent.

In SpringMVC each DispatcherServlet has one WebApplicationContext.   So there may be more than WebApplicationContext if the web application has multiple DispatcherServlet. By default Spring always look for the ApplicationContext: your_dispatcherservlet_name-servlet.xml. These DispatcherServlet related WebApplicationContext should have MVC-specific configurations.   Other non MVC-specific configuration such as the beans for service or persistence layer should be in root WebApplicationContext.

In SpringMVC the root WebApplicationContext is bootstrapped by using ContextLoadListener specified as Listener in web.xml.



<web-app>
              ............
            <context-param>
                        <param-name>contextConfigLocation</param-name>
                        <param-value>
                                    /WEB-INF/classes/META-INF/applicationContext.xml
                                    /WEB-INF/classes/META-INF/applicationSecurity.xml
                        </param-value>

            </context-param>

            <listener>
                        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
            </listener>
              ............
</web-app>


The above is the example of configuration in web.xml for root WebApplicationContext.

MVC specific WebApplicationContext is loaded for each of DispatcherServlet.  It is defined in each of servlet in web.xml. The below is an example of configuration for a DispatcherServelt where a child WebApplicationContext is specified.



<web-app>
            ...........
.
            <servlet>
                        <servlet-name>mvc-dispatcher</servlet-name>
                        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
                <init-param>
                    <param-name>contextConfigLocation</param-name>
                    <param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
                </init-param>
                <load-on-startup>1</load-on-startup>
            </servlet>

            ............
</web-app>



Saturday, February 2, 2013

JavaScript as Object-Oriented Language


As some of experienced Java, C++ or C# programmers I used to think JavaScript as some kind of elementary programming languages when compared to the full-fledged OO languages such as Java or C#, or C++. However even JavaScript cannot do some advanced and complex things which we can do using Java, C# or C++ it is still an programming language with OO features. And programmers normally are so used to class-type OO languages - Java, C++ or C# they would find it hard to understand and confusing how to use the OO features in JavaScript. The below is aimed to help skilled Java, C++ or C# programmer to grab the essence of JavaScript OO features in short time.


Object concepts in JavaScript


Contrary to the impression of me and some of Java developers, JavaScript thinks heavily with object. Almost everything in JavaScript is object. At the first glance it is not so obvious because JavaScript doesn't explicitly show this like Java, C++, C#. But it is true that most of things are dealt with objects in JavaScript. A number, a string, a date, an array, a function or a custom-made object are all objects even with some primitive type like numbers.

var myAmount = 123.456;
var myAmount = new Number(123.456);

In above example the first line will declare one variable myAmount with the given value. Actually JavaScript will create one Number object. It is the same as the second line does.
The meaning of object in JavaScript is the same as in Java, C++, or C#. An object is a collection of data stored as properties and the methods that can be used to manipulate the data in the object.
The below example demonstrate the properties and the methods of JavaScript object. In the first line we declare one string object with the value as "This is a string" and the second line the property length of this string object is used. And in third line we invoke a method called toUpperCase of the string object.


var myString = "This is a string";
alert(myString.length)
var upperCasedVar = myString.toUpperCase();
 

So far the object in JavaScript looks very similar as Java, C++ or C# although object creation in JavaScript sometimes is not so obvious.

 

What does object in JavaScript look like?


 

Objects in JavaScript have properties and methods. The properties are the name-value pairs and method. These are exactly same as Java, C# or C++.
But there are something different in JavaScript. Java, C++ or C# are all class-based Object-Oriented languages. All properties and methods must be predefined in the class from which the object is instantiated. In JavaScript you can don't need to predefine them. All you need to do is to add the property name to the object and then give the value to this property. That's it.


var myLaptop = new Object();
myLaptop.make = "DELL";
myLaptop.model = "Inspiron";
myLaptop.year = 2011;
 

In the above example we create one object as myLaptop and then we add three properties to this myLaptop object.
For the properties in JavaScript object there is one thing which cannot be done in Java or other OO languages: You can delete one property from the object using keyword delete.
//Creates a new object, myobj, with 4 properties.
var myLaptop = new Object();
myLaptop.make = "DELL";
myLaptop.model = "Inspiron";
myLaptop.year = 2011;
myLaptop.uer = "Mark Chen";

//Removes the a property, leaving myLaptop with only 3 properties.
delete myLaptop.user;

 

Methods in JavaScript is similar to the properties. Methods of JavaScript object are the normal JavaScript functions which are assigned to the properties of the object.
The below example shows that one function is defined and assigned to the object: myLaptop. It becomes the method of that object and you invoke this method in this object.
var myLaptop = new Object();
myLaptop.make = "DELL";
myLaptop.startup = function() {
      return "Startup is done....";
};
myLaptop.startup();
document.write(myLaptop.make + "  " + myLaptop.startup());

 

How do you create object in JavaScript?


 

JavaScript provides some built-in objects. String, Date, Array, Math and Object are mostly common used. You can also have the custom-built objects.
There are many ways in JavaScript to create an object. Actually we have seen two different ways to create objects in the above examples: using new operator and using object initializer.
The below are some examples of creating JavaScript objects using new operator and object initializer.
var myDate = new Date(2013, 2, 11);

var myObj = new Object();

var anotherObj = {};

var myLaptop = new Object();
myLaptop.make = "DELL";
myLaptop.model = "INSPRION";
myLaptop.price = 1150.00;

var anotherLaptop = {make: "DELL", model:"INSPRION", price:1150.00}

 

Besides the new operator and object initializer you can also use constructor function. This way is very similar to Java, C# or C++. Constructor function is a JavaScript function which is used to set the properties and methods for the object. You can use new operator to invoke this function. What you get is a JavaScript object.
function Laptop(make, model, price) {
    this.make = make;
    this.model = model;
    this.price = price;
    this.startup = function() {
        alert(make+" "+model+" is started up.");
    }
}

var myLaptop = new Laptop("DELL", "INSPRION", 1150.00);


Inheritance and Prototype


Inheritance is one of most important characteristics of OO language. In class-based OO languages such as Java, C++ or C# inheritance is implemented using class and subclass. JavaScript also provides inheritance. But it is implemented using another concept called prototype.

So what is prototype in JavaScript? A prototype is a property in an object and this property actually is a reference to another object. But this prototype property is a bit special: the object will inherit all properties and methods from its prototype object.
The below is an example of using prototype to add one property and one method to an object.


function Laptop(make, model, price) {
    this.make = make;
    this.model = model;
    this.price = price;

}

// Adding the property to the prototype of Laptop object
// Adding the method to the prototype of Laptop object
Laptop.prototype.user = "Mark";
Laptop.prototype.startup = function() {
      alert(this.make+" "+this.model+" "+this.user + " is started up.");
}
     
var myLaptop = new Laptop("DELL", "INSPRION", 1150.00);

// Invoke the startup method which is inherited from prototype
myLaptop.startup();

 

The prototype property in JavaScript object is just another object. When you invoke new operator against Laptop function. The object which is created will automatically has one prototype property set as one empty object. But you can override this empty object with the object you want. In the below example the prototype of Laptop is set to Computer object. So all Laptop objects will have the properties and methods of Computer object.


function Computer(user) {
      this.user = "Mark";
      this.startup = function() {
            alert(this.user + " is started up.");
      }
}

function Laptop(make, model, price) {
    this.make = make;
    this.model = model;
    this.price = price;
}

Laptop.prototype = new Computer("Mark");
     
var myLaptop = new Laptop("DELL", "INSPRION", 1150.00);

myLaptop.startup();

 


 


 

Monday, January 14, 2013

What is the use of static import?


The use of static import in Java is quite simple: to provide the convenience to Java programmers when they use some fields or methods from a static class.
For example in your codes you want to use abs(int ) from static class Math.   Normally your codes will be like:

double d1 = Math.abs(-0.29);
double d2 = Math.abs(-0.39);


With using static import you don't need to specify Math class you can directly use abs(int) method.


import static java.lang.Math.*;
double d1 = abs(-0.29);
double d2 = abs(-0.29);

You can see that: you could save some time when you have many places to use abs(int) method in your Java codes since you don't need to type in Math for each invocation.

But in my opinion if in you Java file you have multiple static classes you should be cautious with using static import.   It may reduce the readability of your Java codes.  Any new comer who reads your codes first time may want to know which staic class a particular method belongs to and he may find it a bit harder to do so becuase of static import. 

Wednesday, December 12, 2012

Specify Java compiler version in Maven

Sometime you want to compile your Java codes in one particular version in Maven it is quite easy to do so by specifying this in maven-compiler-plugin.  It is shown as:


    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.0.2</version>
                <configuration>
                    <source>1.5</source>
                    <target>1.5</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

In the above example you specify Java is compiled in verison 1.5 and generated classes are compatible with JVN 1.5.

Monday, December 3, 2012

XQuery Short Tutorial - Part 2


This is the second part of XQuery Short Tutorial.   To view the first part click on this url: XQuery Short Tutoril - Part1

Variables

In XQuery a variable is very easy to be identified.  All XQuery variables always start with $.

There are two types of variables: global variable and local variable.  

Global variable implies that it can be accessible from anywhere within XQuery.   Global variable is declared in the prolog part in XQuery.

Local variable is only accessible within the scope where it is declared such as in one FLOWR expression.

One thing needs to be remembered that once variables are assigned they cannot be assigned with new value.

Example 1

declare variable $displayedText as xs:string := ‘No result found based on the given conditions’;


In above example one global variable of xs:string type is declared and assigned a value:  'No result found based on the given conditions'.

Example 2

let $products := (<product>
                    <id>143</id>
                    <name>Cable</name>
                  </product>,
                  <product>
                    <id>234</id>
                    <name>Adapter</name>
                  </product>)
return $products


FLOWR expression

FLOWR expression is essential in XQuery body part.  Actually the body part of one useful XQuery is consisted of many FLOWR expressions. In order to use XQuery effectively you should master FLOWR expression.

FLOWR stands for For, Let, Order, Where, Return.  This expression is used to iterate, assign, filter, order and retrieve one XML document.

The below is a FLOWR expression.

Example 3

let $result := $flightOpsData/FlightLeg
for $flight in $result/InboundFlights
return $flight


This FLOWR expression first assign the node FlightLeg under variable $flightOpsData to a local variable $result and then iterates a list of nodes of InboundFlights under the variable $result and then retrieve the list back.

The next example goes further to add where to filter the nodes to be returned.

Example 4

let $result := $flightOpsData/FlightLeg
for $flight in $result/InboundFlights
where $flight/ArrivalPort=’SYD’
return $flight


The above FLOWR expression will retrieve the flights whose ArrivalPort is SYD.

In the above 3 examples we have seen Let, For, Where, Return already now we add the last one: Order to the expression.

Example 5

let $result := $flightOpsData/FlightLeg
for $flight in $result/InboundFlights
where $flight/ArrivalPort=’SYD’
order by $flight/ArrivalDateTime
return $flight


This FLOWR expression will retrieve all the flights whose ArrivalPort is SYD and the retrieved result will be ordered by flight’s ArrivalDateTime.

When we get here we have use all clauses in a FLOWR expression.   In the reality not all clauses are needed to present in the expression.   When we write FLOWR expression we need to keep in mind the following point:

·         Each FLOWR expression should have return clause as its last clause.  It is mandatory.

·         where and order are optional.

·         At least either one of let clauses or one of for clauses should be used.

·         You can have multiple let clauses or multiple for clause.

·         FLOWR expression can be nested.


Functions

Like functions in other languages XQuery functions provides specialised functionality. Functions will make XQuery programming easier since you can reuse these functionalities and don’t need to implement it yourself.  They also make XQuery much easier to understand and maintain.

There are many built-in functions available for you to use immediately in your XQuery.  Also you can develop your own custom functions.

The custom functions are defined in prolog part in XQuery

The below is one example of XQuery function.

Example 6

 (: Function used to convert the duration into minutes :)
declare function xf:total-minutes-from-duration( $duration as xdt:dayTimeDuration? )  as xs:decimal? {
       $duration div xdt:dayTimeDuration('PT1M')
 } ;


You can see from the above. One function has the function name, function parameters, return parameter and implementation part.

Implementation part of function actually is the same as the body party of XQuery.   You can static and dynamic portions to implement your functionality. 

The function in example 6 is called xf:total-minutes-from-duration.  Its input parameter is $duration of type xds:dayTimeDuration and it will return the value(s) of type xs:decimal.   The function implementation part is: $duration div xdt:dayTimeDuration('PT1M').

The input parameters and return parameter can be typed or untyped.

Typed parameter means that you specify the type of the parameter.   These types can be atomic value type or node type.

The below are some example of types.

Example 7

xs:integer
xs:boolean
xs:anyAtomicType
xs:string
node()
element()
tns:ProductType


Function parameters can have no type.   No type means that you can pass anything (atomic value, node type or empty sequence) to the parameter. 

Function parameters can have modifier following the parameter name.   These modifiers are: ?, *. +.

Modifier ? means that you can one item or empty.   * means one or more than one items or empty.   + means one or more than one items.

The above rules also apply to the return parameter of the function.


Let us see one example listed as below.  In this function there are 3 typed function parameters.  One is a specific element type, second atomic type and the last generic element type.  And the last one can be one element or a sequence of elements or empty.    The return type of this function is generic element type and can be a sequence of elements or empty.

Example 8

declare function xf:filterFlightOpsData(
      $flightOperationsQueryRS1 aselement(tns:FlightOperationsQueryRS),
      $requestDateTime as xs:dateTime,
      $sortedFlightOpsDataList as element(ops:FlightOpsData)*) as element()* {
    (:  Funtion implementation is omitted here for brevity   :)
};


Make elements and attributes dynamically

Just XSLT XQuery also has the capability to create the element or attribute dynamically.   And this is quite useful in using XQuery. 

Actually it is rather simple to do in XQuery.

This is used to create element dynamically.

element {element_name} {element_value}


This is used to create attribute dynamically.

attribute {attribute_name} {attribute_value}


The below is one actual example that uses dynamic creation of attribute.   FlightSegements has two attributes: one is ID which is statically created and NumberOfStops which is dynamically created depending on if $FlightSegment has this attribute or not.

Example 9

<FlightSegment ID="{data($FlightSegment/@ID)}">
   if ($FlightSegment/@NumberOfStops)
   then
       attribute {"NumberOfStops"}{data($FlightSegment/@NumberOfStops)}
   else
    () 
</FlightSegment>