Tuesday, February 5, 2013

Java Data Time Format made simple


/**
     * Format a time from a given format to given target format
     * 
     * @param inputFormat
     * @param inputTimeStamp
     * @param outputFormat
     * @return
     * @throws ParseException
     */
    private static String TimeStampConverter(final String inputFormat,
            String inputTimeStamp, final String outputFormat)
            throws ParseException {
        return new SimpleDateFormat(outputFormat).format(new SimpleDateFormat(
                inputFormat).parse(inputTimeStamp));
    }
Sample Usage is as Following:
    try {
        String inputTimeStamp = "Tue Feb 05 13:59:44 IST 2013";

        final String inputFormat = "EEE MMM dd HH:mm:ss z yyyy";
        final String outputFormat = "yyyy.MM.dd GGG hh:mm aaa";

        System.out.println(TimeStampConverter(inputFormat, inputTimeStamp,
                outputFormat));

    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

How and When, does finally block get executed in java - deep thinking from C++ concepts RAI Resource Allocation is Initializtion


Does finally block runs even after block/object/function get returned?

Yes. Even if there was an Exception within catch block, finally will be executed.
If you are familiar with C++, just think finally as the destructor of an object. What ever the state of a statement within the object, ~Destructor will be executed. But you cant put return withinfinally[some compilers allow though].
See the code below: See how global variable y been changed. Also see how Exception1 been covered by Exception2.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace finallyTest
{
    class Program
    {
        static int y = 0;
        static int testFinally()
        {
            int x = 0;
            try
            {
                x = 1;
                throw new Exception("Exception1");
                x = 2;
                return x;
            }
            catch (Exception e)
            {
                x = -1;
                throw new Exception("Exception2", e);
            }
            finally
            {
                x = 3;
                y = 1;
            }
            return x;
        }

        static void Main(string[] args)
        {
            try
            {
                Console.WriteLine(">>>>>" + testFinally());
            }
            catch (Exception e)
            { Console.WriteLine(">>>>>" + e.ToString()); }
            Console.WriteLine(">>>>>" + y);
            Console.ReadLine();
        }
    }
}
output:
    >>>>>System.Exception: Exception2 ---> System.Exception: Exception1
   at finallyTest.Program.testFinally() in \Projects\finallyTest\finallyTest\Program.cs:line 17
   --- End of inner exception stack trace ---
   at finallyTest.Program.testFinally() in \Projects\finallyTest\finallyTest\Program.cs:line 24
   at finallyTest.Program.Main(String[] args) in \Projects\finallyTest\finallyTest\Program.cs:line 38
>>>>>1

Monday, February 4, 2013

Creating and using own jsp Tag Library

Creating and Using Your Own JSP Tag Library

Java Server Pages (JSP) is a well-established technology for implementing the View layer in web applications using the MVC (Model-View-Controller) pattern. JSP makes it easy to embed HTML and Java logic together, offering a standardized and streamlined approach to building dynamic web interfaces.

JSP also supports custom tag libraries, allowing developers to create reusable components that encapsulate presentation logic. This leads to cleaner, more maintainable code. In this article, we'll explore how to create and use a custom JSP tag library, as well as review the JSP life cycle.

Why Use Custom JSP Tags?

JSP provides standard tags such as <jsp:include> and <jsp:useBean>, but sometimes, application-specific logic needs to be reused across multiple pages. Custom tags help you:

  • Encapsulate and reuse complex logic
  • Write cleaner JSP pages with less embedded Java code
  • Separate business logic from view code more effectively

JSP Life Cycle

Before creating tags, it's important to understand how JSPs work behind the scenes:

  1. Translation: The JSP file is converted into a servlet source file by the container.
  2. Compilation: The servlet source is compiled into a class file.
  3. Initialization: The jspInit() method is called once for setup.
  4. Request Processing: For each request, _jspService() is invoked.
  5. Destruction: The jspDestroy() method is called before the servlet is unloaded.

Creating a Custom Tag Library

1. Create a Tag Handler Class

Start by creating a Java class that extends SimpleTagSupport:

package com.example.tags;

import java.io.IOException;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import javax.servlet.jsp.JspWriter;

public class HelloTag extends SimpleTagSupport {
    private String name;

    public void setName(String name) {
        this.name = name;
    }

    public void doTag() throws IOException {
        JspWriter out = getJspContext().getOut();
        out.println("Hello, " + name + "!");
    }
}

2. Create the TLD File

Create a file called hello.tld in the WEB-INF directory:

<?xml version="1.0" encoding="UTF-8"?>
<taglib xmlns="http://java.sun.com/xml/ns/javaee"
        version="2.1">

    <tlib-version>1.0</tlib-version>
    <short-name>helloTag</short-name>
    <uri>http://example.com/hello</uri>

    <tag>
        <name>greet</name>
        <tag-class>com.example.tags.HelloTag</tag-class>
        <body-content>empty</body-content>
        <attribute>
            <name>name</name>
            <required>true</required>
            <rtexprvalue>true</rtexprvalue>
        </attribute>
    </tag>
</taglib>

3. Use the Tag in a JSP File

<%@ taglib prefix="h" uri="http://example.com/hello" %>

<html>
<body>
    <h:greet name="Alice" />
</body>
</html>

Output:

Hello, Alice!

Packaging the Tag Library

To distribute your tag library:

  • Compile your Java classes and place them in the correct package structure
  • Put the TLD file inside the META-INF directory of a JAR file
  • Place the JAR inside your application's WEB-INF/lib folder

Benefits of Custom Tags

  • Reduce duplication by reusing presentation logic
  • Keep JSPs clean and easy to read
  • Improve separation between logic and markup

Conclusion

Custom JSP tags allow you to extend the capabilities of JSP pages by hiding complex Java logic behind simple tag interfaces. They're a great way to promote reusability and maintain clean, modular web pages.

Start by creating simple tags, then expand into more advanced tag features as your application grows.