Friday 24 December 2010

URL Rewriting

URL Rewriting:
·         This is one of approach of implementing session tracking
·         In this approach we rewrite the URLs in the response message adding the data to maintain for the next request
Note:
·         The Session data here can be added into the URL
·         The url either in the form of QueryString or path info
·         In case of query string we separate the URL with ? char
·         We can read this data as request parameter
·         In case of path info: first we need to configure the URL pattern for the servlet as path mapping. And in the program we can read it using getPathInfo() or getRequestURI() method.
What are the limitations of this approach?
·         The Session data is maintained in URL.
·         THE size and type of content is restricted
·         URL Rewriting is not secure
·         All the pages in the Session should be dynamic
·         Increases the dependency: as all the possible pages processing the request between the sources and target pages should implement URL Rewriting
Note:
We prefer the URL Rewriting in case of maintaining non-sensitive, small and simple text data in short length Sessions



More articles on

session tracking

session tracking:
is a process of maintaining / tracking the user data in a session.
Session: is an uninterrupted set of request and response between a client and server.
Advantages:
This helps improving the communication with the client also gives convenience avoiding asking the same data repeatedly.
Example:
Ecommerce:
1). Flipcart
2) snapdeal
To maintain the cart all most every website is using session tracking to remember the login user.
Session tracking can be implemented in 4 ways:

1.      URL Rewriting
2. HTML Hidden Form Filed
3.       Cookie
4.       HttpSession
·         This is one of approach of implementing session tracking
·         In this approach we rewrite the URLs in the response message adding the data to maintain for the next request
Note:
·         The Session data here can be added into the URL
·         The url either in the form of QueryString or path info
·         In case of query string we separate the URL with ? char
·         We can read this data as request parameter
·         In case of path info: first we need to configure the URL pattern for the servlet as path mapping. And in the program we can read it using getPathInfo() or getRequestURI() method.
What are the limitations of this approach?
·         The Session data is maintained in URL.
·         THE size and type of content is restricted
·         URL Rewriting is not secure
·         All the pages in the Session should be dynamic
·         Increases the dependency: as all the possible pages processing the request between the sources and target pages should implement URL Rewriting
Note:
We prefer the URL Rewriting in case of maintaining non-sensitive, small and simple text data in short length Sessions

session management (http://raj-servlets.blogspot.com/2013/09/session-management.html)
Session tracking types:




More articles on
Session management or session tracking



what is session ?

session is an uninterrupted set of request and response between a client and server.


example project on session tracking (hidden form , url rewriting, forward, include)






Monday 1 November 2010

About HttpSession:

About HttpSession:
Assume
1)open browser
2)Request sent to servlet
3)Servlet calls request.getSession() server creates HttpSession object on the server side and gives response back and along with response it sends the session id
(you can think as reference to the HttpSession object created in the above step)
4)We request to another servlet or same servlet or another jsp, this time
browser sends the session id that it received in the above step to server when
you make request it happens in the background...
5)Now if you call request.getSession, server won't create new HttpSession
object, it identifies the existing session object by matching the session id
sent by browser..
6)When user calls logout button we write code session.invalidate() and
the httpsession object on the server will be destroyed
Now if you open new browser and make request... in the response
server creates another httpsession object and all the above steps
repeats....
What is the use of it ?
If you store any object in request scope when you send new request
the previous request object wont be there.
If you store any object in session scope you can get that object in
all the requests....
Real time comparison:
What if you don't have httpsession
1)You visited flipkart you went to the page where shoes were displayed
and you ordered 1 pair of shoes
2)Then you visited Cell phone related page and bought one
3)And then you tried to pay how would you feel if it shows only cell
This is what happens if you use request scope to store the items
purchased.The things you stored wont' be available in second request
as you know request object life is short... once the response came back
request object no more exists...
So here if you use HttpSession to store the objects you bought then
when you check out it displays all the items you bought
Imagine the bad things that can happen if you don't logout.
Imagine you logged in to your bank site and didn't logout then
if some other user came to the internet center that session object
might be still valid and that user can transfer money from your account.
That is the reason we have to logout...Banks generally write code to
expire the session if user doesn't use the site for 1 minute or 2 minutes
so that others may not take advantage if you don't log out

1)If you open a browser and close the browser generally it is the httpsession scope. But some times what happens is even if you open another browser in internet explorer some times both first and second browser takes the same httpsession object ... If you go to file->New session then only other httpsession object gets created... when you call request.getSession

But if you open one IE browser and Mozilla browser then you can clearly understand that.... HttpSession object gets created for each browser.... So when you open one IE browser and Mozilla browser 2 httpsession object gets printed...Best way to understand is by printing httpsession.... then you can see if same content is printed then you can think as same session



some more examples: HttpSession


Example program for HttpSession

Thursday 17 June 2010

Displaying Date

Steps:

Maintain Folder Structure


GoTo your folder DisplayDate
under src folder
create java file DisplayingDate.java

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class DisplayingDate extends HttpServlet
{
 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
 {
  PrintWriter pw=response.getWriter();
  Date today=new Date();
  pw.println("<html>"+<body><h1>Today Date is</h1>");
  pw.println("<b>"+today+"</b></body>"+"</html>");
 }
}

Compile this program.
javac DisplayingDate.java

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class DisplayingDate extends HttpServlet
{
 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
 {
  PrintWriter pw=response.getWriter();
  Date today=new Date();
  pw.println("<html>"+"<body><h1>Today Date is</h1>");
  pw.println("<b>"+today+"</b></body>"+"</html>");
 }
}

Again compile:
javac DisplayingDate.java

We got errors that packages does not exist
package  javax.servlet.
package  javax.servlet.http.
Because we have not set the class path.
So set the class path
E:/DisplayDate/src>set classpath=C:\Program Files\Apache Software Foundation\Tomcat 8.0\lib\servlet-api.jar;
now compile the program
javac DisplayingDate.java

Now ok.
Go to WEB-INF folder
open web.xml file
<web-app>
 <servlet>
  <servlet-name>Hello</servlet-name>
  <servlet-class>DisplayDate</servlet-class>
 </servlet>
 <servlet-mapping>
 <servlet-name>Hello</servlet-name>
 <url-pattern>/DateDisplay</url-pattern>
</servlet-mapping>
</web-app>

-->Save the file
Deploy your project (folder) DisplayDate into Servler
Go to apache tomcat server folder




Start the server:


Go to any browser:
and type your local host with port no
http://localhost:8080/





type user name and password; (at the time of installing tomcat server we should set the username and password.)
here my username is: root
password is root.










Tuesday 15 June 2010

How many ways to develop servlet programs

There are three ways to develop

1. Take Java class implementing javax.servlet.Servlet(Interface) and provide implementation to all the 5 methods of that interface

2. Take a java class extending from javax. servlet.GenericServlet(class) and provide implementation to public void service(-,-) method.

3. Take a Java class extending from javax.servlet.HttpServlet(class) and override one of the seven (7) doXXX(-,-) methods.

How many types of servlets?

There is a possibilities of developing 'n' types of servlets like httpServlet, ftpservlet, smtpServlet and etc,...for all these protocals are specific servlet classes.
GenericServlet is the super class contains common properties and logics. 

Monday 14 June 2010

Web Application Folder Structure






Work flow of Servlet

Work flow of Servlet

The server checks if the servlet is requested for the first time.
If yes, web container does the following tasks:
loads the servlet class.
instantiates the servlet class.

calls the init() method passing the ServletConfig object
else
calls the service() method passing request and response objects

The web container calls the destroy method when it needs to remove the servlet such as at time of stopping server or undeploying the project.

How web container handles the servlet request?
The web container is responsible to handle the request. Let's see how it handles the request.
maps the request with the servlet in the web.xml file.
creates request and response objects for this request
calls the service method on the thread

The public service method internally calls the protected service method
The protected service method calls the doGet method depending on the type of request.
The doGet method generates the response and it is passed to the client.
After sending the response, the web container deletes the request and response objects. The thread is contained in the thread pool or deleted depends on the server implementation.

What is written inside the public service method?
The public service method converts the ServletRequest object into the HttpServletRequest type and ServletResponse object into the HttpServletResponse type. Then, calls the service method passing these objects. Let's see the internal code:

public void service(ServletRequest req, ServletResponse res) 
        throws ServletException, IOException 
    { 
        HttpServletRequest request; 
        HttpServletResponse response; 
        try 
        { 
            request = (HttpServletRequest)req; 
            response = (HttpServletResponse)res; 
        } 
        catch(ClassCastException e) 
        { 
            throw new ServletException("non-HTTP request or response"); 
        } 
        service(request, response); 
    } 


What is written inside the protected service method?
The protected service method checks the type of request, if request type is get, it calls doGet method, if request type is post, it calls doPost method, so on. Let's see the internal code:

protected void service(HttpServletRequest req, HttpServletResponse resp) 
        throws ServletException, IOException 
    { 
        String method = req.getMethod(); 
        if(method.equals("GET")) 
        { 
            long lastModified = getLastModified(req); 
            if(lastModified == -1L) 
            { 
                doGet(req, resp); 
            }  
    .... 
    //rest of the code 
        } 
    } 



You may like the following posts:
Web Container

How to access your Web Application in other systems

I would like to make available to other to access my web application:

1. Once your web application is ready
2. Go to command prompt
3. type ifconfig (press enter)

Note down your Computer  IP Address. for example: IPv4 Address. . . . . . . . . . . : 192.168.0.112
Start your server to Run your Application. (Here I'm using Tomcat Server)





 So your local web portal link is:
Go to Any browser :
192.168.0.112:8080/ServRequest/
Syntax: your system ip address:port number/url-name


Wednesday 9 June 2010

Example program on Servlet Request


index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Servlet Request</title>
<form method="get" action="check">
Enter your name<input type="text" name="name"> <br>
<input type="submit" value="login">
</form>
</head>
<body>
</body>
</html>


Servlet Program:
//DemoReq1.java

import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class DemoReq1 extends HttpServlet
{
 public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
 {
  res.setContentType("text/html");
  PrintWriter pw=res.getWriter();
 
  String name=req.getParameter("name");//will return value
  pw.println("Namasthe  "+name);
  pw.close();
 }
}

web.xml


<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<servlet>
 <servlet-name>Raj</servlet-name>
 <servlet-class>DemoReq1</servlet-class>
</servlet>
<servlet-mapping>
  <servlet-name>Raj</servlet-name>
 <url-pattern>/check</url-pattern>
</servlet-mapping>
</web-app>










rereree














You may like the following posts:

Tuesday 8 June 2010

What is web.xml file

The deployment descriptor is an xml file, from which Web Container gets the information about the servet to be invoked.
The web container uses the Parser to get the information from the web.xml file. There are many xml parsers such as SAX, DOM and Pull.
There are many elements in the web.xml file. Here is given some necessary elements to run the simple servlet program.


<web-app> represents the whole application.
<servlet> is sub element of <web-app> and represents the servlet.
<servlet-name> is sub element of <servlet> represents the name of the servlet.
<servlet-class> is sub element of <servlet> represents the class of the servlet.
<servlet-mapping> is sub element of <web-app>. It is used to map the servlet.
<url-pattern> is sub element of <servlet-mapping>. This pattern is used at client side to invoke the servlet.


Monday 7 June 2010

Introduction to Servlets

There are two types of Web Resource programs:

1. Static Web resource Programs:
    It generates static web pages. Ex: html pages
2. Dynamic Web resource programs:
    It generates dynamic web pages.
    Ex:
    Servlet programs
    JSP programs
   ASP.net
   Etc.,


What is Web Application?
A Web application is a collection of web resource programs.

img file, java script file can not generate web pages directly but they act as helper programs to another web resource programs.

Web Application is a collection of static, dynamic and helper (Ex: image files) programs.



To Execute Java Apps we need JRE+JVM
To execute Applet programs we need Applet viewer
To execute Servlet programs we need Servlet Container or Web Container. Web Servers (Ex: Tomcat, WebLogic) supplies this Servlet, JSP containers.


Servlet Features:

Better performance: because it creates a thread for each request not process.
Portability: because it uses java language.
Robust: Servlets are managed by JVM so we don't need to worry about memory leak, garbage collection etc.
Secure: because it uses java language..


You may like the following posts:

Friday 4 June 2010

Prerequisite to learn Servlets


1. Download any server (Ex: Tomcat, Weblogic,..)
    How to download Tomcat Server
2. Download the jar files
    servlet-api.jar
3. JDK 7
4. Eclipse IDE for Java EE Developers (Juno 4.2)
5. import javax.servlet and javax.servlet.http packages

Table of Content:

1. Create Dynamic Web Project

2. Create Servlet class

3. Deploy the servlet

4. Run and test the servlet





How to download Tomcat Server

http://crunchify.com/step-by-step-guide-to-setup-and-install-apache-tomcat-server-in-eclipse-development-environment-ide/

For Command Prompt:
1. go https://tomcat.apache.org/download-80.cgi or

2. Go to Binary Distributions
3. Choose Core:
4. Click on 32-bit/64-bit Windows Service Installer (pgp, md5, sha1)
5. Once you download the Tomcat Server installer,click on to install

Go to Downloads in your PC


Click on apache-tomcat-..exe file

Next





HelloWorld servlet program


Sunday 2 May 2010

Servlet Interview Questions and Answers

Web Application Structure


Example program for Filter

//Home.html
<html>
 <body>
<form method=post action="ser1">
<input type="submit" value="Invoke TestServlet using path /ser1"/>
</form><br><br>
<form method=post action="ser2">
<input type="submit" value="Invoke TestServlet using path /ser2"/>
</form>
 </body>
</html>
//TestServlet.java
//TestServlet
package com.rajendra.servlets;

import javax.servlet.*;
import java.io.*;

public class TestServlet extends GenericServlet {

public void service (ServletRequest req, ServletResponse res) throws ServletException, IOException {

PrintWriter out=res.getWriter();
out.println("In TestServlet, processing request<br/>");
}//service
}//class
//Creating MyFilter1.java
//Filter
package com.rajendra.servlets;

import javax.servlet.*;
import java.io.*;

public class MyFilter1 implements Filter {

public void init(FilterConfig fc){}

public void doFilter(ServletRequest req, ServletResponse res, FilterChain fc) throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.println("In MyFilter1, filtering Request...<br/>");

fc.doFilter(req,res);

//Post Processing can be performed here if any
out.println("In MyFilter1, filtering Response...<br/>");
}//doFilter

public void destroy() {}
}//class
//MyFilter2.java
//Filter
package com.rajendra.servlets;

import javax.servlet.*;
import java.io.*;

public class MyFilter2 implements Filter {

public void init(FilterConfig fc){}

public void doFilter(ServletRequest req, ServletResponse res, FilterChain fc) throws ServletException, IOException {
PrintWriter out=res.getWriter();
out.println("In MyFilter2, filtering Request...<br/>");

fc.doFilter(req,res);

//Post Processing can be performed here if any
out.println("In MyFilter2, filtering Response...<br/>");
}//doFilter

public void destroy() {}
}//class
//Configuring the Filter Application
<!--web.xml-->
<web-app>
<filter>
<filter-name>filter1</filter-name>
<filter-class>com.santosh.servlets.MyFilter1</filter-class>
</filter>
<filter>
<filter-name>filter2</filter-name>
<filter-class>com.santosh.servlets.MyFilter2</filter-class>
</filter>

<filter-mapping>
<filter-name>filter1</filter-name>
<url-pattern>/ser1</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>filter2</filter-name> 
<servlet-name>ts1</servlet-name>
</filter-mapping>
<!--
<filter-mapping>
<filter-name>filter1</filter-name>
<url-pattern>/ser2</url-pattern>
</filter-mapping>
-->
<servlet>
<servlet-name>ts1</servlet-name>
<servlet-class>com.santosh.servlets.TestServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>ts1</servlet-name>
<url-pattern>/ser1</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ts1</servlet-name>
<url-pattern>/ser2</url-pattern>
</servlet-mapping>
</web-app>



Servlet Filter

Filter

Introduction:
·         As we know that how to manage session (Session management, HttpSession) in web application.
·         And if we want to make sure that a resource( jsp, servlet, etc) is accessible only when user session is valid, we can achieve this by using servlet session attributes.
·         But if we have a huge number of servlets and jsps, then it will become hard to maintain because of redundant(repeated) code.
If we want to change the attribute name in future, we will have to change all the places where we have session authentication.

What is Servlet Filter?
It is an Interface which is predefined in javax.servlet.Filter interface
A Servlet filter is an object that can intercept(stops) HTTP requests targeted at your web application. 
A servlet filter can intercept requests both for servlets, JSP's, HTML files or other static content
By using the Servlet Filter class we can overcome the following problems:


Some common tasks that we can do with filters are:
·         Logging request parameters to log files.
·         Authentication and autherization of request for resources.
·         Formatting of request body or header before sending it to servlet.
Internationalization
·         Compressing the response data sent to the client.
Alter response by adding some cookies, header information etc.

Purpose of Servlet Filter

Intercept request from a client browser before it gets processed in the server
Intercept/manipulate response from server before it is sent to the client browser


Advantages of Servlet Filter

Servlet filter is pluggable
No dependency between filters
 




following diagram illustrates:



Servlets and filters both are unaware of each other and we can add or remove a filter just by editing web.xml.

We can have multiple filters for a single resource and we can create a chain of filters for a single resource in web.xml. We can create a Servlet Filter by implementing javax.servlet.Filter interface.
For more information http://docs.oracle.com/javaee/6/api/javax/servlet/Filter.html
Advantages of Filters:

  • Reusable code : that can transform the content of requests, responses, and header information from one format to another: Example: a web application that formats the data before it is presented to the client. And different clients require different formats such as Wireless Markup Language(WML), Excel Sheets, Portable Document Format(PDF) to do this we need of transformation of filtering in a Web application.
Work flow of Filter:
·         When the web container loads the filter class using the normal java class loading
·         This class may be loaded from a local file system, a remote file system, or other network services
·         If the web container fails to load the class, it terminates this initialization process.
·         After the filter class is loaded, the web container creates the object of Filter class. The Web container uses the no-argument constructor to create a new instance of the Filter class.
·         Once the Filter object is created, the web container initializes the Filter object by invoking init(0 and passing the FilterConfig object reference to this method.
·         FilterConfig object allows the Filter object to access name-value configured initialization parameters, the reference to the ServletContext interface for the Web Application, and other container specific details.
·         The Web Container creates one FilterConfig object per filter declaration in the deployment descriptor.
·         The init() reads the configuration data and initialize resources, then the Web container keeps the Filter object into active state that is it makes it available and ready to handle requests, Otherwise, if the filter fails to initialize, it throws the UnavailableException. If the init(0 of Filter interface throws an exception, the Web container does not put this object into the active state. That is it removes the object.
·         After deploying the web application or before the request is sent to the Web container to access a Web resource, the container locates the list of filters that must be applied to the Web resource.
·         When the container receives the request, it takes the first filter object from the list and calls its doFilter() method passing ServletRequest, ServletResponse and a reference of the FilterChain object that it uses.
·         The doFilter() method of a Filter performs preprocessing, such as examining the request’s headers, wrapping the request and / or response object passed into its doFilter() method with a customized implementation of ServletRequest, or HttpServletRequest and / or ServletResponse or HttpServletResponse respectively to modify request/response headers or data.
·         After performing all its preprocessing operations, if any, the filter may call doFilter() on FilterChain object passing in the request and response objects.
·         The doFilter() method of FilterChain is responsible to invoke the next entity in the chain.
·         The next entity may be another filter, or if the filter making the invocation is the last filter configured for this chain then the next entity is the target web resource.
·         Otherwise filter can block the request by not making the call to invoke the next entity, that is by not calling doFilter() on FilterChain object.
·         After doFilter() method invocation on theFilterChain object, filter can perform post processing operations.
·         The destroy() method is called either after all threads have completed their functionality or when thread’s timeout period elapses. This method detaches all resources such as memory and threads from filter instance.

<?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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
    <display-name>ServletFilter</display-name>
    <servlet>
        <servlet-name>HelloServlet</servlet-name>
        <servlet-class>com.tech2money.HelloServlet</servlet-class>

    </servlet>
    <servlet-mapping>

        <servlet-name>HelloServlet</servlet-name>
        <url-pattern>/HelloServlet</url-pattern>
    </servlet-mapping>
    <filter>
        <filter-name>HalloFilter</filter-name>

        <filter-class>com.tech2money.HalloFilter</filter-class>

    </filter>



    <filter-mapping>

        <filter-name>HalloFilter</filter-name>

        <url-pattern>/HelloServlet</url-pattern>

    </filter-mapping>


    <welcome-file-list>

        <welcome-file>index.jsp</welcome-file>

    </welcome-file-list>

</web-app>


Example of basic Servlet Filter class

package com.rajendra;
import javax.xml.crypto.dsig.spec.XPathType.Filter;
public class HalloFilter extends Filter {
/**
     * init() is called by the web container to indicate to a filter that it is being placed into service.

     * @param config

     * @throws ServletException

     */

    public void init(FilterConfig config) throws ServletException {

        // Get init parameter which is defined in the <init-param> tag in web.xml for filter definition

        String initParam = config.getInitParameter("init-Param");



        // Print the init parameter

        System.out.println("Init Param: " + initParam);

    }



    /**

     * doFilter() is called by the container each time a request/response pair is passed through the chain due to a

     * client request for a resource at the end of the chain.

     * @param request

     * @param response

     * @param chain

     * @throws java.io.IOException

     * @throws ServletException

     */

    public void doFilter(ServletRequest request, ServletResponse response,
30
            FilterChain chain) throws java.io.IOException, ServletException {



        // Get the IP address of client machine.

        String ipAddress = request.getRemoteAddr();



        // Log the IP address and current timestamp.

        System.out.println("IP " + ipAddress + ", Time "+ new Date().toString());



        // Pass request back down the next resource

        chain.doFilter(request, response);

    }



    /**

     * destroy() is called by the web container to indicate to a

     * filter that it is being taken out of service.

     */

    public void destroy() {

        /*

         * Called before the Filter instance is removed from service by the web

         * container

         */

    }

}