Showing posts with label Java Server Pages. Show all posts
Showing posts with label Java Server Pages. Show all posts

Sunday, 19 January 2014

Creating custom tags in JSP - Example

The following example illustrates creating your own tags in JSP. The tags you create here will have a prefix and a tag name.

Why should I write tags?

Tags are used to reduce the size of a JSP page by trimming lines of lengthy, redundant code in JSP pages and put them in a class and execute it every time you declare the tag. For example, you want to insert a student record in JSP. For this, you need to load the driver class, create connection object, execute the query.  But for all this, you can simply write a tag, say <student:insert> which will have attributes sno,sname and age.

<student:insert sno="101" sname="smith" age="20"/>

Now each time this tag is executed, a student record is inserted. This is not a pre-defined tag but the tag that you should write, meaning, you should implement the code in a class and link it up with this tag.

Here are some key points about the tags:
  • Every tag will have a name and a corresponding class.
  • The class name need not be same as the tag name.
  • The attributes of a tag are the parameters to that particular method. The attribute names must be same as the member variables.
  • There can be required (mandatory) attributes for a tag.
  • You can also write a tag with no attributes.
Let us now start by writing a simple tag with no attributes. The aim of this tag is to print a message.

Folder structure
webapps
           |_ jsp8
                   |_ WEB-INF
                                    |_ mytags.tld
                                    |_ classes
                                                |_ tags
                                                        |_ MyTag.java
                   |_ index.jsp

index.jsp



<%@taglib prefix="t" uri="WEB-INF/mytags.tld"%>
<html>
<body>
<t:footag/>
</body>
</html>

Here the tag prefix is mandatory and the uri is where the custom tags are defined. You can have any prefix.

mytags.tld

A tld file must be written that maps tags to their corresponding classes.


<taglib>
    <tlib-version>1.0</tlib-version>
    <jsp-version>2.0</jsp-version>



    <tag>
    <name>footag</name>
    <tag-class>tags.MyTag</tag-class>
    <body-content>empty</body-content>
     </tag>



</taglib>

<name> is the name of the tag that comes after the prefix (after the :)
<tag-class> is the class in which the tags functionality is provided.
<body-content> defines if the tag must be empty or contain other tags along with text or tag dependent text etc. There are three possible options:

empty: Meaning that the tag should not be given a body. For example,
<t:footag>text</t:footag> is false, whereas <t:footag></t:footag> or <t:footag/> are true.

scriptless: Meaning that the tag can contain body including but not limited to text and other html tags. This is the default.

tagdependent: Meaning that the body can contain tag-dependent content, for example you might create a tag that takes an SQL query and executes it, so you'll write the corresponding SQL query there.

MyTag.java

This class contains the functionality of the tag, here written in the doTag() method.


package tags;
import javax.servlet.jsp.tagext.*;
import javax.servlet.jsp.*;
import java.io.*;
public class MyTag extends SimpleTagSupport
{
     public void doTag() throws JspException, IOException
    {
    JspWriter pw=getJspContext().getOut();
    pw.println("This is in the tag");
    }
}

Here we got the implicit object out so that we can write on the JSP page declaring this tag.

References

  1. http://docs.oracle.com/javaee/5/tutorial/doc/bnama.html#bnamg
  2. http://www.tutorialspoint.com/jsp/jsp_custom_tags.htm

Mixing HTML with JSP Code

The following example illustrates mixing HTML with JSP code. For starters, typically some of the JSP programs look weird and confusing because both the HTML and JSP code is mixed. But if you can carefully understand what tag is what, you can write even more complex JSP programs than you see.
       One key point you need to know that, you can end a scriptlet tag anywhere you want. For example,


<%

if(true){

%>

<p>This is in the if-block. </p>

<%

out.println("This is that's it.");

}

%>

As you can see the first tag <% %> was ended unexpectedly to  write the message This is in the if-block. This is a html line executed only if the if-condition is met. Isn't this simple?
Now let us write a program.

index.jsp


<%!
int a=10;
%>
<%
    if(a==10)
    {
%>
<b>This is bold text, I'm seen only when a==10</b>
<%
    }
    else
    {
%>
<b>I am not seen, because a is not 10!</b>
<%
    }
%>

<br/>I am after if-else.
Previous: Using scriptlets in JSP
Next: Using declarations with example

Saturday, 18 January 2014

JSP Tutorial for Beginners

Here is a quick-start JSP tutorial for beginners. Before you read this tutorial, I suggest you to have a per-requisite knowledge of servlets in Java.
In this tutorial you are going to learn:
  • Scriptlets, Declarations and Expressions
  • JSP Directives
  • XML Tags
  • Working with JSP beans
  • Custom tags

Introduction to JSP 

JSP stands for Java Server Pages. It is a tag based approach that mixes both the HTML and the java servlet code. The reasons why we should use JSP will be the strongest foundation for you.
  • You do not need to write servlet classes anymore. They are replaced by JSP.
  • Tag based approach is more cleaner and programmer friendly.
  • HTML mixed with servlet code will provide all logic at one place.
  • You NEED NOT COMPILE servlets, RESTART server. Because the server automatically checks if a JSP page is modified upon each request. If modified, jasper container translates JSP to servlet (.java) file, compiles it and then loads it automatically.
  • Simplified data processing with beans approach.

1. Scriptlets, Declarations and Expressions

The very basics of JSP you need to start coding with.

2. JSP Directives

3. XML Tags

A clean, tag based approach for JSP.

4. JSP Beans

How JSP simplifies data processing with MVC using beans?

5. Custom tags 

Create custom tags to improve re-usability.

    Using JSP Declaration XML Tag

    The following example illustrates using <jsp:declaration> tag. This is an alternative to the <%! %> (declaration).
         This tag is used to declare global variables or write member methods of the jasper-generated servlet class.

    index.jsp


    <jsp:declaration>
        int x=10;
        String st;
        public void print()
        {
        st="hello";
        }
    </jsp:declaration>
    <jsp:scriptlet>
        out.println(x);
        // initialize st
        print();
        out.println(st);
    </jsp:scriptlet>

    Note: You can write multiple <jsp:declaration>, <jsp:scriptlet> tags.

    Previous: <jsp:scriptlet> tag
    Next: <jsp:include> tag

    How to create JSP Error pages

    The following example illustrates creating error pages in JSP. As the name suggests, error pages are those pages that will be viewed to the user when an error occurs in a jsp page.
          For example, when an exception occurs in a JSP page, you'll get the default tomcat (or any server) generated error page which contains the entire details of where the error occurred etc. In case if you don't want that to be shown to the user, you can use the error pages.
         There is one tag that you'll be using with two different attributes in two different contexts. We will be using the @page directive. The syntax will for this directive is as follows

    <%@page attr="value"%>

    Now, the first context is using the attribute errorPage whose value must be the jsp page that displays the error.

    <%@page errorPage="myerr.jsp"%>

    This tag should be written in the JSP page where the exception will occur.

    The next context is using the attribute isErrorPage whose value must be true for error pages.

    <%@page isErrorPage="true"%>

    This tag must be placed in the error page.

    The following example will add two numbers. A NumberFormatException is raised if the user enters non integer values in the textfields. When such an exception occurs, an error page is shown.

    index.jsp - Takes input of 2 numbers



    <html>
        <body>
        <form action="add.jsp">
    Enter first number: <input type="text" name="t1"/>
    Enter second number: <input type="text" name="t2"/>
        <input type="submit" value="Add"/>
        </form>
        </body>
    </html>

    add.jsp - prints the sum



    <%@page errorPage="myerror.jsp"%>
    <%
        int x=Integer.parseInt(request.getParameter("t1"));
        int y=Integer.parseInt(request.getParameter("t2"));
    out.println("The sum is "+(x+y));
    %>

    myerror.jsp - displays the error message



    <%@page isErrorPage="true"%>
    <h1>Please type your input properly</h1>
    <b>
    <%=exception%>
    </b>

    Here, if the isErrorPage is not true or if the tag is omitted, then you'll not get the exception object used here. However, if you do not use the exception object you need not write the tag.

    Note: You cannot declare multiple error pages for single JSP page. All of the exceptions (aka errors in this context) must be directed to an error page which gets the exception object. Depending upon the exception you get, the jsp page will display a corresponding message or do a corresponding action.

    Thursday, 16 January 2014

    Using JSP Beans with example

    The following example illustrates using JSP beans. This will introduce you to three tags

    <jsp:useBean>
    <jsp:setProperty>
    <jsp:getProperty>

    Before we start, let us talk about why use these beans.

    Introduction to beans

    A bean is a class containing some member variables and methods. This class represents a particular entity. For example, take Student class. A student typically contains a number, name and age. So, i will create a class called Student which contains the member variables sno, sname, age.

    Now I want to store those student details into the database one by one. So every time a student record is entered, i assign those values into sno, sname, age correspondingly. And then i'll store them in the database.
    So, every time data is entered, I'll store the details in the class member variables and then get them and store in the database.

    This is a clean approach. This is what is called as re-usability which means that for every student record we are using the same class.

    A bean class contains typically of two types of methods called setter and getter methods.
    A setter method is used to put the value into a member variable.
    A getter method is used to get the value of a member variable.

    There are some rules for giving names to these setter and getter methods. These rules are kept because the JVM has to understand what is what.

    For example, if a member variable is named sno then, the corresponding methods will be:

    public void setSno(int sno)
    {
    this.sno=sno;
    } 
    public int getSno()
    {
    return sno;
    } 

    Note that the names of those methods must be the same i.e. they should start with set or get and then followed by the member variable name with first letter capital. The parameter name, can however be different.

    <jsp:useBean>

    This tag typically takes two attributes namely, id and class.
    class: This is the bean class. Here Student
    id: This is the name of the object for the student class.
    scope: This tag takes the scope of the object session, request, page etc.

    Syntax: <jsp:useBean id="st" class="beans.student" />

    When this tag is simply closed as above, the default constructor of the Student class is activated.

    <jsp:setProperty>

    This tag is used to inject the values into the object. It takes two to three parameters.

    name: The name of the object to which the values must be injected.
    property: The member variable to which the value must be injected
    value:  This is the value to be injected (set) into the member variable. Usually, we don't do this, the value is taken from the form.
    param: This is the name of the input field from which the value is to be taken. When the input field names and  the property names in the bean class are different we use this. Otherwise, we specify * in the property field when all the property names and the input field names are same.

    <jsp:getProperty>

    This tag is used to get the injected value from the object.

    name: The name of the object.
    property: The member variable.

    Folder structure

    webapps
              |_ jsp6
                     |_ WEB-INF
                                      |_ classes
                                                  |_ beans
                                                            |_ Student.java
                                                            |_ Student.class
                     |_ index.jsp
                     |_ print.jsp

    Student.java - Bean class



    package beans;
    public class Student
    {
    private int sno;
    private String sname;
    private int age;

        public void setSno(int sno)
        {
        this.sno=sno;
        }
       
        public int getSno()
        {
        return sno;
        }

        public void setSname(String sname)
        {
        this.sname=sname;
        }

        public String getSname()
        {
        return sname;
        }

        public void setAge(int age)
        {
        this.age=age;
        }

        public int getAge()
        {
        return age;
        }
    }

    index.jsp



    <html>
        <body>
        <form action="print.jsp">
    Student number: <input type="text" name="sno"/>
    Student name: <input type="text" name="sname"/>
    Student age: <input type="text" name="age"/>
        <input type="submit" value="Submit"/>
        </form>
        </body>
    </html>

    Here the data is sent to print.jsp using GET (default).

    print.jsp



    <%--
    Create an object 'st' for the class beans.Student using
    default constructor
    --%>

    <jsp:useBean id="st" class="beans.Student">


    <%--
    Put the values entered into the form into the bean class
    --%>

    <jsp:setProperty name="st" property="*"/>


    <%--
    Get all the values that are put in the object 'st' with the
    given property names
    --%>

    <jsp:getProperty property="sno" name="st"/>
    <jsp:getProperty property="sname" name="st"/>
    <jsp:getProperty property="age" name="st"/>

    </jsp:useBean>

    Using JSP Expressions with Example

    The following example illustrates using JSP expressions.
    An expression is a combination of symbols that represents a value. Examples of expression include a+b, a*b, new Date() etc.
    In JSP you can get an expression value and print it without the need of writing in scriptlets. The syntax is as follows

    <%=some-expression%>

    Here the result of this expression is returned as String object. If the tag alone is written in a JSP page, then the expression value is printed. In simple words, you can get the result of a function call, an arithmetic operation or an object creation using the expression.

    The expression shouldn't return a void value.

    index.jsp



    <html>
        <body>
        <%="This is sample text"%><br/>
        <%=10+20%><br/>
        <%=new Integer(20)%><br/>
        <%="The difference is"+(20-10)%>
       
        <%--
        This is an error, void type not allowed
        <%=out.println("hai")%>
        --%>
        </body>
    </html>

    Output of the program



    This is sample text

    30

    20

    The difference is10

    Previous: <jsp:forward>

    References

    http://docs.oracle.com/javaee/5/tutorial/doc/bnaov.html

    Using JSP forward XML Tag

    The following example illustrates using <jsp:forward> tag. This tag is used to forward the current jsp page to another page (any page jsp or html). Just like redirect. But here, you can transfer the data from one jsp page to another jsp or servlet page by setting the request attributes. Here is the syntax
    <jsp:forward page="sample.jsp"/>

    Here page is a mandatory attribute.

    Folder structure
    webapps
               |_ jsp5
                     |_ index.jsp
                     |_ sample.jsp

    index.jsp



    <html>
        <body>
        This is in the html body<br/>
        <jsp:scriptlet>
        request.setAttribute("sample","this is sample text......");
        </jsp:scriptlet>
        <jsp:forward page="sample.jsp"/>
        </body>
    </html>

    Here, using the setAttribute() we have set an attribute to the corresponding request. The request object here is carried to the sample.jsp file because of the <jsp:forward> tag. The request here is forwarded.

    sample.jsp


    <%
        out.println(request.getAttribute("sample"));
    %>

    Using JSP include XML Tag

    The following example illustrates <jsp:include> tag which is used to transfer the current request and response objects to a new jsp page and include that result in this page. It is not an alternative to @include directive
        This is a pre-defined tag, hence the prefix jsp and doesn't need to load external tag libraries. Those who are familiar with tags will find this comfortable. This contains mandatory page attribute. Let us look at its syntax. This tag is used to embed other pages into a JSP page and you can write as many tags you want.
    <jsp:include page="sample.html"/>

    Folder structure
    webapps
               |_ jsp4
                       |_ index.jsp
                       |_ sample.html

    index.jsp



    <html>
        <body>
        This is in the html body<br/>
        <jsp:include page="sample.html"/>
        </body>
    </html>

    sample.html



    <html>
        <body>
        <h2>This is a h2 heading</h2>
        <p>This is a paragraph in sample.html</p>
        </body>
    </html>

    Previous: Using JSP Scriptlet XML Tag and Next: Using JSP forward tag

    Using JSP Scriptlet XML Tag

    jsp tutorial
    The following example illustrates using <jsp:scriptlet> tag as an alternative for <% %> tag.
    Both are one and the same while this tag is a much cleaner approach. It is like a html tag and ends as a normal HTML tag would.

    The tag contains a prefix jsp which occurs before the : and the tag name is scriptlet. This is a pre-defined tag meaning, we need not load external tag libraries (aka taglibs) and these tags start with the prefix jsp. The syntax will be as follows


    <jsp:scriptlet>

    // code to be written in the scriptlet

    </jsp:scriptlet>

    Just as you would use the normal scriptlet tags, these tags can be inserted anywhere in the HTML file.

    index.jsp



    <html>
        <body>
        This is in the html body
        <jsp:scriptlet>
        out.println("This is in the scriptlet");
        </jsp:scriptlet>
        </body>
    </html>

    Wednesday, 15 January 2014

    Using @include directive in JSP

    The following example illustrates using @include directive in JSP.
           This directive is used to include a file (typically jsp or html) into a JSP page. Let us now see a simple example of how this works.


    Syntax

    <%@include file="myfile.jsp"%>

    As you can see, you are passing an attribute called file with takes the file to be embedded.

    JSP file - index.jsp



    <html>
        <body>
        This is in the html body

        <%
        out.println("This is in scriptlet");
        %>
       
        <%@include file="sample.html"%>
        </body>
    </html>

    sample.html



    <html>
        <body>
        <h2>This is a h2 heading</h2>
        <p>This is a paragraph in sample.html</p>
        </body>
    </html>

    In this way you can also include as many files you want regardless of their file type as far as the web browser can show it to the user.

    JSP Declaration Tag Example

    In this example you are going to learn about the JSP declaration tag. This tag is used to declare member variables and methods of the servlet class corresponding to our JSP file.

    Let me explain this more clearly. When we write a JSP file, the JSP container (jasper.jar) automatically writes a corresponding servlet (.java) file, compiles it and deploys it.

    Now with the help of the JSP declaration tag we can declare variables and methods that were members of that servlet class. Don't believe me? Well, I'll show you the proof below. Let us move to the example first.

    Folder structure:
    webapps
                |_ jsp2
                        |_ index.jsp

    Syntax



    <%!


    // declaration of variables and methods of the servlet class


    %>

    Note the exclamatory mark (!). If you forget it, it will be a scriptlet tag.

    Example - index.jsp


    <%!
    int a=10;
        public int getA()
        {
        return a;
        }
    %>
    <%
        out.println("The value of a is "+getA());
    %>

    Here a is a member variable of the servlet class corresponding to the JSP file and getA() is the member method that returns the value of a. Now, in the scriptlet (i.e.) in the _jspService() method we are calling the getA() and we are printing it. So the output will be:



    The value of a is 10

    index_jsp.java - Corresponding servlet

    You can find this file in 

    C:\Program Files\Apache Software Foundation\Tomcat 7.0\work\Catalina\localhost\jsp1\org\apache\jsp

    Here is a sample structure of the file (need not be exactly the same, i'm telling the outline):



    public final class index_jsp


    {


    int a=10;


             public int getA()


             {


             return a;


             }





             public void _jspService(HttpServletRequest req,HttpServletResponse res)


             {


             out.println("The value of a is "+getA());


             }


    }

    Using @page import in JSP

    jsp import example
    Here is a simple example that illustrates using @page import in JSP.

    In this example, you'll learn how to import java packages in JSP using the @page directive so that we can use classes directly in JSP program without the need of mentioning the full classpath while using other classes.
    Folder structure:
    webapps
                |_ jsp1
                         |_ index.jsp

    index.jsp


    <%@page import="java.util.*"%>
    <%
        ArrayList<String> as=new ArrayList<String>();
        as.add("One");
        as.add("Two");
        as.add("Three");
        as.add("Four");

            for(String k:as)
            out.print(k+"  ");
    %>

    The first tag imports the java.util package so are we able to use the ArrayList without the need of writing java.util.ArrayList.
    You can also add as many number of page imports as you want either in single tag or multiple tags. For example,

    <%@page import="java.util.*,java.io.*"%>
    (OR)
     <%@page import="java.util.*"%>
     <%@page import="java.io.*"%>

    Wednesday, 27 November 2013

    Autocomplete HTML Input Field using JSP and JQuery in Five Lines!


    Everyone is fascinated about auto-complete. Right? I think, Are you? Drop in the comment below. Long time I've been connecting JQuery and Java and have some of the posts like loading JSP file in JQuery in one line Now, it is time to go further.

    I would be blogging now a simple example on how to connect auto-complete for a HTML text field to a JSP file with JQuery in one line! Yes, in five lines!, YOU heard it RIGHT!

    Project structure

    Folder path: C:\Program Files\Apache Software Foundation\Tomcat 8.0\webapps\jq_autocomplete



    jq_autocomplete

                    |

                    +-- index.html

                    +-- auto.jsp

    index.html - HTML file



    <html>
        <head>
            <title>Send POST Request to Servlet with JQuery</title>
            <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
            <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
            <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
            <script>
                    // When any key is down
                    $(document).keydown(function(){

                        // Get the input element and its value
                        var i=$("#com");
                        var val=i.val();

                        // Send request only if user types alphabet
                        // because auto.jsp returns names of companies
                        // which contains only alphabets
                        if(val.match(/^[A-z]+$/))
                        {
                            // Send request and get the data
                            $.get("auto.jsp?com="+val,function(data){

                                // Get each item separated by new line
                                var items=data.split("\n");

                                // put those items in autocomplete! That's it!
                                i.autocomplete({source:items});
                            });
                        }
                       
                    });
            </script>
        </head>
       
        <body>
            <input type="text" id="com" name="com"/>
        </body>
    </html>

    The point here is that the function keydown is executed every time when a key is down in the document and so the request will be sent each time when the key is down degrading performance of the application. To avoid this, the if-condition is useful which checks if the value matches the regex which corresponds to any alphabet.

    auto.jsp - Returns auto complete data



    <%@page import="java.util.*"%>
    <%
        // Create ArrayList and add some items
        ArrayList<String> as=new ArrayList<String>();
        as.add("Google");
        as.add("Yahoo");
        as.add("Apple");
        as.add("Microsoft");
        as.add("Linkedin");
        as.add("Facebook");
        as.add("IBM");
        as.add("Oracle");
        as.add("Salesforce");
        as.add("Amazon");
       
            String s=request.getParameter("com");
           
                for(String st:as)
                {
                    if(st.toLowerCase().startsWith(s.toLowerCase()))
                    {
                        out.println(st);
                    }
                }
    %>

    The best price you could pay for this post is sharing it. I thank you in advance :)
    Photo Credit: Angelina :) via Compfight cc

    Saturday, 23 November 2013

    Load a JSP File using JQuery in One Line


    Here is how to load a JSP file using JQuery in a single line!. The following is a hello world JSP example which will be loaded on a button click using the JQuery. As you can see from the image, the paradigm, write less, do more. is exactly exemplified here.

    Project structure

    Folder: C:\Program Files\Apache Software Foundation\Tomcat 8.0\webapps\jq_jsp

    jq_jsp

        |

        +-- index.html

        +-- hello.jsp


    index.html




    <html>


    <head>


    <script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>


    <script>


    // When the document is ready..


    $(document).ready(function(){


    // When any element with input tag is clicked


    // execute the following function


    $("input").click(function(){


    // Get object of element with loadHere id


    // And in it load the hello.jsp file!


    $("#loadHere").load("hello.jsp");


    });


    });


    </script>


    <title>Load a JSP File in JQuery</title>


    </head>




    <body>


    <input type="button" value="Get hello"/>


    <div id="loadHere"/>


    </body>


    </html>


    hello.jsp




    <%


    response.getWriter().println("Hello world!");


    %>


    The greatest appreciation you could give me is sharing this article. I would sincerely appreciate it :)