Welcome to NALIN.

It's all about Technology and Programming.


This blog includes information to the trending technologies, hottest programming tutorials and solution to programming problems.


Do you want to contribute to this blog with your knowledge and skills? If yes, then contact us here


Thank you !!!

Generating HTML output in Servlet

Leave a Comment
If you want to handle requested URI in your web module, then it will be easy to generate HTML response using servlet code of yours instead of using template library. For examples, in my case, I tried out a simple Java DSL which easily generates output in HTML using the self written Servlet. Below is the complete code:

package nalin.servlet.web;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/index")
public class IndexServlet extends HtmlWriterServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HtmlWriter html = createHtmlWriter(req, resp);
        String message = getMessage(req, html);
        
        html.header()
            .h(1, "Welcome to Servlet Example")
            .p("Let's explore Java Servlet 3.x Features.")
            .p(message)
            .ul(
                html.link("Index", "/index"),
                html.link("Hello", "/hello"),
                html.link("Sys Props", "/sys-props")
            )
            .footer();
    } 

}

I had written a base HtmlWriterServlet class that exposes a method where an instance can be acquired a HtmlWriter builder. Wrapping of the HTML like builder has to benefit is that it's easy to read and similarly it helps generate correct good form tags. For example, the "ul" and "table" accepts Java List or Map object, and it generates the correct HTML tags.

Here is another example how I generate a table view of Java System Properties page with few lines of code:

package nalin.servlet.web;

import java.io.IOException;
import java.util.TreeMap;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/sys-props")
public class SysPropsServlet extends HtmlWriterServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HtmlWriter html = createHtmlWriter(req, resp);
        TreeMap sysProps = new TreeMap(System.getProperties());
        html.header()
            .h(1, "Java System Properties")
            .table(sysProps)
            .footer();
    }

}

The simple HtmlWriter class provides few HTML builder methods and it can help generate HTML links with relative context paths. You can easily further improve it to help generate more HTML code such as form tags etc.

Also, note that ServletResponse object let you have full control on writing custom responses, so you are not restricted to only returning HTML. You can write binary output such as PDF or even MP3 files. You simply need to control the Response Writer and the correct corresponding content mime type and size that will return.

How Servlet and JSP create sessions ?

1 comment
In Servlet, you may get the Session object by "httpServletRequest.getSession(true)". The "true" flag will create the session if it doesn't already exist, else it gets the existing session.

Now if you want to check whether you have the session exists or not (without have to create one if doesn't exist), you need to pass in "false" and then check for "null".

Session session = httpServletRequest.getSession(false);
if (session == null) {
  // do something without creating session object.

}

Now comes the trick part. If you run above code and then dispatch the request to render a JSP page, you might quickly come to find out that the container will create a new Session object still! It turns out that by default JSP will create new Session object if you do not have one! To disable this, you need to set this explicitly on top of the JSP page:

<% page session="false" %>

Only with this you will able to actually prevent creation of unnecessary Session object if you were to use JSP for output! Something to watch out for when debugging session based application.

Five reasons: Why is Java the best programming language?

Leave a Comment
Java is one of the best programming languages for development. The popularity and usage of Java are still increasing even after two decades which is a big time for any Programming language. There are only a few programming languages which seem hard to get replaced and Java is one of them. Here are 5 reasons why Java is the best programming Language.

1. Object Orientation

Java is an object-oriented programming language that supports all principles like Data Abstraction, Encapsulation, Polymorphism, Overloading, Overriding, and Inheritance. Which makes it as powerful as C++. We all know C++ is the extended version of C programming. Thus, it makes Java better than C programming.

2. Rich API

Another big reason to learn Java is it’s Rich API. Java provides API for almost everything you need in development like I/O, networking, utilities, XML parsing, database connection etc. Whatever left is covered by open source libraries like Apache Commons, Google Guava, and others.

3. Great collection of Open Source libraries

The big organisations like Apache, Google, and others has contributed to add a lot of great libraries, which makes Java development very easy, faster and cost effective.

4. Platform Independent and Free

In the 1990s, this was the main reason for Java’s popularity. The idea of platform independence is great, and Java’s tagline “write once run anywhere” was enticing enough to attract lots of new development in Java. This is still one of the reason of Java being best programming language, most of Java applications are developed in Windows environment and run in UNIX platform.

Java is free from the start, i.e. you don’t need to pay anything to create Java application. This FREE thing also helped Java to become popular among individual programmers, and among large organisations.

5. Wonderful Community and Documentation

There is Java community to help beginners, advanced and even expert Java programmers. Java actually promotes taking and giving back to community habit. Lots of programmers, who use open source, tester etc. The expert programmer provides advice FREE at various Java forums and StackOverflow. This is simply amazing and gives a lot of confidence to a newbie in Java.

Javadoc made learning easy and provide an excellent reference while coding in Java. With an advent of IDE, you don’t even need to look Javadoc explicitly in a browser, but you can get all information in your IDE window itself.


Java is everywhere, it’s on the desktop, it’s on mobile, it’s on a card, almost everywhere and so is Java programmers.
Integrated Development Environment (IDE) Like Eclipse and Netbeans made Java development much easier, faster and fluent. It’s easy to search, refactor and read code using IDEs.

Design Pattern: The Pipeline

Leave a Comment
Today I’ll have a look into the Pipeline pattern, a design pattern inspired from the original Chain of Responsibility pattern by the GoF.

The Chain Of Responsibility

Basically the Chain of Responsibility defines the following actors:
  1. Command: the object to be processed
  2. Handler: an object handling interface. There can be many handlers in the chain. This interface defines 2 methods
  • setSuccessor(Handler successor): defines the next successor in the chain to pass the command to
  • handle(Command command): handle the command
The goal of this pattern is to decouple the Command object from its processing chain. A new Handler can be easily added to the chain without breaking any existing code.


The disadvantage of this design is the number of operations needed when a new handler is added into the pipeline. You need to break an existing successor/predecessor link, insert the new handler then relink it to the chain. It is very similar to a linked list. If a successor link is badly set accidentally, the whole chain is broken.

In the context of dependency injection within a container (JEE or Spring) it is not easier either. 3 operations are required:
  • unlinking an existing handler
  • relinking the new handler with its successor
  • relinking the existing predecessor to the new handler

The Pipeline

When an user posts a new Tweet, it needs to be processed by several services:
  • contentValidationService: to limit the tweet size to N characters, including the URL shortening
  • xssEncodingService: encode the tweet content to prevent XSS (cross-site scripting) attacks
  • tweetService: simply persist the tweet in the repository
  • userlineService: put the tweet in the current user line
  • timelineService: put the tweet in the current user timeline
  • taglineService: put the tweet in the appropriate taglines if it contains tags
  • mentionlineService: put the tweet in the timeline of any mentioned users
  • contactsService: spread the tweet to the timeline of all followers of current user
As you can see, the tweet processing services resemble quite a lot to a pipeline of processors. And more importantly the processing order does really matter. xssEncodingService should be placed before the tweetService (responsible of the persistence in repository). Similarly, the tweetService needs to be placed before any line related service because in a multi-threaded environment, the tweet needs to be persisted before any user could read it.

The Pipeline pattern meet those requirements but is more flexible than the Chain Of Responsibility pattern. It defines the following actors:
  • Command: command object to be process. A tweet in our example
  • PipelineManager: central class of the pattern. Define the following attribute and method
    • handlers: list (ordered) of Handlers
    • doPipeline(Command object): execute the processing pipeline
  • Handler: an interface defining the process(Command object) method
Below is the formal UML class diagram:
The major difference with the Chain Of Responsibility pattern is the introduction of the PipelineManager actor. The flexibility of the Pipeline pattern comes from the fact that at any time, a new Handler can be injected into the pipeline through the PipelineManager.

Below is a sample Spring XML configuration illustrating dependency injection.

<bean id="tweetPipelineManager" class="service.pipeline.tweet.TweetPipelineManager">
    <property name="tweetHandlers">
        <list>
            <ref bean="tweetContentValidationService"/>
            <ref bean="xssEncodingService"/>
            <ref bean="tweetService"/>
            <ref bean="userlineService"/>
            <ref bean="timelineService"/>
            <ref bean="taglineService"/>
            <ref bean="mentionlineService"/>
            <ref bean="contactsService"/>
            <ref bean="retweetService"/>
        </list>
    </property>
</bean>

Adding a new tweetHandler is as easy as adding a new entry in the list of handlers. Furthermore, since the handlers collection is a List, the order is preserved.

HTML templating with jQuery

Leave a Comment
In this short article, we’ll see some techniques to generate DOM elements and section using jQuery and its chaining feature.

Dynamic DOM elements creation

There are 2 techniques out there to create dynamic DOM elements.
  1. Using the createElement() method on the Document standard oject:
    var myDiv = document.createElement("div");
    var mySpan = document.createElement("span");
    mySpan.createTextNode(displayedText);
    myDiv.appendChild(mySpan);

  2. Using jQUery
    var myDiv = $('div').append(($('span').html(displayText));
Clearly the second method is better and cleaner. However this technique is suitable only for occasionnal dynamic DOM creation. If you need to create iterable items (like a table or a list of items) with dynamic data, it’ll become quickly a nightmare.

HTML templating with jQuery

The idea

Here is a very common use case: you are designing a user search page. There is a search form with various parameters. Below the search section is the result section where you display all found users in a table.

In the old style architecture, a click on “Search” button will submit the form to the server, which will then execute the query and build the result table and render the response page. All the job is done server-side.

With RESTfull architecture, the server only takes care of the DB querying and will return a list of JSON objects as results. The client-side is responsible for the data formatting. There “HTML templating” comes into play.

The idea is to create a template row representing a result and hide it at the end of the page:

<div>
    <form id="searchForm">
        ...
        <button type="submit" onclick="doSearch()">Search</button>
        ...
    </form>
    <section id="resultArea">
        <table id="resultTable">
            <thead>...</thead>
            <tbody></tbody>
        </table>
    </section>
</div>    
<div id="templates" style="display:none;">
    <tr id="rowTemplate">
        <td class="name">Name</td>
        <td class="age">Age</td>
        <td class="skills">Java, C#, Python</td>
        <td class="xp">5 years</td>
    </tr>
     
    <span id="someOtherTemplate">
        ...
        ...
    <span>
</div>

As shown above, all the DOM element templates are nested inside a div container with style=”display:none;” so it will not be visible on the page.

The same div can contain several template elements, like our template row for search result or any other templates. You need to give them a unique id so they can be easily fetched using jQuery selector.

Implementation

Now let’s see how we can format result row upon reception of the JSON data from server. Let’s assume that the returned data is a list of JSON objects representing each an user details:

{
  "name": "John Skit",
  "age": "29",
  "skills": "Java, Groovy, HTML5",
  "xp": "7 years"
}

function doSearch()
{
    $.ajax({
        type: 'GET',
        url:  '/search',
        dataType: 'json',
        success: function(data)
        {
            $.each(data, function(index,user)
            {
                $('#rowTemplate').clone().attr('id','')
                .find('.name').html(data.name).end()
                .find('.age').html(data.age).end()
                .find('.skills').html(data.skills).end()
                .find('.xp').html(data.xp).end().
                .appendTo('#resultTable tbody');
            });
        }
    });
}

In the ajax success function, upon reception of the JSON data set, we iterate through the “data” list. For each user JSON we:
  1. clone the #rowTemplate
  2. clear its id
  3. find each row column by its class
  4. fill in its HTML content with JSON data
  5. append the whole row to the body of #resultTable
That’s pretty simple. The job is done with a jQuery chain using end() method to go back and forth to the row element .

Please notice that at step 2, we need to clear the id of the cloned element otherwise we’ll end up having several rows with the same id in the DOM, big trouble!

Of course, the example is quite straightforward because the logic is minimalist. If you have complex logics with if/else if blocks involved, all the jQuery chaining beauty is gone!

function doSearch()
{
    $.ajax({
        type: 'GET',
        url:  '/search',
        dataType: 'json',
        success: function(data)
        {
            var row;
            $.each(data, function(index,user)
            {
                row =$('#rowTemplate').clone().attr('id','');
 
                row.find('.name').html(data.name).end()
                .find('.age').html(data.age);
 
                // Age discrimination
                if(data.age > 50) 
                {
                    row.find('.age').addClass('oldDuffer'); 
                }
                 
                row.find('.skills').html(data.skills).end()
                .find('.xp').html(data.xp);
 
                // XP highlighting
                if(data.xp < 3) 
                {
                    row.find('.xp').addClass('junior'); 
                }
 
                row.appendTo('#resultTable tbody');
            });
        }
    });
}

Variable shadowing in Java

Leave a Comment
Today I’ll look into a rare feature of Java: variable shadowing. First, let me define what is a shadowed field or method:

A field is considered shadowed when;

  • a subclass of its declaring class declares a field with the same name
  • a variable having the same name and type is declared in the local scope
  • a method argument/parameter is declared with a same name and type

Local variable shadowing



public class MyClass{
    private int count = 10;
    private void localVariable(){
        int count = 5;
        System.out.println("count = "+ count);
    }
    public static void main(String[] args){
        MyClass test = new MyClass();
        test.localVariable();
    }
}

Result : count = 5

because the count local variable declared inside localVariable() method shadows the variable count declared at class level. If we want to access the instance variable, we need to add the this keyword.

private void localVariable(){
    int count = 5;
    System.out.println("count = "+ this.count);
}

Method argument shadowing

private int count;
public void setCount(int count){
    this.count = count;
}

The this keyword is mandatory to resolve the ambiguity. Without this, the compiler cannot know whether we are assigning the count method argument value to itself. If you remove the this keyword, you would get a compilation warning anyway.

Superclass field shadowing

Let’s consider the following classes:

public class SuperClass {

    protected String val = "SUPER_VAL";
    protected void display(){
        System.out.println("val = "+this.val);
    }
}
public class ChildClass extends SuperClass{

    private String val;
    public ChildClass(String value){
        this.val = value;
    }
    public static void main(String[] args){
        ChildClass child = new ChildClass("CHILD_VAL");
        child.display();
    }
}

The execution gives: val = SUPER_VAL

The val field has been declared in the SuperClass but is shadowed in the ChildClass because the latter declares another field with same name and type. Although the ChildClass has been instantiated with “CHILD_VAL”, the execution of child.display() gives you “SUPER_VAL”.

The reason is simple. When the child instance is created, there are 2 variables val. The one from SuperClass with value “SUPER_VAL” and the one from ChildClass with injected value “CHILD_VAL” through constructor.

When the display() method is called, since it is define in the SuperClass, it is the val field in the context of SuperClass which is used. Not surprising that the output shows “SUPER_VAL”.

public class ChildClass extends SuperClass
{
    private String val;
    public ChildClass(String value){
        this.val = value;
        super.val = value;
    }
    public static void main(String[] args){
        ChildClass child = new ChildClass("CHILD_VAL");
        child.display();
    }
}

In the above modified code, we force the value for the hidden val field in SuperClass with super.val = value, and the output gives: val = CHILD_VAL

Now let’s add another class in the hierarchy;

public class AncestorClass{
    protected String val = "ANCESTOR_VAL";
}
public class SuperClass extends AncestorClass{
    protected String val = "SUPER_VAL";
}
public class ChildClass extends SuperClass{
    private String val = "CHILD_VAL";
    public void displayVal(){
        System.out.println("val = " + super.val);
    }
    public static void main(String[] args){
        ChildClass child = new ChildClass();
        child.displayVal();
    }
}

Obviously, the output will display: val = SUPER_VAL

The question now is: what if we want to display the val value of AncestorClass ? Obviously the super keyword only refers to the first parent class up in the class hierarchy. Casting comes to the rescue. Indeed we can force the this keyword representing the current class instance to a particular type in the class hierarchy !

public class ChildClass extends SuperClass{
    private String val = "CHILD_VAL";
    public void displayVal(){
        System.out.println("val = " + ((AncestorClass) this).val);
    }
    public static void main(String[] args){
        ChildClass child = new ChildClass();
        child.displayVal();
    }
}

This time, we do have val = ANCESTOR_VAL

Happy Coding !

Issue analysis and solved : No mapping found for HTTP request with URI [/WEB-INF/views/home.html] in DispatcherServlet with name 'appServlet'.

Leave a Comment
WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/WEB-INF/views/home.html] in DispatcherServlet with name 'appServlet'

I got above PageNotFound (ERROR 404) message while loading home.html page in Spring Web MVC project with Google App Engine nature. But when I use home.jsp then it works fine.

Then I searched and analysed how the flow of servlet container goes through the request.

  1. First the DispatcherServlet is invoked by the Servlet Container.
  2. The DispatcherServlet finds a mapping which maps to the home method of the Controller and the home method returns a view name "home".
  3. Now the DispatcherServlet uses a View Resolver (InternalResourceViewResolver) to find the View to render the model through, since the name is "home", this maps to the /WEB-INF/view/home.html view.
  4. Now essentially a call is made to RequestDispatcher.forward("/WEB-INF/views/home.html")
  5. The Servlet container at this point tries to find the servlet which can handle /WEB-INF/views/home.html uri - if it had been a .jsp there is a JSPServlet registered which can handle rendering the jsp, however for *.html there is no servlet registered, so the call ends up with the "default servlet", which is registered with a servlet-mapping of / which probably the DispatcherServlet is.
  6. Now the Dispatcher servlet does not find a controller to handle request for /WEB-INF/views/home.html and hence the message that I saw during project run.
If you are also getting this type of error and you want this kind of a extension to be handled by the servlet container, say tomcat, you can register *.html extension to be handled by JSPServlet and then it should work cleanly. Or return forward:/resources/HelloWorld.html which will be considered a static file relative to your resources folder.

And one of my friend asked how he would register *.html extension to be handled by JSPServlet. So, I told him that it can be achieved in two simple steps.
  1. By adding this servletmapping for the JSP servlet.

    <servlet-mapping>
    <servlet-name>jsp</servlet-name>
    <url-pattern>*.html</url-pattern>
    </servlet-mapping>
    This tells the application container to use the the JSP servlet when serving html files.
  2. Comment out the <mime-mapping> for text/html mime type (*.html) files so that the container won't handle HTML files as static content.
Happy Debugging !