JEE : Java Server Page (JSP) life cycle

All the JSP run under supervising of web server. They do not receive requests from client and they do not send the response to client. All the JSP pages pass through the Server side processing. And result of sever side processing is sent to client. That is why they called dynamic pages. In the case of static page there is no server processing, web server returns them as they are.
Life Cycle
Dotted line showing that, When client sends the request for static page , server returns the requested page without processing and solid line showing that when client sends the request for dynamic page, server process it and the response generated is returned to client.
Life Cycle Steps
How the JSP executes
1. A request for a JSP pages is made by the client.
2. The request is handled by the web server.
3. Then the request is delegated to the JSP container
4. Container will check whether JSP to be invoked is changed or not
5. If there are some changes or its new JSP page then engine translates the contents of a JSP into its implementation servlet
6. Otherwise already implemented servlet is used by container.
7. Then container uses the service method of servlet to process the request of client.
Execution path for jsp pages
From the above figure we can see that there are to phase associated with the JSP, one is translation, compilation and execution.
  • The translation phase may be omitted if the servlet generated for a particular JSP is not older then that JSP.
  • Compilation phase also depends on the translation phase.
  • The execution phase always exists. The generated servlet is executed each time whenever the request is made by the client.

Popular Logics for implementation to check basic skills of fresher

Factorial
long Factorial( int n ) {
if ( n>0 )
return( n * Factorial(n-1) );
else
return( 1 );
}
Fibonacci
int Fibonacci( int n ) {
if ( n==1 || n==2 )
return( 1 );
else
return( Fibonacci(n-1) + Fibonacci(n-2) );
}
GCD
int GCD( int a, int b )
{
if ( a>=b && a%b==0 )
return( b );
else if ( a<b )
return( GCD( b, a ) );
else
return( GCD( b, a%b ) );
}
Power
double Power( double x, int n ) {
if ( n==0 )
return( 1 );
else if ( n>0 )
return( x * Power( x, n-1 ) );
else
return( (1/x) * Power( x, n+1 ) );
}
Reverse Printing
void ReverseChar( void ) {
char ch;
if ( (ch=getchar( ))!='n' )
ReverseChar( );
putchar( ch );
}
Decimal to binary conversion
void ToBin( int n ) /*
{
if (n>1)
ToBin( n/2 );
printf( "%d", n%2 );
}
Decimal to hexadecimal conversion
void ToHex( int n )
{
char *htab[ ] = { "0", "1", "2", "3", "4", "5", "6", "7", "8","9", "A", "B", "C", "D", "E", "F" };
if (n>15)
ToHex( n/16 );
printf( "%s", htab[n%16] );
}
Printing a decimal in words
void InWord( int n ) {
char *wtab[ ] = { "Zero", "One", "Two", "Three", "Four","Five", "Six", "Seven", "Eight", "Nine" };
if (n>9)
InWord( n/10 );
printf( "%s ", wtab[n%10] );
}

JSP SCRIPTING ELEMENTS

Expression tag ( <%= %>)

  • This tag is used to sent the output of the expression to the output stream like method println().
  • This tag allows the developer to embed any Java expression and is short for out.println().
  • This tag starts with <%= and ends with %>.
  • A semicolon ( ; ) does not appear at the end of the code inside the tag.
For example,to show the current date and time. <HTML>
<HEAD>
<TITLE>MCA</TITLE>
</HEAD>
<BODY>
Date : <%= new java.util.Date() %>
</BODY>
</HTML>

Declaration tag ( <%! %> )

  • This tag allows the developer to declare variables or methods.
  • Before the declaration you must have <%!
  • At the end of the declaration, the developer must have %>
  • Code placed in this tag must end in a semicolon ( ; ).
  • Declarations do not generate output so are used with JSP expressions or scriptlets.
For Example, <%! String course=”Master of Computer Application”; %> <HTML>
<HEAD>
<TITLE>MCA</TITLE>
</HEAD>
<BODY>
I am pursuing <%=course%>
</BODY>
</HTML>

Scriptlet tag ( <% ... %> )

  • Between <% and %> tags,any valid Java code is called a Scriptlet. This code can access any variable or bean declared.
  • Any code in scriptlet is executed when user asks to jsp page.
It is used to
  • Executing logic at server side
  • Implementing conditional HTML by posing a conditional on the execution of portion of page.
  • Printing HTML portion repeatedly by placing them into JSP Scriptlet’s Loop
For example <HTML>
<HEAD>
<TITLE>MCA</TITLE>
</HEAD>
<BODY>
<%
for(int i=0;i<5;i++){
%>
<br>This is jsp demo</br>
<%
}
%>
</BODY>
</HTML> OUTPUT of this JSP page is This is jsp demo This is jsp demo This is jsp demo This is jsp demo This is jsp demo

Directive tag ( <%@ directive ... %>)

  • A JSP directive gives special information about the page to the JSP Engine.
  • There are three main types of directives:
    • page - processing information for this page.
    • Include - files to be included.
    • Tag library - tag library to be used in this page.
Directives do not produce any visible output when the page is requested but change the way the JSP Engine processes the page. For example, you can make session data unavailable to a page by setting a page directive (session) to false.

JSP : Predifined variables | implicit objects

There are following implicit objects those become available to programmer to use in JSP page.

 

out

The out implicit object is an instance of a javax.servlet.jsp.JspWriter object and is used to send content in a response. The JspWriter object emulates some of the functionality found in the java.io.PrintWriter and java.io.BufferedWriter objects to provide a convenient method of writing text in a buffered fashion. The out implicit object can be configured on a per JSP basis by the page directive. Example :

<HTML>
<HEAD>
<TITLE>JSP Demo</TITLE>
</HEAD>
<BODY>
<% out.write("Server Date is: "); %>
<% out.write(new java.util.Date().toString()); %>
</BODY>
</HTML>

 

request

The request implicit object is an instance of a javax.servlet.http.HttpServletRequest object. The request implicit object represents a client's request and is a reference to the HttpServletRequest object passed into a HttpServlet's appropriate service method.

 <HTML>
<HEAD>
<TITLE>JSP Demo</TITLE>
</HEAD>
<BODY>
<%= request.getParameter("text")%>
</BODY>
</HTML>

Type the following url on address bar: http://localhost:8080/jsp1/requestobject.jsp?text=hello user Output is : hello user

 

response

The response implicit object is an instance of a javax.servlet.http.HttpServletRequest object. The response implicit object represents a response to a client's response and is a reference to the HttpServletResponse object passed into a HttpServlet's appropriate service method.

 <HTML>
<HEAD>
<TITLE>JSP Demo</TITLE>
</HEAD>
<BODY>
<%
response.setContentType("text/html");
java.io.PrintWriter pw=response.getWriter();
pw.println("Hello world");
%>
</BODY>
</HTML>

 

session

The session implicit object is an instance of a javax.servlet.http.HttpSession object. By default JSP creates a keep session context with all clients. The session implicit object is a convenience object for use in scripting elements and is the equivalent of calling the HttpServletRequest getSession() object.

<HTML>
<HEAD>
<TITLE>JSP Demo</TITLE>
</HEAD>
<BODY>
<%
int hits=0;
String h=""+session.getAttribute("hits");
if(h==null){
hits=0;
}else{
hits=Integer.parseInt(h);
}
hits++;
out.write("Total Hits : "+hits);
session.setAttribute("hits",""+hits);
%>
</BODY>
</HTML>

Output: Total Hits : 4

 

application

The application implicit object is an instance of a javax.servlet.ServletContext object. The application implicit object represents a Servlet's view of a Web Application and is equivalent to calling the ServletConfig getServletContext() method.

<HTML>
<HEAD>
<TITLE>JSP Demo</TITLE>
</HEAD>
<BODY>
<%
int hits=0;
String h=""+application.getAttribute("hits");
if(h==null||h.equals("null")){
hits=0;
}else{
hits=Integer.parseInt(h);
}
hits++;
out.write("Total Hits : "+hits);
application.setAttribute("hits",""+hits);
%>
</BODY>
</HTML>

Output: Total Hits : 4

 

config

The normal JSP deployment scheme automatically done by a container works, but nothing stops a JSP developer from declaring and mapping a JSP via the Web Application Deployment Descriptor, web.xml. A JSP can be manually deployed in the same fashion as a Servlet by creating a Servlet declaration in web.xml and replacing the servlet-class element with the jsp-page element. After being declared, the JSP can be mapped to a single or set of URLs same as a Servlet. Example to passing initial parameters to JSP page using config object.

In Web.xml 

  <web-app>
<servlet>
<servlet-name>configobject.jsp</servlet-name>
<jsp-file>/configobject.jsp</jsp-file>
<init-param>
<param-name>author</param-name>
<param-value>Hemraj</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>configobject.jsp</servlet-name>
<url-pattern>/configobject.jsp</url-pattern>
</servlet-mapping>
</web-app> 

 In configobject.jsp 

 <HTML>
<HEAD>
<TITLE>JSP Demo</TITLE>
</HEAD>
<BODY>
<h2>Author of Page:</h2>
<h3><%=""+config.getInitParameter("author")%></h3>
</BODY>
</HTML>

 

page

The page implicit object represents the current class implementation of the page being evaluated. If the scripting language of the page is java, which by default it is, the page object is equivalent to the keyword of a Java class. This object is used to refer the instance of current JSP page created after translation in servlet. We can use it to differentiate local and instance variable as shown in following example.

<HTML>
<HEAD>
<TITLE>JSP Demo</TITLE>
</HEAD>
<BODY>
<%out.write(page.toString());%>
</BODY>
</HTML>

 

exception

The exception object is available only within error pages. It is a reference to the java.lang.Throwable object that caused the server to call the error page. You would use it just as you would use any other Exception or Error object in the catch block of a try-catch section of code. The exception object has page scope.
Example :

 <%@page contentType="text/html" pageEncoding="UTF-8"%> <html>
<head>
<title>JSP Page</title>
</head>
<body>
<h2>Error/Exception :</h2>
<%=exeception.getMessage()%>
</body>
</html>

 

pageContext

The pageContext implicit scripting variable is an instance of a javax.servlet.jsp.PageContext object. A PageContext object represents the context of a single JavaServer Page including all the other implicit objects, methods for forwarding to and including Web Application resources, and a scope for binding objects to the page. The PageContext object is not always helpful when used by itself because the other implicit objects are already available for use. A PageContext object is primarily used as a single object that can easily be passed to other objects such as custom actions. This is useful since the page context holds references to the other implicit objects.

 <HTML>
<HEAD>
<TITLE>JSP Demo</TITLE>
</HEAD>
<BODY>
<%
int hits=0;
String h=""+ pageContext.getAttribute("hits");
if(h==null||h.equals("null")){
hits=0;
}else{
hits=Integer.parseInt(h);
}
hits++;
out.write("Total Hits : "+hits);
pageContext.setAttribute("hits",""+hits);
%>
</BODY>
</HTML>

Output: Total Hits : 4

@AttributeOverrides annotation in hibernate/JPA

@AttributeOverrides annotation is used in hibernate/JPA to rename the column(s) name of the embadable class while it is being embedded in other class.
Suppose A class is embedded in class B, then if A entity contains the column name of any property "phone", then B entity can override the column name to "mobileNumber". So, in the table, column name will be "mobileNumber".

package entity;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Embeddable;

@Embeddable
public class ContactKey implements Serializable {
    private int roll;
    private String sem;
    private String branch;

    public int getRoll() {
        return roll;
    }

    public void setRoll(int roll) {
        this.roll = roll;
    }

    @Column(name = "sem")
    public String getSem() {
        return sem;
    }

    public void setSem(String sem) {
        this.sem = sem;
    }

    public String getBranch() {
        return branch;
    }

    public void setBranch(String branch) {
        this.branch = branch;
    }

    @Override
    public String toString() {
        return "ContactKey [roll=" + roll + ", sem=" + sem + ", branch="
                + branch + "]";
    }
}


package entity;

import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;

@Entity(name="Contact")
@Table(name="Contact")
public class Contact {
    
    @Id
    @GeneratedValue
    private    int id;
    
    @Embedded
    @AttributeOverrides(
            @AttributeOverride(name="sem",column=@Column(name="semester"))
    )
    private ContactKey contactKey;
    private String name;
    private String email;
    private long phone;
    
    
    public String getName() {
        return name;
    }

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

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public long getPhone() {
        return phone;
    }
    
    public void setPhone(long phone) {
        this.phone = phone;
    }
    
    public ContactKey getContactKey() {
        return contactKey;
    }

    public void setContactKey(ContactKey contactKey) {
        this.contactKey = contactKey;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
    
}

here, database table will not contain the column "sem". It will have the "semester" column since we have overridden in contact entity.

Hibernate (or JPA) - Using "mappedBy" attribute of mapping annotations(like @OneToOne, @OneToMany, @ManyToMany)

Using "mappedBy" attribute of mapping annotations(like @OneToOne, @OneToMany, @ManyToMany) for bi-directional relationship. This attribute allows you to refer the associated entities from both sides. If "X" has association with "Y" then you can get X from Y and Y from X.

For example, If you have "Book" entity and "Author" entity those are associated to each other in the way that Book has a Author and Author associated with a Book.
Now if you retrieve the Book Object from hibernate session, then you can get the Author entity from Book entity. Or if you get the Author entity then you can get the Book entity from Author entity.
So you require the bidirectional navigation relationships between Book and Author entities.

This is achieved in the Hibernate using the  @OneToOne relationship provided that child entity must have property type of parent and marked with annotation @OneToOne(mappedBy="parent") where parent is the Owner entity of this child entity.


package entity;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;

@Entity
@Table(name = "Book")
public class Book {
    private int id;
    private String title;
    private String content;
    private Author author;

    @Id
    @GeneratedValue
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
    
    @OneToOne(cascade=CascadeType.ALL)
    public Author getAuthor() {
        return author;
    }

    public void setAuthor(Author author) {
        this.author = author;
    }

    @Override
    public String toString() {
        return "Book [id=" + id + ", title=" + title + ", content=" + content
                + ", author=" + author.getId() + "]";
    }
    
}


package entity;

import javax.persistence.*;

@Entity
@Table(name = "Author")
public class Author {
    private int id;
    private String name;
    private String email;
    private long phone;
    private Book book;
    @Id
    @GeneratedValue
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public long getPhone() {
        return phone;
    }

    public void setPhone(long phone) {
        this.phone = phone;
    }
    @OneToOne(mappedBy="author")
    public Book getBook() {
        return book;
    }

    public void setBook(Book book) {
        this.book = book;
    }

    @Override
    public String toString() {
        return "Author [id=" + id + ", name=" + name + ", email=" + email
                + ", phone=" + phone + ", book=" + book.getId() + "]";
    }
    
}


Testing classes

Inserting records


import java.util.ArrayList;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import entity.Author;
import entity.Book;


public class Insert {
    public static void main(String[] args) {
        Configuration cfg=new Configuration();
        SessionFactory sf=cfg.configure("hibernate.cfg.xml").buildSessionFactory();
        Session session = sf.openSession();
        
        Author author=new Author();
        author.setEmail("author@gmail.com");
        author.setName("name");
        author.setPhone(543653465L);
        
        Book book1=new Book();
        book1.setAuthor(author);
        book1.setContent("re  td e sdf asdfasdfasd f");
        book1.setTitle("java");
        
        session.beginTransaction();
        session.save(book1);
        session.getTransaction().commit();
        
    }
}

Retrieving Records

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import entity.Author;
import entity.Book;

public class update {
    public static void main(String[] args) {
        Configuration cfg=new Configuration();
        SessionFactory sf=cfg.configure("hibernate.cfg.xml").buildSessionFactory();
        Session session = sf.openSession();
        session.beginTransaction();
        
        //Book book = (Book) session.get(Book.class, 2);
        //System.out.println(book.getAuthor());
        
        Author author = (Author) session.get(Author.class3);
        System.out.println(author.getBook());
        //book.getAuthor().setName("Test Author");
        //session.getTransaction().commit();
        
    }
}

hibernate configuration file

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="connection.driver_class">oracle.jdbc.OracleDriver</property>
        <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
        <property name="connection.username">hemraj</property>
        <property name="connection.password">hemraj</property>
        <property name="dialect">org.hibernate.dialect.OracleDialect</property>
        <property name="hbm2ddl.auto">update</property>
        <property name="show_sql">true</property>
        <mapping class="entity.Library"/>
        <mapping class="entity.Book"/>
        <mapping class="entity.Author"/>
    </session-factory>
</hibernate-configuration>

Popular Posts