Servlet Context tutorial for Java beginners

Written by admin on . Posted in Advanced Java

What is a servletcontext

ServletContext is a configuration Object which is created when web application is started. It contains different initialization parameter that can be configured in web.xml.

Example of ServletContext with scenario

You are developing a web application where you want to access the email of administrator in whole application. You want to set this email id @ one location and every Servlet and Jsp can access that email. In that case you will take the help of ServletContext. You can add this email in servletcontext via init parameter in web.xml. Now this value (Email id of administrator) will be available to every Jsp and Servlet in the web application.

Life Cycle of ServletContext

Step 1: Servlet container reads the DD (Deployment Descriptor – web.xml) and creates the name/value string pair for each <context-param> when web application is getting started.

Step 2: Container creates the new Instance of ServletContext.

Note*: ServletContext is an Interface.

Step 3: Servlet container gives the ServletContext a reference to each name/value pair of the context init parameter.

Step 4: Every servlet and JSP in the same web application will now has access to this ServletContext.

Servlet context init parameter Syntax

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
</web-app>

 

Difference from ServletConfig

  • ServletConfig is one per servlet while ServletContext is one per web application.
  • ServletContext is available to all servlet & jsp in web application while ServletConfig will be available only specific servlet.
  • Difference in the syntax for servletcontext and servletconfig.

What is servletcontextlistener

Now you know that you can set init parameter in ServletContext & this Servletcontext will be initialized when application starts. After initialization this servletcontext will be available to all servlet and jsp. But what if you want to perform some kind of action when context initialization/destruction process happens. This is the situation when you will take the help of servletcontextlistener.

 

Bullet Points

  • Only one ServletContext is available per web application.
  • Every servlet in the same web application will have access to servletcontext.
  • It is used to access application level parameter.
  • If application is in distributed environment then there will be one servletcontext per JVM.
  • ServletContext has init parameter that can be configured in web.xml.

Java Servlet Container tutorial for beginners

Written by admin on . Posted in Advanced Java

What is Servlet Container

Normal Java application’s starting point is Main(public static void main(String args[])) method. When ever java application needs to start, main method of the application should be invoked. But in case of Servlet this is not true, Servlet doesn’t contain any main method. So who will initiate and run the method of Servlet. It’s Container who has the full control of Servlets. Tomcat is the example of Servlet container.

How it works

When ever user request for any resource from Server Web server(Apache) will pass the request to Servlet Container(Tomcat) instead of directly to servlet. It is container who will create request and response Object and then pass it to Servlet eligible for asked resource and invoke service method of Servlet.

Services Provided by Container

  • Communication Support
  • Servlet Life cycle management
  • MultiThreading Support
  • JSP Support

Web Application Basics

Written by admin on . Posted in Advanced Java

Different Actors in Web application

There are different actors which comes into picture of web application.

  • End User
  • Web Client(Browser Application)
  • Server(Web Server / Application Server)
  • Actual Page requested on Server

User : It’s the end user who actually raise the request for a page on Server or submit a form.

Web Client : Browsers(IE, Firefox..) are software that knows how to communicate with servers using HTTP protocol and render the page recieved from server in the form of HTML.

Server : Servers are kind of software which handle the user request and search for the content requested by end User and return the appropriate result(Requested Page or Error Code). Server can be of two type web server and App Server. It’s web server which directly handles the user request and pass it to app server to process.

 

What is HTML

HTML(Hyper text markup Language) is a language used by servers to send the response to Browser’s so that they(Browsers) can render the page properly on user side.

What is HTTP Protocol

HTTP(Hyper Text Transfer Protocol) is protocol used by client(Browser) and server(Web Server) to communicate.  HTTP has web specific featured that  runs on TCP/IP protocol. Structure of HTTP conversation can be divided in two types, HTTP Request or HTTP Response.

Note*: HTML can be the part of HTTP protocol response.

HTTP Request

When ever end User clicks any link or submit any form browser send HTTP Request to Server so that server can process it and provide the HTTP Response.

HTTP Request’s are of different kind. HTTP has several methods which inform the server about the kind of Request is being made by browser.

Methods in HTTP Protocol

  • GET
  • POST
  • PUT
  • DELETE
  • HEAD
  • TRACE
  • OPTION
  • CONNECT
GET and POST are the method which is used mostly in web environment and we will discuss only those.

GET method is the default method which will be used by Browser(If not specified explicitly). GET method is used by browser to ask(Not submitting any data) for some kind of resources on server(HTML, Image, PDF  etc..).

POST method is used by browser to send some information to server for processing. Eg.  Form Submission..

HTTP Request Example

Host            =javabeginnerstutorial.com
User-Agent      =Mozilla/5.0 (Windows NT 6.0; rv:15.0) Gecko/20100101 Firefox/15.0.1
Accept          =text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language =en-gb,en;q=0.5
Accept-Encoding =gzip, deflate
Connection      =keep-alive
Cookie          =****Deleted Date *********
If-None-Match   =****Deleted Date *********

 

Difference between GET and POST method

GET method used for asking some data from server. While POST is used for submission some data to server.

GET is idempotent while POST is not idempotent.

GET do not have any BODY part while POST has.

GET can submit some data but that will be the part of Header  and there is limitation on data submitted via GET method while Post can submit data in body part and there is no restriction on data that can be submitted in POST request.

HTTP Response

This is what server send to user client(Browser) when user ask for something from Server(GET / POST Request). HTTP Response contains Header and a Body part.

HTTP Response Header Contains below information along with others

  • Protocol Version(Used by web server)
  • HTTP Status Code(Successful/Fail/Not Found….)
  • Content Type (MIME Type)
  • Content Length
  • Date
  • Server details

Content Type(content-type) in header part of HTTP response is also known as MIME type. This information is used to tell the browser the kind of data server is sending,  weather it is Image or Text or PDF or anything else. According to this information Browser will know how to handle the data.

HTTP Response, Body part contains the HTML or other content that needs to be rendered by Browser on client side.

HTTP Response Example

Status           =OK - 200
Date             =Sun, 07 Oct 2012 18:00:32 GMT
Server           =Apache
X-Pingback       =http://javabeginnerstutorial.com/
Vary             =Accept-Encoding,Cookie,User-Agent
Expires          =Sun, 07 Oct 2012 19:00:33 GMT
Pragma           =public
Cache-Control    =max-age=3600, public, must-revalidate, proxy-revalidate
Etag             =89aba25474c721198ed96b924c270932
X-Powered-By     =W3 Total Cache/0.9.2.4
Content-Encoding =gzip
Set-Cookie       =PHPSESSID=3ccad49ae7e632de2f908b8ba36e70a5; path=/
Last-Modified    =Sun, 07 Oct 2012 18:00:33 GMT
Content-Type     =text/html; charset=UTF-8
X-Cache          =*****************Deleted Data***************
X-Cache-Lookup   =*****************Deleted Data***************
Via              =*****************Deleted Data***************
Connection       =close

 

Variable shadowing

Written by doanduyhai on . Posted in Advanced Java

Today we’ll look into a rare feature of Java: variable shadowing

First, let’s define what is a shadowed field or method:

A field is considered shadowed when

  • a subclass of its declaring class declares a field with the same name and same
  • a variable having the same name and type is declared in the local scope
  • a method argument/parameter is declared with a same name and type

Servlet Basics

Written by admin on . Posted in Advanced Java

Servlet Basic

Servlet don’t have a main method. It is container which is responsible to manage the lifecycle of servlet. Web server hands the request to web container in which servlet is deployed and not to Servlet itself. Then container provides request and response to servlet. It is container which calls the servlet’s method.

Advantage of Using Container

  1. Lifecycle management of servlet
  2. Multithreading support for servlet
  3. Security provide
  4. JSP support
  5. Provides communication between web server and servlet

Servlet Life Cycle

  1. Servlet Instantiation by no-arg Constructor run.
  2. init() method will be called. This method called once in the life cycle of servlet. Internally init(ServletConfig) is called which internally call init() method.
  3. Servlet is initialized and will be in this state till it is destroyed. Till then all request will go through service() method. Each request will run in separate thread.
  4. destroy() method will be called by Container to clean up all the resource. Here lifecycle of servlet will finish.

It is the ServletConfig which transform an Object to Servlet. Container provides servletcofig to servlet via init() method.

ServletConfig

  • Used to provide deploy-time information to the servlet.
  • One servletConfig per servlet will be created.
  • Can be used to access to access servletContext.

ServletContext

  • ServletContext per web application will be created.
  • Used to access web app parameter.
  • Will be available to all the servlet in application.

Note: HttpServletRequest and HttpServletResponse are interfaces. It is container which implements given interface.

JSP Basics

Written by admin on . Posted in Advanced Java

JSP Basic

A JSP becomes a servlet. You don’t directly create servlet, it is generated by Container only. Container takes what you have written in your JSP, translates it into a servlet class source file then compiles that into a java servlet class. And this code would execute in the same as it were written in java file.

JSP Elements

There are 4 basic JSP elements.

  • Scriptlet
  • Directive
  • Expression
  • Declaration

Scriptlet

You might face the situation where you have to add Java code in JSP. You can use scriptlet.

<%
system.out.println("Hello");
%>

 


Directive

Type of Directive

Its a way to give instruction to Container on at page translation time. Type of Directive

  • page
  • include
  • taglib
Page Directive

There might be situation where you need to import some package in JSP like you do in java file. You can use directive for this purpose.

Syntax
<%@ %>
Single package import
<%@ page import="java.lang.*" %>
Multiple package Import
<%@ page import="java.lang.*,java.lang.util.*" %>

 


Expression

Expression is used when you want to provide some argument to statement that prints to the implicit response PrintWriter out. Expression becomes the argument to an out.print().

Syntax

Method parameter

<%= contact.getName()%>

variable access

<%= x %>

Note: If there are local variable as well as instance variable then above statement will print the value of local variable if you want to print the instance variable then use this like below.

<%= this.x %>

Here contact.getName will be provided as the argument to out implicit object as it is. Note: DO not place ”;” in the end of expression.
Note: All scriptlet and expression code lands in a service method. So all the variables declared in scriptlet will be a local variable. To make a class level variable JSP declaration can be used.


Declaration

JSP declaration defined inside the class but outside the service method. It means declaration is for static and instance variable and methods.

Syntax

Variable declaration

<%! int i=0;%>

Method Declaration

<%! String getName()
{
   String name = "JBT";
    return name;
}
%>

Note: Here we are using ”;” in the end as it be statment in generated java file. So it is required.

Implicit Object

There are some implicit object which container will provide to use directly in JSP these are called Implicit Object. There are 9 implicit Object in JSP

  • out
  • request
  • response
  • session
  • application
  • config
  • exception
  • pageContext
  • page

These implicit objects are map to Object from Servlet/JSP API.

Implicit Object API
out JspWriter
request HttpServletRequest
response HttpServletResponse
session HttpSession
application ServletContext
config ServletConfig
exception Throwable
pageContext PageContext
page Object

JSP Comment

You can put comments in JSP and there are two type of comments in JSP.

HTML Comment

These comment will be the part of generated response means these comment will go to client side. Syntax:

<!-- Comment -->

JSP Comment

These comments are for the developer only it will not be the part of translated page. Syntax:

<%-- Comment --%>