ADVANCED JAVA PROGRAMMING MODULE 1 NOTES



MODULE 1: Servlets:

What is a Server?

• A server is a computer that responds to requests from a client

• Typical requests: provide a web , upload or download a file, send email

• A server is also the software that responds to these requests; a client could be the browser or other software making these requests

• Typically, your little computer is the client, and someone else’s big computer is the server

• However, any computer can be a server

• It is not unusual to have server software and client software running on the same computer

• Ex: Apache Tomcat is a Server ⋄ Apache is a very popular server

o. 66% of the web sites on the Internet use Apache o Apache is:

▪ Full-featured and extensible

▪ Efficient

▪ Robust

▪ Secure

▪ Up to date with current standards

▪ Open source

▪ Free

What is Web Application Development?

• Web application development involves development of Dynamic HTML applications that can interact with database

• In the development of web based applications the interaction of Web application works on this way

|Browser | | Servlet | |Server |

| | | | | |

HTML

What Is a Servlet?

• A servlet is a small Java program that runs within a Web server.

• Servlets receive and respond to requests from Web clients, usually across HTTP, the Hyper Text Transfer Protocol.

• Servlet is an opposite of applet as a server-side applet.

• Applet is an application running on client while servlet is running on server.

• Servlets are server side components that provide a powerful mechanism for developing web applications.

• Using servlets we can create fast and efficient server side applications and can run it on any servlet enabled web server.

• Servlet runs entirely inside the JVM (Java Virtual Machine).

• Since the servlet runs on server side so it does not depend on browser compatibility.

“The Helper Application is nothing but a SERVLET”

[pic]

• The content of the dynamic web s need to be generated dynamically.

• In the early days of the Web, a server could dynamically construct a by creating a separate process to handle each client request.

• The process would open connections to one or more databases in order to obtain the necessary information.

• It communicated with the Web server via an interface known as the Common Gateway Interface (CGI).

Servlet Structure

A Simple JAVA Servlet

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class ServletDemo extends HttpServlet

{

public void doPost(HttpServletRequest req HttpServletResponse res) throws ServletException,IOException

{

res.setContentType(“text/html”)

PrintWriter out=res.getWriter();

out.println("“);

out.println("Java Servlet"); out.println("“);

out.println(“ My First Servlet program “);

out.println("");

}

}

• A java Servlet is a java class that reads request sent from a client and responds by sending information to the client.

• The java class must extend HttpServlet and override the Httpservlet’s doGet() or doPost() methods

• doGet() ⋄ used when request is sent using the METHOD=“GET” attribute of HTML

• doPost() ⋄ used when request is sent using the METHOD=“POST” attribute of HTML

• Both doGet() and doPost() requires two arguments

• The first argument is an HttpservletRequest object

• The secons argument is an HttpservletResponse object

• The HttpSevletRequest used to receive request from cleint.

• The HttpServletResponse is used to Respond to Client.

• (format of data response depends on client, ex: data given is in the form of a HTML or XML if the client is a browser)

• Both throws ServletExcetion and IOException

Request:

- Information that is sent from client to a server.

- Information means

• Who made the request

• What user-entered data is sent

• Which HTTP headers are sent

Response:

- Information that is sent to client from server

- Information means

• Text(html, plain) or Binary(image) data

• HTTP headers, cookies, etc

The Servlet API

[pic]

[pic]

javax.servlet-Interface

✓ The servlet interface declares methods that manage the servlet and its communications with clients.

✓ Servlet writers/developers provide some or all of these methods when developing a servlet.

✓ Some of the important INTERFACES are:

➢ Servlet

• The servlet interface is the central abstraction of the java servlet API. It defines the life cycle methods of a servlet.

• All the servlet implementations must implement it either directly or indirectly by extending a class which implements the servlet interface.

• The two classes in the servlet API that implement the servlet interface are GenericServlet and HttpServlet.

➢ ServletRequest

• ServletRequest object is used to obtain the client request information such as request parameter, contenttype and length, locale of client, request protocol etc

➢ ServletResponse

• The ServletRepsonse interface assists a servlet in sending a response to the client.

➢ ServletConfig

• The servlet container uses a ServletConfig object to pass initialization information to the servlet.

• ServletConfig object is mostr commonly used to read the initialization parameters.

➢ ServletContext

• ServletContext object is used to co0mmunbicate with the servlet container.

• There is only one ServletContext object per web application (JVM).

• This is initialized when the web application is started and destroyed only when the web application is being shut down.

➢ SingleThreadModel

• SingleThreadModel is a marker interface is used to ensure that servlet handle only one

request at a time.

javax.servlet- Classes

➢ GenericServlet

• The GenericServlet class implements the servlet and ServletConfig interfaces.

• It can be extended to develop our own p[rotocol based servlet.

➢ ServletConextEvent

• This is the event class for notifications about changes to the servlet context of a web application.

➢ ServletInputStream

• Provides an input stream for reading binary data from client request.

➢ ServletOutputStream

• Provides an output stream for sending binmary data to the client.

The Servlet Exception Classes

➢ ServletException

• javax.servlet defines two exceptions.

• The first is ServletException, which indicates that a servlet problem has occurred.

➢ UnavailableException

• UnavailableException, which extends ServletException. It indicates that a servlet is unavailable.

javax.servlet.http - Interfaces

➢ HttpServlet

➢ HttpServletRequest

• Extends the ServletRequest interface to provide request information for HTTP servlets

➢ HttpServletResponse

• Extends the ServletResponse interface to provide HTTP-specific functionality in sending a response.

➢ HttpSession

• Provides a way to identify a user across more than one request or visit to a Web site and to store information about that user.

javax.servlet.http – Classes

➢ HttpServlet

• Provides an abstract class to be subclassed to create an HTTP servlet suitable for a website.

➢ HttpServletRequestWrapper

• Provides a convenient implementation of the HttpServletRequest interface that can be subclassed by developers wishing to adopt the request to a servlet.

➢ HttpServletResponseWrapper

• Provides a convenient implementation of the HttpServletResponse interface that can be subclassed by developers wishing to adopt the response from a servlet.

➢ Cookies

• Creates a cookie.

Servlet Lifecycle

• The Servlet lifecycle is simple, there is only one main state – “Initialized”.

[pic]

• init( ), service( ), and destroy( ) are the three methods which are central to the life cycle of a servlet.

• They are implemented by every servlet and are invoked at specific times by the server.

Procedure:

• First, user enters URL, browser then generates an HTTP request for this URL, & this request is then sent to the appropriate server.

• Second, this HTTP request is received by web server, web server maps this request to a particular servlet.

• The servlet is dynamically retrieved & loaded into the address space of the server.

• Third, server invokes init( ) method of the servlet. This method is invoked only when the servlet is first loaded into memory.

• It is possible to pass initialization parameters to the servlet so it may configure itself.

• Fourth, the server invokes the service ( ) method of the servlet. This method is called to process the HTTP request. It may also formulate an HTTP response for the client.

• The service( ) method is called for each HTTP request.

• Finally, the server may decide to unload the servlet from its memory. The server calls the destroy( ) method to relinquish any resources such as file handles that are allocated for the servlet.

init()

init() method is called only once in the life time of the servlet.

Example: init() reading configuration parameters

1. In this example, we are actually setting up our own database connection by reading init parameter values T.

2. The init parameter values are configured in the web.xml deployment descriptor.

Public void init(ServletConfig config) throws ServletException {

super.init(config);

String driver=getinitParameter(“driver”);

String fURL= getinitParameter(“url”);

try{

openDBConnection(driver,Furl);

} catch(SQLException e)

{

e.printStackTrace();

}

}

Web.xml

chart

chartServlet

driver

com..RmijdbcDriver

url

jdbc:cloudscape:rmi:CloudScapeDB

service()

- The service() method is an abstract method in GenericServlet class which is then implemented in a subclass.

- HTTPServlet is a subclass that is already provided for the developers.

- The service() method implementation of the HTTPServlet class then dispatches the call to doxxx() methods depending on the HTTP request type.

[pic]

doGet and doPost methods of Servlet

• The default service() method in an HTTP servlet routes the request to another method based on the HTTP transfer method (POST, and GET).

• HTTP POST requests from HTML file are routed to the doPost() method, HTTP GET requests are routed to the doGet() method.

• Most operations that involve forms use either a GET or a POST operation, so for most servlets override either doGet() or doPost().

• Implementing both methods is a good practice to provide both input types or pass the request object to a central processing method.

Example Program using HTTP doGet() method:

• The doGet() method is the method inside a servlet that gets called every time a request from a html or jsp is submitted.

• The control first reaches the doGet() method of the servlet and then the servlet decides what functionality to invoke based on the submit request. The get method called when the type of submission is "GET".

• doGet is used when there is are requirement of sending data appended to a query string in the URL.

• The doGet model the GET method of Http and it is used to retrieve the info on the client from some server as a request to it.

• The doGet cannot be used to send too much info appended as a query stream. GET puts the form values into the URL string.

• GET is limited to about 256 characters (usually a browser limitation) and creates really ugly URLs.

package ServletPrograms;

import java.io.*;

import javax.servlet.ServletException;

import javax.servlet.http*;

public class doGetDemo extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException

{

PrintWriter out=response.getWriter();

out.println("");

out.println("user password");

out.println("");

String username=request.getParameter("username");

String password=request.getParameter("password");

out.println("username = "+username);

out.println("");

out.println("password = "+password);

out.println("");

out.close();

}

}

Example Program using HTTP doPost() method:

• The doPost() method is the method inside a servlet that gets called every time a requests from a HTML or jsp calls the servlet using "POST" method.

• doPost allows you to have extremely dense forms and pass that to the server without clutter or limitation in size. e.g. you obviously can't send a file from the client to the server via doGet. doPost has no limit on the amount of data you can send and because the data does not show up on the URL you can send passwords.

• But this does not mean that POST is truly secure. It is more secure in comparison to doGet method.

package ServletPrograms;

import java.io.*;

import javax.servlet.ServletException;

import javax.servlet.http*;

public class doPostDemo extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException,IOException

{

PrintWriter out=response.getWriter();

out.println("");

out.println("user password");

out.println("");

String username=request.getParameter("username");

String password=request.getParameter("password");

out.println("username = "+username);

out.println("");

out.println("password = "+password);

out.println("");

out.close();

}}

Difference between HTTP doGet and HTTP doPost methods of Servlet

|Difference Type |GET (doGet()) |POST (doPost()) |

| | | |

| | | |

|HTTP Request |The request contains only the |Along with request line and header it |

| |request line and HTTP header. |also contains HTTP body. |

| | | |

|URL Pattern |Query string or form data is |Form name-value pairs are sent in the |

| |simply appended to the URL as |body of the request, not in the URL |

| |name-value pairs. |itself. |

| | | |

|Parameter passing |The form elements are passed to |The form elements are passed in the |

| |the server by appending at the |body of the HTTP request. |

| |end of the URL. | |

| | | |

|Size |The parameter data is limited |Can send huge amount of data to the |

| |(the limit depends on the |server. |

| |container normally 4kb) | |

| | | |

|Idempotency |GET is Idempotent(can be |POST is not idempotent(warns if applied |

| |applied multiple times without |multiple times without changing the |

| |changing the result) |result) |

| | | |

|Usage |Generally used to fetch some |Generally used to process the sent data. |

| |information from the host. | |

| | | |

|Security |Not Safe - A person standing |Safe - No one will be able to view what |

| |over your shoulder can view |data is getting submitted (Data hidden |

| |your userid/pwd if submitted |from users.) |

| |via Get (Users can see data in | |

| |address bar.) | |

| | | |

|Data Format |Supports ASCII. |Supports ASCII + Binary. |

| | | |

Reading Servlet Parameters

• The ServletRequest class includes methods that allow you to read the names and values of parameters that are included in a client request.

• The example contains two files. A Web is defined in PostParameters.htm and a servlet is defined in PostParametersServlet.java.

Handling Client Request form data:

- Whenever we want to send an input to a servlet that input must be passed through html form.

- An html form is nothing but various controls are inherited to develop an application.

- Every form will accept client data and it must send to a servlet which resides in server side.

- Since html is a static language which cannot validate the client data. Hence, in real time applications client data will be accepted with the help of html tags by developing form and every form must call a servlet.

Steps for Developing form:

1. Use … tag.\

2. To develop various control through … tag and all tag must be enclosed with … tag.

3. Every form must call a servlet by using the following:

….



Example:

Login Information

Login Information

UserName:

Password:

Handling HTML Data in Servlet:

In order to handle or obtain the data html form in a servlet, we have the following methods which is present in HttpServletRequest.

There are four types of handling data:

1. getParameter

2. getParameterValues

3. getParameterNames

4. getReader or getInputStream

getParameter: You call request.getParameter to get the value of a form parameter.

getParameterValues: . You can also call request.getParameterValues if the parameter appears more than once,

getParameterNames: you can call request.getParameterNames if you want a complete list of all parameters in the current request.

getReader or getInputStream: you need to read the raw request data and parse it yourself, call getReader or getInputStream.

Example:

String Username =req.getParameter(“username”);

String Password=req.getParameter(“password”);

req is an object of HttpServletRequest

Example for getParameter:

HTML:

Login Information

Login Information

UserName:

Password:

Servlet:

package ServletPrograms;

import java.io.*;

import javax.servlet.ServletException;

import javax.servlet.http*;

public class getParameterDemo extends HttpServlet {

public void doPost(HttpServletRequest req, HttpServletResponse res)throws ServletException,IOException

{

PrintWriter out=res.getWriter();

out.println("");

out.println("user password");

out.println("");

String username=req.getParameter("username");

String password=req.getParameter("password");

out.println("username = "+username);

out.println("");

out.println("password = "+password);

out.println("");

out.close();

}

}

Example for getParameterValues

HTML:

Login Information

Login Information

Habits:

Reading

Movies

Writing

Singing

Servlet:

package ServletPrograms;

import java.io.*;

import javax.servlet.ServletException;

import javax.servlet.http*;

public class getparametervaluesdemo extends HttpServlet {

public void doPost(HttpServletRequest req, HttpServletResponse res)throws ServletException,IOException

{

PrintWriter out=res.getWriter();

res.setContentType(“text/html”);

String[] values=req.getParameterValues(“habits”);

out.println(“Selected Values…”);

for(int i=0;i ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download