Tuesday, 29 September 2015

Implicit Objects

Implicit Objects


The objects are created by the web container which are available to all the jsp pages are known as Implicit Objects.
The available implicit objects are out, request, config, session, application etc. 

JSP supports nine implicit objects given below:

• out :
The out implicit object is an instance of a javax.servlet.jsp.JspWriter object and is used to send content in a response. 

• request :
The request object is an instance of a javax.servlet.http.HttpServletRequest object. Each time a client requests a page the JSP engine creates a new object to represent that request. 

• application :
The application object is direct wrapper around the ServletContext object for the generated Servlet and in reality an instance of a javax.servlet.ServletContext object. 

• page :
This object is an actual reference to the instance of the page. It can be thought of as an object that represents the entire JSP page. 

• exception :
The exception object is a wrapper containing the exception thrown from the previous page. It is typically used to generate an appropriate response to the error condition. 

• response :
The response object is an instance of a javax.servlet.http.HttpServletResponse object. Just as the server creates the request object, it also creates an object to represent the response to the client. 

• config :
The config object is an instantiation of javax.servlet.ServletConfig and is a direct wrapper around the ServletConfig object for the generated servlet. 

• session :
The session object is an instance of javax.servlet.http.HttpSession and behaves exactly the same way that session objects behave under Java Servlets.

• pageContext :
The pageContext object is an instance of a javax.servlet.jsp.PageContext object. The pageContext object is used to represent the entire JSP page.

Basic Flow showing the use implicit objects: 

Thursday, 24 September 2015

Tags Used in JSP

Tags Used in JSP


Various tags are used in JSP which help to use the functionalities if Java and HTML simultaneously. Java code is not required to be complete or self-contained within a single scriptlet block. It can straddle markup content, provided that the page as a whole is syntactically correct.
JSP pages use several delimiters for scripting functions. The most basic is, <% ... %> which encloses a JSP scriptlet. A scriptlet is a fragment of Java code that is run when the user requests the page. Other common delimiters include <%= ... %> for expressions, where the scriptlet and delimiters are replaced with the result of evaluating the expression, and directives, denoted with <%@ ... %>.
So, following are the types of tags commonly used: 

 Directives: In the directives we can import packages, define error handling pages or the session information of the JSP page.

• Declarations: This tag is used for defining the functions and variables to be used in the JSP.

 Scriplets: In this tag we can insert any amount of valid java code and these codes are placed in _jspService method by the JSP engine.

 Expressions: We can use this tag to output any data on the generated page. These data are automatically converted to string and printed on the output stream.

 Custom Tags:
Custom tags are user-defined JSP language elements that encapsulate recurring tasks. Custom tags are distributed in a tag library, which defines a set of related custom tags and contains the objects that implement the tags.
Syntax of custom tag is: <prefix:tag attr1="value" ... attrN="value" />

To use a custom tag in a JSP page, two things are to be kept in mind:
i. Declare the tag library containing the tag
ii. Make the tag library implementation available to the web application

 Expression language:
Simpler form for JSP Expressions came with JSTL 1.0, in the form of Expression Language. EL is used to set action attribute values from different sources at runtime. JSP Expression Language is also used without parameters but as actions directly in a webpage. JSP EL always starts with a "$" followed by a "{" and ends with a "}". The expression is specified inside the brackets. A set of implicit variables provide access to the requested data. 
Example:
${2+3+4}
JSP EL supports literal numbers, the boolean value "true,false", "null", the strings enclosed in single and double quotes. 

 Additional Tags:
The JSP syntax add additional tags, called JSP actions, to invoke built-in functionality. Additionally, the technology allows for the creation of custom JSP tag libraries that act as extensions to the standard JSP syntax. One such library is the JSTL, with support for common tasks such as iteration and conditionals (the equivalent of for and if statements in Java.) 

Wednesday, 23 September 2015

Directory Structure of JSP

Directory Structure of JSP


Whenever a JSP file is created, various files and directories are formed alongside. 
Following diagram gives a glimpse of those files and directories which are present when jsp files are created.


Tuesday, 22 September 2015

Lifecycle of JSP

Lifecycle of JSP


JSP life cycle is also managed by container. Usually every web container that contains servlet container also contains JSP container for managing JSP pages.The key to understanding the low-level functionality of JSP is to understand the simple life cycle they follow.
A JSP life cycle can be defined as the entire process from its creation till the destruction which is similar to a servlet life cycle with an additional step which is required to compile a JSP into servlet. 

JSP pages life cycle phases are:

Translation: JSP pages do not look like normal java classes, actually JSP container parse the JSP pages and translate them to generate corresponding servlet source code. If JSP file name is javat.jsp, usually it is named as javat_jsp.java.
Compilation: If the translation is successful, then container compiles the generated servlet source file to generate class file.
Class Loading: Once JSP is compiled as servlet class, its lifecycle is similar to servlet and it gets loaded into the memory.
Instance Creation/Instantiation - After JSP class is loaded into memory, its object is instantiated by the container.
Initialization: The JSP class is then initialized and it transforms from a normal class to servlet. After initialization, ServletConfig and ServletContext objects become accessible to JSP class.
Request Processing: For every client request, ServletRequest and ServletResponse to process and generate the HTML response, is invoked by the container.
Destroy: Last phase of JSP life cycle where it is unloaded from the memory.



JSP lifecycle methods are:

jspInit() declared in JspPage interface. This method is called only once in JSP lifecycle to initialize config params.
_jspService(HttpServletRequest request, HttpServletResponse response) declared in HttpJspPage interface and response for handling client requests.
jspDestroy() declared in JspPage interface to unload the JSP from memory.



So, JSP page is translated into servlet by the help of JSP translator. The JSP translator is a part of web server which is responsible for this translation into servlet. After that, Servlet page is compiled by the compiler and gets converted into the .class file. Moreover, all the processes that happen in servlet are performed on JSP later like initialization, committing response to the browser and destroy.

JSP Compilation and Translation

When a browser asks for a JSP, the JSP engine first checks to see whether it needs to compile the page. If the page has never been compiled, or if the JSP has been modified since it was last compiled, the JSP engine compiles the page. During the translation phase each type of data in a JSP page is treated differently. Static data is transformed into code that will emit the data into the response stream. 

JSP Initialization

Typically initialization is performed only once and as with the servlet init method, you generally initialize database connections, open files, and create lookup tables in the jspInit method. 

JSP Execution


Whenever a browser requests a JSP and the page has been loaded and initialized, the JSP engine invokes the _jspService() method in the JSP. 

JSP Destroy

The jspDestroy() method is the JSP equivalent of the destroy method for servlets. We can override jspDestroy when space clean up is to be done, such as releasing database connections or closing open files. 

Monday, 21 September 2015

Advantages of JSP over Servlet

Advantages of JSP over Servlet


JSPs offer a wide variety of advantages to the developer. Following points draw attention to the positive points of JSP:

• HTML response can be generated from servlets also but the process is cumbersome and error prone, when it comes to writing a complex HTML response, writing in a servlet turns out to be a very difficult task. JSP helps in this situation and provides us flexibility to write normal HTML page and include our java code only where it's required.

• JSP provides additional features such as tag libraries, expression language, custom tags that helps in faster development.

• JSP pages are easy to deploy, only the modified page in the server is needed to be replaced and container takes care of the deployment. If JSP page is modified, we don't need to recompile and redeploy the project. The servlet code needs to be updated and recompiled if we have to change the look and feel of the application.

• Actually Servlet and JSPs compliment each other. Servlet is used as server side controller and to communicate with model classes whereas JSPs should be used for presentation layer.

• Basically, JSP technology is the extension to servlet technology. All the features of servlet can be used in JSP. In addition to that, implicit objects, predefined tags, expression language and Custom tags can also be used in JSP, that makes JSP development easy.

• JSP can be easily managed/maintained because it is easy to separate the business logic with presentation logic. In servlet technology, business logic is mixed with the presentation logic.

• As compared to Active Server Pages (ASP), the advantages of JSP are twofold. First, the dynamic part is written in Java, not Visual Basic or other MS specific language, so it is more powerful and easier to use. Second, it is portable to other operating systems and non-Microsoft Web servers.

• Compared to pure Servlets, JSP is more convenient to write regular HTML than to have plenty of println statements that generate the HTML.

• In JSP there is less code than Servlet. So, a lot of tags can be used such as action tags, jstl, custom tags etc. that reduces the code. Moreover, we can use EL, implicit objects etc.

• JavaScript can generate HTML dynamically on the client but can hardly interact with the web server to perform complex tasks like database access and image processing etc.Whereas, JSP can do these tasks efficiently.

Friday, 18 September 2015

Why JSP should be used?

Why JSP should be used?


JSP Page consists of HTML code and provides an option to include java code for dynamic content. Since web applications contain a lot of user screens, JSPs are used a lot in web applications. Best part about JSP is, it provides additional features such as JSP Tags, Expression Language, Custom tags. This makes it easy to understand and helps a developer to quickly develop JSPs.

Performance of JSP is significantly better because it allows the embedding of Dynamic Elements in HTML Pages itself instead of having a separate CGI(Common Gateway Interface) files.

JSP is always compiled before it is processed by the server unlike CGI/Perl which requires the server to load an interpreter and the target script each time the page is requested.

JSPs are usually used to deliver HTML and XML documents, but through the use of OutputStream, they can deliver other types of data as well.

Java Server Pages are built on top of the Java Servlets API, so like Servlets, JSP also has access to all the powerful Enterprise Java APIs, including JDBC, JNDI, EJB, JAXP etc.

JSP pages can be used in combination with servlets that handle the business logic, the model supported by Java servlet template engines.

Also, JSP is an integral part of Java EE, a complete platform for enterprise class applications. This means that JSP can play a part in the simplest applications to the most complex.

Finally, Java Server Pages can be used for a variety of purposes, such as retrieving information from a database or registering user preferences, accessing Java Beans components, passing control between the pages and sharing information between requests, pages etc.

Thursday, 17 September 2015

JSP Architecture

JSP Architecture


As far as architecture of JSP is concerned, it may be seen as a high-level abstraction of Java-Servlets. At runtime, JSPs are translated into servlets. Web server needs a container to process JSP pages commonly known as JSP engine. It is responsible for intercepting requests for JSP pages. 

A JSP container works with the Web Server to provide the runtime environment and other services a JSP needs. JSP can be used independently or as the view component of a server-side model-view-controller design, normally with Java Beans as the model and Java Servlets as the controller. JSP allows Java code and certain pre-defined actions to be interleaved with static markup content as HTML, with the resulting page being complied and executed on the server to deliver a document.

The compiled pages, as well as any dependent Java libraries, contain Java byte code. Like any other Java program, they are executed within a JVM that interacts with the server's host OS. The web container creates JSP implicit objects like pageContext, servletContext, session, request and response.



Following steps explain how web pages are created using JSP:
1. Just like a normal page, browser sends HTTP request to the web browser.
2. The web server recognizes that the HTTP request is for a JSP page and forwards it to a JSP engine. This happens with the help of URL or JSP which ends with .jsp.
3. JSP engine loads the JSP page from disk and converts it into a servlet content. 
4. Now the JSP engine complies the servlet into an executable class and forwards the original request to a servlet engine.
5. Servlet engine which is the part of web server loads the servlet class and executes it. During execution, the servlet produces an output in HTML format, which is passed to the web server inside the HTTP response.
6. The web server forwards the HTTP response to the browser in terms of static HTML content.
7. Finally web browser handles the dynamically generated HTML page inside the HTTP response exactly as if it were a static page.


Given diagram explains all of the above steps:

Wednesday, 16 September 2015

Introduction to Spring

Introduction


What is Spring?

Spring framework also known as framework of frameworks, as it provides support to various frameworks such as Struts, Hibernate, EJB, JSF etc.
Spring Framework is a Java platform that provides infrastructure support for developing Java applications.
Spring handles the infrastructure so you can completely focus on your application.
Spring enables you to build applications from "plain old Java objects" (POJOs) and to apply enterprise services non-invasively to POJOs.

Benefits of Spring platform:

1) Makes a Java method executable in database transaction without dealing with transaction APIs.
2) Makes local Java method a remote procedure without dealing with remote APIs.
3) Makes local Java method a management operation without dealing with JMX APIs.
4) Makes local Java method a message handler without dealing with JMS APIs.

Advantages of Spring Framework

1) Loose Coupling
2) Easy to test
3) Lightweight
4) Fast Development
5) Predefined Templates

Main principles on which Spring works:

1. Inversion of control:
It is the mechanism to give control to the container to get instance of object.
It means that instead of creating the object using new keyword, we let the container make object for us. 

2. Dependency Injection:
It is the way of injecting (assigning) properties to an object.

Tuesday, 15 September 2015

Java Server Pages(JSP)









Java Server pages (JSP)


JSP is a simple sort of text document that contins two types of text:
1. static text: that can be expressed in any text-based format such as HTML, XML etc.
2. dynamic text: which contains dynamic data.

So, it is basically a technology that helps to create dynamically generated web pages based on HTML, XML, or other document types. It was released in 1999 by Sun Microsystems, JSP is a bit similar to PHP, but it uses the Java programming language.

To deploy and run JSP, a compatible web server with a servlet container, such as Apache Tomcat or Jetty, is required. The recommended file extension for the source file of a JSP page is .jsp.

JSP allows to mix static HTML with dynamically generated HTML- in the way that the business logic and the presentation are well separated.

 JSP technology creates web application just like Servlet technology. It can be thought of as an extension to servlet because it provides more fuctionality than servlet such as expression language, jstl etc.

 A JSP page consists of HTML tags and JSP tags. The JSP elements in a JSP page can be expressed in two syntaxes, standard and XML, though any given file can use only one syntax. A JSP page in XML syntax is an XML document and can be manipulated by tools and APIs for XML documents. 

 JSP can be used to generate web forms which give outputs based on users input. To bridge the gap between JSP and HTML in JSP, additional features such as JSP Tags, Expression Language, Custom tags etc are used.

It is often quoted that can be done using servlet can accomplished using JSP. But one should note that these two technologies are complementary to each other and NOT replacement of each other.

In a typical Model-View-Cintrol (MVC) application, servlets are often used for the Contoller (C), which involves complex programming logic. JSPs are often used for the View (V), which mainly deals with the presentation. The Model (M) is usually implemented using JavaBean or EJB.

 Thus, Java Server Pages can be used for a variety of purposes, such as retrieving information from a database or registering user preferences, accessing Java Beans components, passing control between the pages and sharing information between requests, pages etc.

Monday, 14 September 2015

Cookies

Cookies


Cookies are small text files that are stored by an application server in the client browser to keep track of all the users.
A cookie has values in the form of name/value pairs.
They are created by the server and are sent to the client with the HTTP response headers.
The client saves the cookies in the local hard disk and sends them along with the HTTP request headers to the server.

A Web browser is expected to support 20 cookies per host and the size of each cookies can be a maximum of 4 bytes each.

Various characteristics of cookies are:
 
1. Cookies can only be read by the application server that had written them in the client browser.
2. Cookies can be used by the server to find out the computer name , IP address or any other details of the client computer by retrieving the remote host address of the client where the cookies are stored.
3. An application server can store cookies in the client machine only when the cookie are enabled in the client browser.

Cookies Description:


The Cookie class of javax.servlet.http package represents a cookie.
The Cookie class provides a constructor that accepts the name and value to create a cookie.
The following code snippet shows the constructor for creating a cookie with name and value.
public Cookie(String cname, String cvalue);
The HttpServletResponse interface provides the addCookie() method to add a cookie to the response object, for sending it to the client.
The following code snippet shows how to add a cookie:
req.addCookie(Cookie cookie);

Retrive the Cookies

The HttpServletRequest provides the getCookies() method that returns an array of cookies that the request object contains.
The following code snippet shows how to retrieve cookies:

Cookie cookie [ ] = req.getCookies();

The Cookie class provides several methods to set and retrieve various properties of a cookie.

The various methods of the Cookie class:1. public String getName()
Returns the name of the cookie.

2. public void setMaxAge(int expiry)
Sets the maximum time for which the client browser retains the cookie value.

3. public int getMaxAge() 
Returns the maximum age of the cookie in seconds.

4. public void setValue(String value)
Sets a new value to the cookie

5. public String getValue()
Returns the value of the cookie

Creating a Simple Program in Servlet using Cookies: In this we receive data from index.jsp and Store it in Cookies after that call it inwelcome.jsp

Steps to create Cookies: 

Step 1 : Create index.jsp with two fields and form action.

1
<%@page contentType="text/html" pageEncoding="UTF-8"%>
2
<!DOCTYPE html>
3
<html>
4
    <head>
5
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
6
        <title>JSP Page</title>
7
    </head>
8
    <body>
9
        
10
        <form action="javat">
11
            <pre>
12
                       <h>LOGIN PAGE</h>
13
            USERNAME : <input type="text" name="name">
14
15
            PASSWORD : <input type="password" name="pass">
16
17
            <input type="submit" value="submit">
18
            </pre>
19
       </form>
20
        
21
   </body>
22
</html>
23
24
25
26
27
    


Step 2 : Create a new file web.xml under WebContent/WEB-INF folder and write the code given below:

1
2
3
<?xml version="1.0" encoding="UTF-8"?>
4
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" 
5
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
6
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
7
    <servlet>
8
        <servlet-name>InterServ</servlet-name>
9
        <servlet-class>com.javat.demo.InterServ</servlet-class>
10
    </servlet>
11
    <servlet>
12
        <servlet-name>Log</servlet-name>
13
        <servlet-class>com.javat.demo.Log</servlet-class>
14
    </servlet>
15
    <servlet-mapping>
16
        <servlet-name>InterServ</servlet-name>
17
        <url-pattern>/javat</url-pattern>
18
    </servlet-mapping>
19
    <servlet-mapping>
20
        <servlet-name>Log</servlet-name>
21
        <url-pattern>/log</url-pattern>
22
    </servlet-mapping>
23
    <session-config>
24
        <session-timeout>
25
            30
26
        </session-timeout>
27
    </session-config>
28
</web-app>
29
30
    


Step 3 : Create a package com.javat.CookiesDemo under Java resources-> src folder and then create the servlet class Login.java. Once you are ready then write the code given below:

1
/*
2
 * To change this template, choose Tools | Templates
3
 * and open the template in the editor.
4
 */
5
package com.javat.demo;
6
7
import java.io.IOException;
8
import java.io.PrintWriter;
9
import javax.servlet.RequestDispatcher;
10
import javax.servlet.ServletException;
11
import javax.servlet.http.HttpServlet;
12
import javax.servlet.http.HttpServletRequest;
13
import javax.servlet.http.HttpServletResponse;
14
15
/**
16
 *
17
 * @author ORANITIN
18
 */
19
public class InterServ extends HttpServlet {
20
21
    /**
22
     * Processes requests for both HTTP
23
     * <code>GET</code> and
24
     * <code>POST</code> methods.
25
     *
26
     * @param request servlet request
27
     * @param response servlet response
28
     * @throws ServletException if a servlet-specific error occurs
29
     * @throws IOException if an I/O error occurs
30
     */
31
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
32
            throws ServletException, IOException {
33
        response.setContentType("text/html;charset=UTF-8");
34
        PrintWriter out = response.getWriter();
35
        
36
        String name=request.getParameter("name");
37
        String pass=request.getParameter("pass");
38
        
39
        if(name.equalsIgnoreCase("admin") && pass.equalsIgnoreCase("123"))
40
        {
41
            RequestDispatcher rd=request.getRequestDispatcher("welcome.jsp");
42
            rd.forward(request, response);
43
            //rd.include(request, response);
44
        }
45
        else
46
        {
47
              response.sendRedirect("index.jsp");
48
             //rd.include(request, response);
49
        }
50
        
51
        
52
        
53
        
54
        
55
        try {
56
            /* TODO output your page here. You may use following sample code. */
57
            out.println("<html>");
58
            out.println("<head>");
59
            out.println("<title>Servlet InterServ</title>");            
60
            out.println("</head>");
61
            out.println("<body>");
62
            out.println("<h1>Servlet InterServ at " + request.getContextPath() + "</h1>");
63
            out.println("</body>");
64
            out.println("</html>");
65
        } finally {            
66
            out.close();
67
        }
68
    }
69
70
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
71
    /**
72
     * Handles the HTTP
73
     * <code>GET</code> method.
74
     *
75
     * @param request servlet request
76
     * @param response servlet response
77
     * @throws ServletException if a servlet-specific error occurs
78
     * @throws IOException if an I/O error occurs
79
     */
80
    @Override
81
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
82
            throws ServletException, IOException {
83
        processRequest(request, response);
84
    }
85
86
    /**
87
     * Handles the HTTP
88
     * <code>POST</code> method.
89
     *
90
     * @param request servlet request
91
     * @param response servlet response
92
     * @throws ServletException if a servlet-specific error occurs
93
     * @throws IOException if an I/O error occurs
94
     */
95
    @Override
96
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
97
            throws ServletException, IOException {
98
        processRequest(request, response);
99
    }
100
101
    /**
102
     * Returns a short description of the servlet.
103
     *
104
     * @return a String containing servlet description
105
     */
106
    @Override
107
    public String getServletInfo() {
108
        return "Short description";
109
    }// </editor-fold>
110
}
111
112
113
114
    


Step 4: Create a new file welcome.jsp under Webpages and write the code given below.
Call data that Store we have stored in Session.

1
2
3
<%@page contentType="text/html" pageEncoding="UTF-8"%>
4
<!DOCTYPE html>
5
<html>
6
    <head>
7
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
8
        <title>JSP Page</title>
9
        <script>
10
          
11
            </script>
12
    </head>
13
    <body>
14
       
15
      <h>welcome login successfull..........</h>
16
            
17
    </body>
18
</html>
19
20
21
22