Friday, 24 January 2014

Understanding Port Numbers

This article will teach you about port numbers which will help you understand why you need a  port number for Tomcat or for any application that should be accessed by others.

To work with any program, the user must load it in the RAM. This program can be loaded at any address in RAM. So, to work with the program, the user must know that address which is highly impossible. Because, every time it is loaded in a different address, randomly. For instance, today it might be loaded in 1000, tomorrow it will be 500 and so on.
       So there must be a way to ensure access to that program, no matter where it is loaded. So, is the concept of port numbers. For every program (or an application) that should be accessed by other programs, we give a port number. Whenever we want to access that program, we tell to the OS that I want to access the program that is at this port number, so connect that program to me.
         The OS maintains a map of port number and the address in RAM of the corresponding program. So, no matter where the program is loaded in RAM, that address is mapped to the port number.
         Just like, no matter where you are, anyone can interact with you by your mobile number.

Port numbers range from 1 to 65,535, where 1 to 1024 are registered for OS services. Now, for your applications you can choose from 1024 to 65535.

Photo credit: yu.edu

Thursday, 23 January 2014

Desktop vs Web applications

This article teaches you the basics of desktop and web applications which is the first concept you need to learn before entering web development.
Before, we learn about the types of applications, let me clarify you about web development and web designing which are mostly confused.
        Web development deals with developing of web applications, that takes the user data and gives output based on it. This involves interaction with the server.
Ex: Java applications come under web development. These applications are executed in the server.
         Web design deals with the design, a.k.a. the look of a web page. It is coded in CSS, and the web page is written using HTML which also comes under web design. Javascript, a client-side scripting language that deals with doing some tasks in the client browser, comes under web-design again.

Types of applications

There are two types of applications, which I'll divide on the basis of interaction with internet.
  • Desktop applications
  • Web based applications
Desktop applications run on the local system which doesn't need internet to work. Also called as standalone applications.
Ex: CCleaner

Web based applications run on the server side and requires internet. These applications can run via the browser (typically) or through a program.
Ex: Google, Facebook etc.

The web based applications store their data in the servers and gives us results based on that data.
         Take Google, for example, the user types in a search query then the browser transfers our query to the Google server and the google server searches its database for the query and gives us results.
         So to develop such kind of applications which takes data from the user via a web browser and give the result, Java servlets can be used.

Wednesday, 22 January 2014

Brief view of HTTP Protocol

This article will teach you the basics of Http protocol that will be helpful for learning servlets and other web development frameworks like Spring, Struts etc.

What is hyper text?

Hyper-text is the text that contains links (called as hyperlinks) which can navigate us from one web page to another web page. And you know, why do we need to navigate from one page to the other.
    HTML (Hyper-text markup language) is a language that is used to develop pages with hyper text. And HTTP is the protocol that is responsible for the transfer of these pages from server to the client.
    Both HTTP protocol and HTML, World-Wide-Web are invented by Tim-Berners Lee with his team.

What is a protocol and HTTP protocol?

A protocol is a set of rules or simply a program. A HTTP protocol defines how data should be transferred from client to the server. It contains commands for establishing the connection to the server, sending the user data to the server, downloading the web page.

HTTPS is another protocol similar to HTTP but, the data sent/received to/from the server is encrypted before transferred. This is slower, because there is an intermediate process called encryption. This is used while transferring sensitive information like usernames and passwords. That is why most login pages have https connection.

Statelessness of HTTP protocol

     The HTTP protocol is responsible for the sending of request and receiving of response, once this process is complete (i.e. one-request-and-the-response-for-it), the http protocol forgets about the data transferred with the request and the data received in the response. This is why http is a stateless protocol.
      One-request-and-the-response-for-it is called as a transaction. So don't get stumped, when you are hit with the word transaction.

Static vs dynamic pages

A web page contains information that is stored in a server. There are two types of web pages static and dynamic.

Static web pages: These pages contains just the information and probably some links to navigate to other pages. The information in these pages is written by someone and stored in the server as a file. The only use of these pages is to just read the information present in them. Best example, is this page, where you just read information which doesn't change by your action.

Dynamic web pages: These pages also contains information, but the information in these pages will change according to the user input. Best example, is Google search, where based upon your search query, you get the results page.
Photo Credit: Mario Romero de Chile via Compfight cc

Basics of Java Servlets

Basics of servlets
This article contains the basics of Java servlets which will kickstart your journey into web development using Java.

What is servlet and web server?

A servlet is a Java program that runs on the server. To run servlet programs, we need a web server. In this tutorial, we will use Tomcat.
       The servlets were introduced by Sun Microsystems as an alternative to CGI which was then most popular for developing web applications. Sun Microsystems did not provide code for working with servlets, they have only specified some set of rules according to which the servlet related classes must be written.
According to those guidelines specified by the Sun, several companies which produce server software like Tomcat have written their own classes that enable programmer to work with servlets.

Two important keywords you need to know:

request: Request made to the server by the browser for data.
response: Output (data) given by the server to the browser after request.
The main aim of the web applications is to take input from the user and give the output. This output which is based on the input given is called as dynamic content.

Servlet container

catalina.jar is called as servlet container. The birth, life and death of a servlet is under the control of this container i.e. this container is responsible for the creation, execution and death of a servlet.
Servlets do not contain a main() method. The corresponding methods are called upon each request by the container itself. The programmer doesn't need to worry about it.
 

Advantages of Servlets over CGI

Servlets are better than CGI under a lot of circumstances. Sure, the disadvantages of CGI in the growing world wide web had been devastating, so are servlets introduced. In CGI:
       Every user request is processed by a program, i.e. for every request a new program is loaded into the RAM by the web server and that program, processes the request and gives the response.
       Because of this, servers required large memory RAMs and high working processors to serve a large number of users at a time. Also, when the program has to interact with the database, for every request, a database connection is created, which is both late and a security loop hole.
       Combined with the statelessness of HTTP protocol (as discussed in the previous chapter), CGI has got another disadvantage. For every request, a program is loaded and then after the response is given, the program is killed. So, there is no way to keep track of the previous requests. This has been of greater disadvantage in all spheres of web applications.

The concept of servlets changed the entire thing.
  • Instead of using, a new program for serving each user request, a thread is used to serve a request. Thereby, making the process more efficient and less costly.
  • Only one database connection serves several user requests, hence more secure.
  • Also, the concepts of cookies and session tracking made it possible to keep track of user's previous requests.
Photo credit: copyblogger.com

Sunday, 19 January 2014

Servlets Tutorial for Beginners

This tutorial will teach you servlets in Java.
In this tutorial you'll learn:
  • Desktop and web applications
  • Installing and configuring Tomcat
  • Http protocol and port numbers
  • Servlet basics
  • Generic and Http Servlets, form submissions
  • Annotations in servlets
  • Servlet communication
  • Cookies
  • Session Tracking

1. Desktop and web applications

You'll need to learn what are web apps before you start developing them.

2. Installing and configuring Tomcat

To work with servlets, you need a web server. We will use Tomcat here. Download Tomcat 7 
For every web application, we create a directory in Tomcat installation directory. So you need to know the typical folder structure for a tomcat web application.

3. HTTP Protocol and port numbers

You need to learn what is HTTP protocol, static and dynamic pages before you develop any web application.

4.  Servlet basics

You'll need to learn the basics of Java servlets that help you ace the web development with Java.

5. Generic and Http Servlets

Generic servlets are protocol-independent, it isn't just for http protocol.
Http servlets are strictly for http protocol.
There are two ways of sending data (aka making request or user input) from client to server. They are GET and POST.

GET transfers data via the address bar as query string. For example,
http://google.com/search?q=amazon

POST transfers data in background and hence not visible in the address bar. This is used for sending usernames and passwords as they must not be visible in the address bar.

6. Annotations in servlets

We can use annotations in servlets. Annotation is data about a class or a member variable or a method that will be useful at run time.

    7. Servlet communication

    Servlets need to communicate with each other to transfer data from one servlet to another.

    8. Cookies

    Cookies are key-value pairs that are stored in the web browser. As HTTP is a stateless protocol, there must be some way for the web application to keep track of the previous requests by the user. For example, in amazon.com while shopping, our items are stored in the cart though we move to other pages, we will be displayed the previous items that we have added. This is because, our previous data is stored. Where? In our browser only!

      9. Session Tracking

      Session tracking is an alternative to cookies. Cookies are stored in client browser, sessions are stored in server. What if cookies are disabled in browser? What if they are manually deleted? For all this, session tracking is the ultimate solution.

      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.*"%>

        Saturday, 4 January 2014

        Servlet Web Application without web.xml

        Here is how we can simply write a tomcat servlet web application without web.xml. Yes, you heard it right and I am going to show you for what you are here. I have just learned it today with the help of my professor. (Thanks to him).
        We can achieve this by using annotations which you might have heard in core Java. It is data about data.
        In a single line, we will be doing the servlet mapping to url pattern. Here is how:
        This doesn't work in versions of tomcat that are < 7. So make sure that you have at least Tomcat 7.

        Project structure



        anser


              |__ index.html


              |__ WEB-INF


                                 |__ classes


                                                |__ MySer.java


                                                |__ MySer.class

        Simple HTML Form - index.html


        <html>
            <body>
                <form action="./hello">
                    <input type="text" name="username"></input>
                    <input type="submit"/>
                </form>
            </body>
        </html>

        Servlet Class with annotation



        import javax.servlet.*;
        import javax.servlet.http.*;
        import javax.servlet.annotation.*;
        import java.io.*;
        @WebServlet(urlPatterns={"/hello"})
        public class MySer extends HttpServlet
        {
            public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
            {
                PrintWriter pw=res.getWriter();
               
                pw.println("<h1>Welcome "+req.getParameter("username")+"</h1>");
               
                pw.close();
            }
        }

        Here, at run time, the above servlet class is the one that will be executed for the url pattern /hello. So, whenever there is a request to the /hello then this class doGet() is activated. Isn't this great and simple? Here you can also include multiple url-patterns for the same class as urlPatterns takes a String[]. For example,
        @WebServlet(urlPatterns={"/hello","/welcome"})
        Here either /hello or /welcome, this MySer will be executed.