Sunday, 14 September 2014

Difference between block level elements and inline elements in HTML

Background

Most of you might already know HTML stands for HyperText Markup Language and is the standard markup language used to create web pages. HTML consists of elements. Most of the elements have stating and ending tag. For eg. <div></div>. Some don't need. For eg. <br />. You can read more about it on Wikipedia or w3schools. In this post I am going to cover what are basic blocks in a HTML.

Blocks in HTML

Elements in HTML are categorized into two types- 
  1. block level elements
  2. inline elements

When block level elements are rendered in a webpage they generally begin and end with a new line. For example <ul>, <table>, <h1>, <p>  tags. Inline elements comprise of tags that come inside(nested) block level element tags. For example <a>, <img>, <b>, <td>.

Difference

Picking this up directly from the W3 documentation -

Certain HTML elements that may appear in BODY are said to be "block-level" while others are "inline" (also known as "text level"). The distinction is founded on several notions:

  • Content model : Generally, block-level elements may contain inline elements and other block-level elements (Exception to this on paragraph/p tag). Generally, inline elements may contain only data and other inline elements. Inherent in this structural distinction is the idea that block elements create "larger" structures than inline elements.
  • Formatting : By default, block-level elements are formatted differently than inline elements. Generally, block-level elements begin on new lines, inline elements do not.

Below are some details on <div> and <span> elements which I have directly picked up from W3schools.I have used them a lot in web pages and JSPs but never knew the basic difference between them and their intended purpose.

<div>  element

  • The HTML <div> element is a block level element that can be used as a container for grouping other HTML elements.
  • The <div> element has no special meaning. Except that, because it is a block level element, the browser will display a line break before and after it.
  • When used together with CSS, the <div> element can be used to set style attributes to large blocks of content.
  • Another common use of the <div> element, is for document layout. It replaces the "old way" of defining layout using tables. Using <table> elements for layout is not the correct use of <table>. The purpose of the <table> element is to display tabular data.

<span> element

  • The HTML <span> element is an inline element that can be used as a container for text.
  • The <span> element has no special meaning.
  • When used together with CSS, the <span> element can be used to set style attributes to parts of the text.


Nesting block level elements inside the <p> tag… right or wrong?

As the documentation clearly says

The P element represents a paragraph. It cannot contain block-level elements (including P itself).

You cannot use block level elements inside paragraph tag. Well no body stops you from adding it but here's what will happen  - opening <div> or any other block level tag will automatically close the <p> element.

Related Links



Saturday, 13 September 2014

Method overloading in Javascript

Background on method overloading

If you are from java or C# background then you must be familiar with the concept of method overloading. You can refer to following post on method overloading in java


Just to summarize (as far as java is considered) two methods are said to be overloaded if they have same method name but different method signatures. Also note method signature is the name of the method plus the number and types of arguments. Signature has nothing to do with return type. Also two methods cannot have same signature.

So for example

public void foo(String arg1);
public void foo(String arg1, String arg2);

are overloaded methods. Also note method overloading is a compile time phenomenon. Which method is to be used for execution is decided at compile time depending on the method signature.

Okay enough of Java overloading background. Lets head to javascript.



Method overloading in Javascript

Method overloading is not possible in Javascript in strict sense!

yeah that's right. You should not do something like

function foo(x)
{
  //some logic 
}

function foo(x,y)
{
  //some logic 
}

Why have i written "should not" rather than "cannot" is because no body can stop you from writing the methods above. It's just that it will not serve it's intended purpose. Why not ?-

The issue is that JavaScript does NOT natively support method overloading. So, if it sees/parses two or more functions with a same names it’ll just consider the last defined function and overwrite the previous ones.

So  foo(x,y) wold override foo(x) in above case.  So if I call method as foo(1) and as per what I have written above foo(x,y) will overwrite foo(x) why is there no some kind of error or Exception ? 

Well because when you specify arguments in the round brackets - they are just like synthetic sugar coating on the real arguments. This is where there is another JavaScript feature, which a lot beginners miss out on. In any JavaScript method, the arguments passed into the method are accessible via an Object array with the name arguments.

So lets say you now have a method

function func1(a,b,c)
{

   //some logic 
} 

and you call func1(1,2,3,4) then a=1(arguments[0]), b=2(arguments[1]),c=3(arguments[2]) and you c(arguments[3]). So as I said arguments inside round brackets are just to improve the functionality.


In fact for above method you can also call it like func1(1,2) and in this case arguments c and d will be undefined. Following the same argument above you can have a function defined with no argument and call it with any number of arguments.

You can check any variable if it is undefined in the following way (using typeof ) -


function func1(a,b,c,d)
{
   if(typeof a == 'undefined')
   {
      alert("a is undefined"); 
    }
     // and so on... 
}


So how do we resolve this issue ?

One of the way I think is suitable for most of the case is follows -

Lets say you have method

function foo(x)
{

} 


Instead of overloading method which is not possible in javascript you can define a new method

fooNew(x,y,z)
{
}


and then modify the 1st function as follows -

function foo(x)
{
  if(arguments.length==2)
  {
     return fooNew(arguments[0],  arguments[1]);
  }
} 

If you have many such overloaded method consider using switch than just if-else statements.

Related Links


Monday, 8 September 2014

Lifecycle of SimpleFormController of Spring MVC

Background

Yes SimpleFormController has been deprecated since Spring 3.0 but is still widely used. So  in this post I am going to discuss the lifecycle or workflow of this controller.

Steps

Workflow is as follows and it is controlled by AbstractFormController class - 

  1. The controller receives a request for a new form (typically a GET).
  2. Call to formBackingObject() which by default, returns an instance of the commandClass that has been configured (see the properties the superclass exposes), but can also be overridden to e.g. retrieve an object from the database (that needs to be modified using the form).
  3. Call to initBinder() which allows you to register custom editors for certain fields (often properties of non-primitive or non-String types) of the command class. This will render appropriate Strings for those property values, e.g. locale-specific date strings.
  4. Only if bindOnNewForm is set to true, then ServletRequestDataBinder gets applied to populate the new form object with initial request parameters and the onBindOnNewForm(HttpServletRequest, Object, BindException) callback method is called. Note: any defined Validators are not applied at this point, to allow partial binding. However be aware that any Binder customizations applied via initBinder() (such as DataBinder.setRequiredFields(String[]) will still apply. As such, if using bindOnNewForm=true and initBinder() customizations are used to validate fields instead of using Validators, in the case that only some fields will be populated for the new form, there will potentially be some bind errors for missing fields in the errors object. Any view (JSP, etc.) that displays binder errors needs to be intelligent and for this case take into account whether it is displaying the initial form view or subsequent post results, skipping error display for the former.
  5. Call to showForm() to return a View that should be rendered (typically the view that renders the form). This method has to be implemented in subclasses.
  6. The showForm() implementation will call referenceData(), which you can implement to provide any relevant reference data you might need when editing a form (e.g. a List of Locale objects you're going to let the user select one from).
  7. Model gets exposed and view gets rendered, to let the user fill in the form.
  8. The controller receives a form submission (typically a POST). To use a different way of detecting a form submission, override the isFormSubmission method.
  9. If sessionForm is not set, formBackingObject() is called to retrieve a form object. Otherwise, the controller tries to find the command object which is already bound in the session. If it cannot find the object, it does a call to handleInvalidSubmit which - by default - tries to create a new form object and resubmit the form.
  10. The ServletRequestDataBinder gets applied to populate the form object with current request parameters.
  11. Call to onBind(HttpServletRequest, Object, Errors) which allows you to do custom processing after binding but before validation (e.g. to manually bind request parameters to bean properties, to be seen by the Validator).
  12. If validateOnBinding is set, a registered Validator will be invoked. The Validator will check the form object properties, and register corresponding errors via the given Errors object.
  13. Call to onBindAndValidate() which allows you to do custom processing after binding and validation (e.g. to manually bind request parameters, and to validate them outside a Validator).
  14. Call processFormSubmission() to process the submission, with or without binding errors. This method has to be implemented in subclasses.


Above was the workflow  as specified in the Spring documentation of AbstractFormController. 

If it's confusing refer to following diagrammatic representations and try to co-relate

Diagrammatic Representation



Note :  If there are any errors in command object fields binding form will be reloaded (as shown in Request 2 of above diagram and after processFormSubmission(), showForm() and referenceData() are again called). onSubmit() is never called if this happens.

Typically a Spring bean lifecycle of a SimpleFormController would look something like below - 



Understanding some basic methods

  • isFormSubmission() : This method determines whether form is submitted (a POST request) or is for initial viewing (a GET request). This method is the base on which the two workflows of SimpleFormController are split.
  • formBackingObject() : This method returns an instance of command object which is the form Object. You can specify the class of this Object by setCommandClass( ) method. Or you can directly specify it in your bean configuration file -

    <property name="commandClass">
    <value>org.opensourceForgeeks.FormBackingObject</value>
    </property>

  • initBinder() : This method is called after the form command object is created and data binder is created by the controller. Developers can override this method to register custom PropertyEditor.
  • isValidateOnBinding(): If this method returns true then the binding validations are performed. By default it is set to true and final. Only way to change it is through setValidateOnBinding() method.
  • referenceData(): This method is used to provide reference data if any. Do not confuse it with formBackingObject() method where form Object is created. This method is used to provide any extra reference data that model may need to render UI page other that the command object. Whole model is then sent  to the View set by formView property of the bean in dispacher-servlet.xml file. Form View will then be rendered (See above diagrams for reference).

Related Links

Tuesday, 2 September 2014

Calling JavaScript function in href vs. onclick

Background

There are multiple ways to call a Javscript function in an anchor tag. You can put the method in href attribute or you can use onclick event or jquery events. This post is about good practices while calling a javascript function in such a scenario.


Usage in order of  increasing good practice


<a id="myLink" href="javascript:MyFunction();">link text</a>
 
<a id="myLink" href="#" onclick="MyFunction();">link text</a>
 
<a id="myLink" href="#" onclick="MyFunction();return false;">link text</a>
 
<a id="myLink" title="Click to do something" href="#" onclick="MyFunction();return false;">link text</a>
 
<a id="myLink" title="Click to do something" href="PleaseEnableJavascript.html" onclick="MyFunction();return false;">link text</a>

But the best practice as of now is to use jquery and attach an even handler to the elements id. Something like -

$('#myLink').click(function()

  {

     MyFunction();

     return false;

  }); 

 Notes

  • The onclick won't fire if someone middle-clicks on your link to open a new tab or if they have JavaScript disabled.
  • In case javascript is enabled adding return false in  onclick will will prevent browser from following the link.
  •  If you don't have a link in href attribute you should do javascript:void(0) rather than # in the href attribute.  '#' will take the user back to the top of the page if it is present in the href attribute and onclick is not returning false.

 

Related Links


Saturday, 30 August 2014

JAXB Tutorial for Java XML binding with annotations

JAXB

JAXB stands for JAVA Architecture for XML bindings. We will come to it in some time. Before that we need to understand a even basic concept - Serialization. Simply speaking Serialization is the process of turning an object in memory into a stream of bytes so that it can be transferred over a network or stored in a persistent storage.


There are various ways to serialize an object. For eg.

  1.  Serialization via XML. Convert the Object to XML transfer it and then convert it back to XML. 
  2. You can do the save via JSON (Javascript object notation).
  3. Or you can use the Serialization provided by Java i.e by making your class implement Serilizable interface.
In this post we will see how can we serialize/de-serialize Objects to and from xml.

Note : The verbs Marshal and Unmarshal are synonymous with Serialize and Deserialize. Specially in XML serialization you will hear the words   Marshal and Unmarshal very frequently.


Dependencies ??

If you are using JDK 6 or higher version you don't have to worry about any dependencies as JAXB comes bundled with it. If you are using a lower version that Java 6 then you can download the jars from here. Download and add “jaxb-api.jar” and “jaxb-impl.jar” on your project classpath.

 To the code....

First Create a model class file in package opensourceforgeeks.model. Lets call it Employee.java . Add the following code to it.
package opensourceforgeeks.model;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

/**
 * 
 * @author athakur
 *
 */

@XmlRootElement
public class Employee {

    private String name;
    private int age;
    private int id;
    
    public String getName() {
        return name;
    }
    
    @XmlElement
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    
    @XmlElement
    public void setAge(int age) {
        this.age = age;
    }
    public int getId() {
        return id;
    }
    
    @XmlAttribute
    public void setId(int id) {
        this.id = id;
    }
    
    @Override
    public String toString() {
        return "Employee [name=" + name + ", age=" + age + ", id=" + id + "]";
    }

}
 


Next lets create a class to test this out.  Create class JAXBTest.java under package opensourceforgeeks.test. Add the following code to it and run - 

package opensourceforgeeks.test;

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import opensourceforgeeks.model.Employee; 
/**
 * 
 * @author athakur
 *
 */ 
 public class JAXBTest {

    public static void main(String args[]) {

        Employee employee = new Employee();
        employee.setName("Aniket");
        employee.setAge(23);
        employee.setId(101);

        try {

            File file = new File("C:\\Users\\athakur\\Desktop\\data.txt");
            JAXBContext jaxbContext = JAXBContext.newInstance(Employee.class);
            Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
            jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

            
            System.out.println("Serializing Data");
            //Serilization
            //put the xml in the file
            jaxbMarshaller.marshal(employee, file);
            //also print it on standard ouput
            jaxbMarshaller.marshal(employee, System.out);
            
            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            
            System.out.println("Deserializing Data");
            //Deserialization
            //read the xml to get the Object
            Employee newEmployee = (Employee) jaxbUnmarshaller.unmarshal(file);
            System.out.println(newEmployee);

        } catch (JAXBException e) {
            e.printStackTrace();
        }


    }

}
Your project structure should look like below - as per above conventions of-course. You are free to put the code anywhere you like :)


Output : 

On the standard output console you can see - 

Serializing Data
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employee id="101">
    <age>23</age>
    <name>Aniket</name>
</employee>
Deserializing Data
Employee [name=Aniket, age=23, id=101]

You can also verify the data in the file whose path you have provided. XML should be generated in that file. It will have same XML as shown on standard output. For more details you can refer to the tutorial provided on the JAXB official site.

NOTE1 : In the model classes that you annotate you need to have default constructor (If you do not have any constructors Java compiler will put one default no arg constructor for you). If you do not provide default constructor you will get following exception -

JAXBException occurred : 1 counts of IllegalAnnotationExceptions.

NOTE2 :  If you get following exception - 
No message body writer has been found for response class
Make sure you are annotating root element with @XmlRootElement

Summary

Its quite self explanatory - the bindings and the conversion. Got the following diagram from the web that explains it in simplest way -



Related Links

t> UA-39527780-1 back to top