Thursday 10 April 2014

CONCEPTS OF SERVLETS

 Creating a servlet program
first servlet program by using Note pad (without using IDE)
(http://raj-servlets.blogspot.in/2013/08/first-servlet-program-by-using-note-pad.html)
How servlet intercepts HTTP requests, and the method it runs
Understanding the role of servlets
Evaluating servlets vs. other technologies
Understanding the role of JSP
Configuring the server
Configuring your 
development environment
Testing the 
server setup
Servlet Basics

The basic structure of servlets
A simple servlet that generates plain text
A servlet that generates HTML
Servlets and packages
Some utilities that help build HTML
The servlet life cycle
Servlet debugging strategies
Handling the Client Request: 
Form Data

The role of form data
Creating and submitting HTML forms
Reading individual request parameters
Reading the entire set of request parameters
Handling missing and malformed data
Dealing with incomplete form submissions
Filtering special characters out of the request parameters
Handling the Client Request: HTTP Request Headers

Reading HTTP request headers
Building a table of all the request headers
Understanding the various request headers
Reducing download times by compressing pages
Differentiating among types of browsers
Generating the Server Response: HTTP Status Codes

Format of the HTTP response
How to set status codes
What the status codes are good for
Shortcut methods for redirection and error pages
A servlet that redirects users to browser-specific pages
A front end to various search engines
Generating the Server Response: HTTP Response Headers

Format of the HTTP response
Setting response headers
Understanding what response headers are good for
Building Excel 
spread sheets
Generating JPEG images dynamically
Sending incremental updates to the browser
Handling Cookies

Understanding the benefits and drawbacks of cookies
Sending outgoing cookies
Receiving incoming cookies
Tracking repeat visitors
Specifying cookie attributes
Differentiating between session cookies and persistent cookies
Simplifying cookie usage with utility classes
Modifying cookie values
Remembering user preferences
Session Tracking

Implementing session tracking from scratch
Using basic session tracking
Understanding the session-tracking API
Differentiating between server and browser sessions
Encoding URLs
Storing immutable objects vs. storing mutable objects
Tracking 
user access counts
Accumulating user purchases
Implementing a shopping cart
Building an 
online store

Servlet internal question paper for web technologies(http://raj-servlets.blogspot.in/2013/04/servlet-internal-question-paper-for-web.html)
Question paper for servlets and jsp for WEB TECHNOLOGIES(http://raj-servlets.blogspot.in/2014/04/question-paper-for-servlets-and-jsp-for.html)


Question paper for servlets and jsp for WEB TECHNOLOGIES

Subject: WT
Class     : III yr II Sem CSE-C
PART-A
Multiple choice:

  1. Servlets are used at?                                                                                      [           ]
a. Broswer side
b. server side
c. Both
d. None
  1. Servlet mapping defines?                                      [A         ]
a.  an association between a URL pattern and a servlet
b.  an association between a URL pattern and a request page
c.  an association between a URL pattern and a response page
d.  All of the above

  1. How many jdbc drivers are there       [           ]
a. one  b. three           c. four              d. five

  1. To execute jdbc program we need                                         [           ]
a. jdbc software          b. jdbc jar file c. mysql software        d. oracle software

  1. Following is not the JSP implicit object                           [        ]
a. String            b. config        c. out            d. request.

Fill in the blanks:
1.       JSP stands for ___________________________.
2.      Jdbc is used to ________________________.
3.      _____________________methods are the Servlet lifecycle methods.
  1. _______________are used to do session tracking .
  2. Class.forName() method is used for ___________

PART-B
Answer any three:
1.     What are JSP directives ? Write any JSP program for login screen?
  1. Explain about the lifecycle of servlets? Illustrate with a suitable example for servlets ?(Write down the steps to write servlet programs)
  2. What are the advantages and characteristics of JAVA BEANS?
  3. Develop a web application for registration for email login details using jsp and jdbc?
  4. Explain about the session tracking? Write a example program for Cookies
  5. What are the steps are involved while writing the jdbc program? Illustrate with a jdbc program to store data into the database




Tuesday 8 April 2014

Context Initialization Parameters

Context Initialization Parameters

  • So far we discussed, Servlet Container supports to store startup and configuration information for a Servlet as initialization parameters (init parameters).
  • init parameters are configured specific to the Servlet configured in the deployment descriptor file, means these data can be retrieved only one servlet
  • But I want to configure data that has to be retrieved into all or more than one servlet.
  • For example my web application contains two servlets , login and registration, and you want the Driver class name and the JDBC URL of both Servlets to establish a connection, for this situation we can implement by using the context initialization parameters (Context init parameters), which are provided under Servlet specification.
This type of parameters are accessible to all the web components in this application.

How to declare the context init parameters?

The following tag is used as a direct child of <web-app> in web.xml to do this:


Syntax:

 <context-param>
     <param-name>parameter name</param-name>
     <param-value>parameter value</param-value>
</context-param>


  • this is not in side servlet, this is out side servlet
  • Annotations style is not supported for configuring this requirement.




Monday 7 October 2013

My first servlet application (a)

Creating servlet programming:  using Command Prompt


set up:
Prerequisite:
1. Download any server (Ex: Tomcat, Weblogic,..)
    How to download Tomcat Server
2. Download the jar files and configure
    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

  1. install jdk from http://java.sun.com
  2. install Apache Tomcat from htt://tomcat.apache.org
  3. Eclipse IDE for java EE Developers
  4. Set up the following environment variables
(a) TOMCAT Home: Directory where Tomcat is installed (e.g: c:\Tomcat)
  1. (b) JAVA_Home: Directory where Java is installed (e.g: c:\Java\jdk1.6.0_06)
  2. (c) Add Java_Home \bin directory to CLASSPATH (E.G: c:\java\jdk1.6.0_06\bin)
  3. Put servlet-api.jar in classpath
My first servlet apps

  1. servlet class – business logic
  2. web.xml - configuration file (every web app should follow web.xml file, this is the place where the first server check when the request comes from the client . So when the request comes from the client server goes to this web.xml configuration file checks for that particular request tries to see the match if it finds the match
  1. web.xml - configuration file (every web app should follow web.xml file, this is the place where the server first check when the request comes from the client . So when the request comes from the client server goes to this web.xml configuration file checks for that particular request tries to see the match if it finds the match
  1. web. Jar file :
we have the servlet class , we have the web.xml what you need to do? In order to deploy your application into webserver is : build a jar file out of your classes , html configuration file all those things. So we need to build a jar, including the servlet class and web.xml
  1. Deploy:
  • Once you build a jar, you deploy into the web server.
  1. Execute:
  • Once you deploy the application into the web server
  • application is ready and you can simply go ahead and enter the url and execute your web application 

Now lets have a look in detail

1. first thing is writing your servlet class.

So first servlet application is I'm simply going to print text “hello World” on the screen so when the user enter the url result of that text would be displayed on the web page

  • I want to make it first application so simple because I would like to do concentrate more on the other things like how do you get all the pieces together and how do you build your jar files , how do you deploy it and I would like to concentrate more on how the code flows between different methods of the class and which order so all those different things about the servlet and web application on the whole so thats the reason I could not put much business logic.
    Just see I have written this code for the servlet and the web.xml file ahead .

    package com.rajservlet.servlets;

    import java.io.IOException;
    import java.io.PrintWriter;
    //these are a part of servlet api jar files, these are the servlet packages.
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;

    public class HelloWorldServlet extends HttpServlet // implements javax.servlet.Servlet //no need this interface now
    {
    public HelloWorldServlet()
    {
    super();
    System.out.println(“in HelloWorld Constructor”);
    }
    public void init()
    {
     System.out.println(“In Hello World Init”);
    }
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
      System.out.println(“In Hellow World service()”);
      If(“GET”.equalsIgnoreCase(request.getMethod())
      {
        doGet(request, response);
      }
      else if(“POST”, equalsIgnoreCase(request.getMethod()))
      {
        doPost(request, response);
      }
     }

    Protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
      System.out.println(“in HelloWordl doGet”);
    }
     Response.setContentType(“text/html”);
     PrintWriter out=response.getWriter();
      out.println(“<html>”);
      out.pritnln(“<body>”);
      out.println(“hello World”);
      out.println(“</body>”);
      out.println(“</html>”);
     }
     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
     System.out.println(“In Hello World doPost()”);
     }
    This is servlet code my servlet is in my package called com.rajservlet.servlet package
  • This is our first “hello world “ servlet,
    ·         My servlet in the package called “com.rajservlet.servlets” package
    ·         We know that in order to write a servlet we need to extend HttpServlet class since we have already imported
    ·         implements javax.servlet.Servlet //no need this interface now: bcoz we know that the HttpServlet extends Generic servlet which inturn implements the Servlet interface .
    ·         So you are Hello World servlet will indirectly be implementing the Servlet interface so we do not write explicitly to implements servlets there
    ·         So once I do the “extends” HttpServlet on the class my class (ie: HelloWorldServlet) has got some features now and those special features are nothing but servlet features or servlet behavior
    ·         I have written all the call back methods in this class during the session init() method, doGet(), doPost(), destroy().
    ·         We have discussed earlier that we don’t need constructor to be declared in a servlet , so practically in real time we don’t put in a constructor  in your servlet because you will not be do anything in the constructor as well. All the initialization code will be in the init() method and jvm will put the default constructor in your servlet class so I simply put “System.out.println() is there in the constructor .
    ·         Next the init() method , this is the place where all your initialization takes place so if you have to perform initialization like getting connection to the database or any other stuff you want to perform in a servlet class , you know that for every request comes in the servlet , the service() method is called which is in turn calles doGet() or doPost() method but the init() method is only calls once when the servlet is loaded so only one time initialization stuff you put in the init() method

    ·         Next service(HttpServletRequest request, HttpServletResponse response) method  it takes the parameters  HttpServletRequest request and HttpServletResponse response throws servlet exception and IOException

    ·         Here one thing please make a note down when do you develop your servlet application in real time  you do not write the service() method as well  in fact you take the default implementation provided by the HttpServlet.
    ·         Again I just put here this service()method so that you will know the flow and when this method is called  and I just tried to emulate (follow) logic which could have been written in the HttpServlet so the HttpServlet class has similar logic but apart from this there will be a lot of other code as of now at this point of time I would …doGet() and doPost() because that is the place I am going to write my business logic so I simply capture the type of method passed by the user so I used request.getMethod()to determine what type of the request the user has sent, if the type is GET, then I call the doGet() method  which passes request and response objects .
    ·         If the type is POST, then I simply call the doPost() method passing the request and response objects.
    ·         So only thing is this service() method is going to do is taking the request, check the type of request, if it is “GET” call the doGet() method , if the type of request is “POST” , call the doPost() method.
    ·         Because it is first call we do not provide any method type it take the GET by default because there  is most specific method provided the default is GET so my doGet() method should be called now so that is the reason I put all the business logic in the doGet() method which again this doGet() method again take the HttpRequest and HttpResponse the parameters and I simply give a print statements here that is “In Hello World in doGet()”
    ·         One thing setContentType() , means setting the content type is to text or html so this is going to tell the client that the type of response I’m sending back to the client is of type html, if you would have been sending pdf document to the client , simply set “application/pdf”. I sent this content type to the response sent back to the client .
    Here I’ m creating PrintWriter object will be displayed on my servlet application.

HelloWorld servlet program

YOu may like the following posts:

Wednesday 4 September 2013

URL Rewriting

Session Management -URL Rewriting

Sessions-URL Rewriting


  • so for we have seen one of maintaining the session.
  • second way is URL rewriting, so what does it mean
  • client basically can disable cookies so client have the ability to disable cookies on their computer. So client can say I do not trust anyone and I do not want to accept any cookies from any of the websites
  • So it disables cookies, so server will not able to send cookie to the client even though the server is sending a cookie that cookie will not store on the client machine. So how can session can maintained in that scenario. Answer to that is URL Retwriting.
  • In the case of URL Rewriting what happens is "JSESSIONID" which earlier cookie was sent in a cookie, now will be appended to the URL which is sent to the client
  • so whatever URL the server sent back to the client along with the URL the session id is also appended (example:URL + ;jsessionid=1234567).
  • Similarly from the client side whenever the second request comes in the client appends the URL again (Example: GET/Metavante;jsessionid=OAAB) to the request which the server has sent it previously

So in this way URL rewriting the client and server can maintain the session

Q: What do you go for ? Do you go for URL Rewriting? Do you go for Cookies? What is the Best Mechanism to maintain the session?
Ans:
For the first time server sends response back to the client, it employes both methods: It sends the Cookie and also sends the JSESSIONID to the URL and respose back to the client. The server really doesnt know the whether the client has disable or enable cookies thus it does the both things simultaneously. Now if the client has not disable to the cookies the client would have sent back a cookie in the next request and then the server would have known the "Ok, server seems to be "not disable the cookies" so let me continue using cookies now. So for request there on the server will only sends cookies . But now for example say "client has disabled cookies ! so server would not have sent back a cookie in the subsequent request, obviously server would have appended the JSESSIONID to the URL  and send back in the next request. Now when the server sees that there is no cookie, there is only jsessionid is appended to the url, it knows that this client has disabled cookie so then for the subsequent requests from there on it only sends the URL rewrting methods for maintianing the session. So basically this is how the session is maintained across the multiple requests.

Maintaining the sessions: 3rd Way is Hidden form parameters

This is using JSP'S.