Thursday, 16 January 2014

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.