abhishek singh. web application: a web application is an application accessible from the web. a web...

74
Abhishek Singh

Upload: marcia-arnold

Post on 23-Dec-2015

222 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

Abhishek Singh

Page 2: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

Web Application:• A web application is an application accessible from the web. A web

application is composed of web components like Servlet, JSP, Filter etc. and other components such as HTML. The web components typically execute in Web Server and respond to HTTP request.

CGI(Commmon Gateway Interface) CGI technology enables the web server to call an external program and pass HTTP request information to the external program to process the request.For each request, it starts a new process.

Page 3: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

Disadvantages of CGI

• There are many problems in CGI technology:– If number of clients increases, it takes more time for

sending response.– For each request, it starts a process and Web server is

limited to start processes.– It uses platform dependent language e.g. C, C++, perl.

Page 4: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

What is a servlet?• A servlet is a Java technology based web component, managed by a container,

that generates dynamic content.• A servlet can be considered as a tiny Java program which processes user request

and generates dynamic content.• There are many other alternatives like php, asp .net or CGI, for developing

dynamic web sites. Benefit of using servlets over other technologies is servlets are developed in Java, so it comes with all benefits of Java language and it is platform independent.

• Following are the some advantages of using servlets.

(1) They are generally much faster than CGI scripts. (2) They use a standard API that is supported by many web servers.

(3) They have all the advantages of the Java programming language,

including ease of development and platform independence. (4) They can access the large set of APIs available for

the Java platform

Page 5: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

What is a Servlet Container?

• Servlet container (also known as servlet engine) is a runtime environment, which implements servlet API and manages life cycle of servlet components.Container is responsible for instantiating, invoking, and destroying servlet components. One example of container is Apache Tomcat which is an open source container.

Page 6: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

Advantage of Servlet• There are many advantages of Servlet over CGI. The web container creates threads for

handling the multiple requests to the servlet. Threads have a lot of benefits over the Processes such as they share a common memory area, lighweight, cost of communication between the threads are low. The basic benefits of servlet are as follows:– 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 no need to worry about memory leak, garbage collection

etc.– Secure: because it uses java language..

Page 7: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

Servlet Terminology• There are some key points that must be known by the

servlet programmer like server, container, get request, post request etc. Let's first discuss these points before starting the servlet technology.– The basic terminology used in servlet are given below:– HTTP– HTTP Request Types– Difference between Get and Post method– Container– Server and Difference between web server and application server– Content Type– Introduction of XML– Deployment

Page 8: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

• HTTP (Hyper Text Transfer Protocol)– Http is the protocol that allows web servers and browsers to exchange data

over the web.– It is a request response protocol.– Http uses reliable TCP connections bydefault on TCP port 80.– It is stateless means each request is considered as the new request. In

other words, server doesn't recognize the user bydefault.

Page 9: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

Http Request MethodsHTTP Request Description

GET Asks to get the resource at the requested URL.

POST Asks the server to accept the body info attached. It is like GET request with extra info sent with the request.

HEAD Asks for only the header part of whatever a GET would return. Just like GET but with no body.

TRACE Asks for the loopback of the request message, for testing or troubleshooting.

PUT Says to put the enclosed info (the body) at the requested URL.

DELETE Says to delete the resource at the requested URL.

OPTIONS Asks for a list of the HTTP methods to which the thing at the request URL can respond

Page 10: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

What is the difference between Get and Post?

GET POST

1) In case of Get request, only limited amount of data can be sent because data is sent in header.

In case of post request, large amount of data can be sent because data is sent in body.

2) Get request is not secured because data is exposed in URL bar.

Post request is secured because data is not exposed in URL bar.

3) Get request can be bookmarked Post request cannot be bookmarked

4) Get request is idempotent. It means second request will be ignored until response of first request is delivered.

Post request is non-idempotent

5) Get request is more efficient and used more than Post

Post request is less efficient and used less than get.

Page 11: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

Anatomy of Get Request• As we know that data is sent in request header in

case of get request. It is the default request type. Let's see what information's are sent to the server.

Page 12: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

Anatomy of Post Request• As we know, in case of post request original data is

sent in message body. Let's see how information's are passed to the server in case of post request.

Page 13: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

• Servlet can be described in many ways, depending on the context.– Servlet is a technology i.e. used to create web application.– Servlet is an API that provides many interfaces and classes including

documentations.– Servlet is an interface that must be implemented for creating any servlet.– Servlet is a class that extend the capabilities of the servers and respond to

the incoming request. It can respond to any type of requests.– Servlet is a web component that is deployed on the server to create dynamic

web page.

Page 14: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

What is Servlet API • Servlet API contains predefined Interface &

helper classes. Implementation of some interface is provided by application developer and implementation of rest of the interfaces is provided by Server vendor. – javax.servlet & its sub packages contain classes and

interface of servlet API.– At the core of servlet API is an interface named

Servlet. This interface provides life cycle method of servlet (Program).Life cycle methods are predefined methods which are invoked by run time environment.

Page 15: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

Generic Servlet & HTTP Servlet

GenericServlet

service ( )Server

Client

HTTPServlet

service ( )HTTP Server

Browser

request

response

doGet ( )

doPost( )

request

response

15

Page 16: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

Interface javax.servlet.Servlet

• The Servlet interface defines methods – to initialize a servlet– to receive and respond to client requests – to destroy a servlet and its resources– to get any startup information– to return basic information about itself, such as its author,

version and copyright.

• Developers need to directly implement this interface only if their servlets cannot (or choose not to) inherit from GenericServlet or HttpServlet.

Life Cycle

Methods

16

Page 17: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

• void init(ServletConfig config) – Initializes the servlet.

• void service(ServletRequest req, ServletResponse res) – Carries out a single request from the client.

• void destroy()– Cleans up whatever resources are being held (e.g., memory, file

handles, threads) and makes sure that any persistent state is synchronized with the servlet's current in-memory state.

• ServletConfig getServletConfig() – Returns a servlet config object, which contains any initialization

parameters and startup configuration for this servlet. • String getServletInfo()

– Returns a string containing information about the servlet, such as its author, version, and copyright.

GenericServlet - Methods

17

Page 18: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

Initializationinit()

Serviceservice()

doGet()doPost()

doDelete()doHead()doTrace()

doOptions()

Destructiondestroy()

Concurrent Threadsof Execution

Servlet Life Cycle

18

Page 19: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

HttpServlet - Methods

• void doGet (HttpServletRequest request, HttpServletResponse response)–handles GET requests• void doPost (HttpServletRequest request, HttpServletResponse response)–handles POST requests• void doPut (HttpServletRequest request, HttpServletResponse response)–handles PUT requests• void doDelete (HttpServletRequest request, HttpServletResponse response)– handles DELETE requests

19

Page 20: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

Servlet Request Objects

• provides client request information to a servlet. • the servlet container creates a servlet request object and

passes it as an argument to the servlet's service method. • the ServletRequest interface define methods to retrieve data

sent as client request:– parameter name and values– attributes– input stream

• HTTPServletRequest extends the ServletRequest interface to provide request information for HTTP servlets

20

Page 21: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

HttpServletResponse - Methods

java.io.PrintWriter getWriter()Returns a PrintWriter object that can sendcharacter text to the client

void setContentType (java.lang.String type)

Sets the content type of the response being sent to the client. The content type may include the type of character encoding used, for example,

text/html; charset=ISO-8859-4 int getBufferSize()

Returns the actual buffer size used for the response

21

Page 22: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

Life Cycle method of a servlet interface --: init()-: this method is invoked only once just after a servlet object is

created, it is used by application programmer to define initialization logic of a servlet. This method like as constructor. ---- -public void init (ServletConfig config) This method is used by server to provide reference of ServletConfig object to the servlet. ServletConfig is an interface of Servlet API, implementation of this interface provided by server vendors.

service ()-: this method is invoked each time request is received for a servlet. It is used by application programmer to defining request

processing logic. – public void service(ServletRequest request ServletResponse response) throws

ServletException,IOException In this method references of object of type servlet Request & servlet -Response are provided by server. Both of these are interfaces, implementation of these interfaces is provided by server vendor. These objects are used to Transfer data b/w server & servlet.

destroy()-: This method is invoked only once just before the servlet is unloaded. public void destroy(); It is used by application programmer for performing cleanup operations.

Page 23: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,
Page 24: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

Description of figure---: 1.2-: ServletConfig object is created for the servlet. 1.4 & 3.1-: Servlet request object are created and request data is

stored in it. 1.5 & 3.2-: Servlet response object is created to receive result of

request processing from the servlet. 1.6 & 3.3-: Request processing thread is started. 1.7 & 3.4-: service method is invoked by the request processing

thread. 1.8 & 3.5-: request data is read by the servlet during request

processing logic. 1.9 & 3.6-: dynamically generated contents are stored by the servlet

in servlet response object. 2.0 & 3.7-: after the complication of service method server reads

the contents of servlet response object. 2.1 & 3.8-: Contents of servlet response are sent as response to the

client.

Page 25: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

• After Some time limit Server invoke destroy() method on servlet. In order to define servlet, implementation of Servlet interface needs to be provided. To facilitate indirect implementation Servlet API provide a helper class named GenericServlet. This class implement Servlet interface and define all the method except service method. It is used as super class of user defines servlet.

• NOTE-:If a class implements an interface and not define all method of this that class must be abstract class.

Page 26: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

• There are given five steps to create a servlet example. These stepse are required for all the servers.

• The servlet example can be created by three ways:– By implementing Servlet interface,– By inheriting GenericServlet class, (or)– By inheriting HttpServlet class

• The mostly used approach is by extending HttpServlet because it provides http request specific method such as – doGet(), – doPost(), – doHead() etc.

• Here, we are going to use apache tomcat server in this example. The steps are as follows:– Create a directory structure– Create a Servlet– Compile the Servlet– Create a deployment descriptor– Start the server and deploy the application

Page 27: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

• Servlet interface and it implementation provided by GenericServlet are protocol neutral. Usually request is submitted to a servlet using Http protocol. Http protocol support following 8 type of request--:

Page 28: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

Create a directory structures:• The directory structure defines that where to put the different

types of files so that web container may get the information and respond to the client. The Sun Microsystem defines a unique standard to be followed by all the server vendors. Let's see the directory structure that must be followed to create the servlet.

the servlet class file must be in the classes folder. The web.xml file must be under the WEB-INF folder.

Page 29: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

HTTP Redirects

• Page redirection is generally used when a document moves to a new location and we need to send the client to this new location or may be because of load balancing , or for simple randomization.

• The simplest way of redirecting a request to another page is using method sendRedirect() of response object. Following is the sig nature of this method:

public void HttpServletResponse.sendRedirect(String location) throws IOException

Page 30: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

• T his method sends back the response to the browser along with the status code and new pag e location. You can also use setStatus() and setHeader() methods tog ether to achieve the same:– ....– String site = "http://www.newpage.com" ;– response.setStatus(response.SC_MOVED_TEMPORARILY

);– response.setHeader("Location", site);– ....

Page 31: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

Example• import java.io.*;• import java.sql.Date;• import java.util.*;• import javax.servlet.*;• import javax.servlet.http.*;• public class PageRedirect extends

HttpServlet• {• public void

doGet(HttpServletRequest request,

HttpServletResponse response) throws ServletException,

IOException

• {• // Set response content type• response.setContentType("text/

html");• // New location to be redirected• String site = new

String("http://www.facebook.com");

• response.setStatus(response.SC_MOVED_TEMPORARILY);

• response.setHeader("Location", site);

• }• }

Page 32: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

Web.xml• ....• <servlet>• <servlet-name>PageRedirect</servlet-name>• <servlet-class>PageRedirect</servlet-class>• </servlet>• <servlet-mapping>• <servlet-name>PageRedirect</servlet-name>• <url-pattern>/PageRedirect</url-pattern>• <welcome-file-list>• <welcome-file>PageRedirect</welcome-file>• </welcome-file-list>

• </servlet-mapping>

Page 33: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

HTTP Servlet Overview

Servlets are modules that extend request/response-oriented servers, such as Java-enabled web servers. For example, a servlet might be responsible for taking data in an HTML order-entry form and applying the business logic used to update a company's order database.

Page 34: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

Java Servlets

• Java’s answer to CGI + ASP• A little more general than CGI/ASP, etc.• Work with all major web servers• Need web server servlet engine• Need servlet development kit

Page 35: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

What’s good about them?

• Concurrency – A servlet can handle multiple request. (Synchronize)

• Forward Request

• Portability

• Efficiency

• Power

• Safety

Page 36: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

Types of Servlet

• Generic Servlet – javax.servlet (package)– extends javax.servlet.Servlet – service method

• Http Servlet– javax.servlet.http (package)– extends javax.servlet.HttpServlet– doget(), doPost()….

Page 37: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

Types of servlets (cont..)

• Generic servlet– service(Request, Response) throws

ServletException, IOException• HttpServlet

– doGet(HttpServletRequest req, HttpServletResponse res)

Page 38: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

Basic Servlet exampleimport java.io.*;import javax.servlet.*;import javax.servlet.http.*;

public class Test extends HttpServlet{ public void doGet(HttpServletRequest in,

HttpServletResponse out) throws ServletException, IOException {

out.setContentType(“text/html”); PrintWriter p = res.getWriter(); p.println(“<H1>HELLO, WORLD!</H1>”); }}

Page 39: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

POST Exampleimport java.io.*;import javax.servlet.*;import javax.servlet.http.*;

public class Test extends HttpServlet{ public void doGet(HttpServletRequest req,

HttpServletResponse res) throws ServletException, IOException {

res.setContentType(“text/html”); PrintWriter out = res.getWriter();

Page 40: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

String pin = req.getParameter(“to”); String orig = req.getParameter(“from”);

out.println(“Sending page to “ + pin + “ from “ + orig); // Actually send the page.

} public void doPost(HttpServletRequest in, HttpServletResponse out) throws ServletException, IOException {

doGet(in, out); }}

Page 41: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

Counter exampleimport ….;public class SimpleCounter extends HttpServlet {int count =0 ;public void doGet( …….) throws …. {

res.setContentType(“text/plain”);PrintWriter out = res.getWriter();

count ++; out.println(“Hit number: “+count); }}// end of class

Page 42: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

• What is the problem with the above example??

Page 43: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

Synchonized counterimport ….;public class SimpleCounter extends HttpServlet {int count =0 ;public void doGet( …….) throws …. {

res.setContentType(“text/plain”);PrintWriter out = res.getWriter();

synchonize(this) { count ++; out.println(“Hit number: “+count); } }}// end of class

Page 44: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

Servlet Life Cycle

• Initialize using init method• Servlet handles requests/clients• Server removes the servlet using destroy

method

Page 45: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

Servlets vs. Applets

• Similarities– Neither has a main()– Both have init() and destroy()– Both are part of a larger application made for the

web

Page 46: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

Servlets vs. Applets (cont..)

• Dissimilarity– Applets run on the client (browser) while servlets run on

the HTTP server– Applets are usually “crippled” in functionality, having

limited ability to look at the local file system, establish network connections, etc.

– Servlets are generally built to handle multiple clients at once, whereas applets generally service one client at a time.

– Servlets handle HTTP request – …

Page 47: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

Servlet Session I: Cookie API

Page 48: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

The Potential of Cookies

• Idea– Servlet sends a simple name and value to client.– Client returns same name and value when it

connects to same site (or same domain, depending on cookie settings).

• Typical Uses of Cookies– Identifying a user during an e-commerce session– Avoiding username and password– Customizing a site– Focusing advertising

Page 49: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

Cookies and Focused Advertising

Page 50: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

Creating Cookies

Page 51: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

Creating Cookies

Three steps to creating a new cookie:1) Create a new Cookie Object

Cookie cookie = new Cookie (name, value);

2) Set any cookie attributes Cookie.setMaxAge (60);

3) Add your cookie to the response object: Response.addCookie (cookie)

We will examine each of these steps in detail.

Page 52: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

Sending Cookies to the Client• Create a Cookie object.

– Call the Cookie constructor with a cookie name and a cookie value, both of which are strings.Cookie c = new Cookie("userID", "a1234");

• Set the maximum age. – To tell browser to store cookie on disk instead of just in

memory, use setMaxAge (argument is in seconds)c.setMaxAge(60*60*24*7); // One week

• Place the Cookie into the HTTP response – Use response.addCookie. – If you forget this step, no cookie is sent to the browser!

response.addCookie(c);

Page 53: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

1. Cookie Constructor You create a new cookie by calling the Cookie

constructor and specifying: Name Value

Example: Cookie cookie = new Cookie (“school”, “NYU”);

Neither the name nor the value should contain whitespace or any of the following characters: [ ] ( ) = , “ / ? @ ;

Page 54: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

2. Set Cookie Attributes

Before adding your cookie to the Response object, you can set any of its attributes.

Attributes include: Name/Value Domain Maximum Age Path Version

Page 55: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

Cookie Name

You rarely call setName() directly, as you specify the name in the cookie constructor.

getName() is useful for reading in cookies.

public String getName();

public void setName (String name);

Page 56: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

Domain Attributes

public String getDomain ();

public void setDomain(String domain);

Normally, the browser only returns cookies to the exact same host that sent them.

You can use setDomain() to instruct the browser to send cookies to other hosts within the same domain.

Page 57: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

JDBC & Servlet

By:Abhishek Singh

Page 58: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

Outline• HTML Forms• Tomcat• Functions in JDBC & Servlet

Page 59: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

HTML FormsAn interface controls to collect data from the user and transmit it to server.

Page 60: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

Element in Forms• TEXT CONTROLS:

<INPUT TYPE="TEXT" NAME="NAME" VALUE="INIT">

• PASSWORD FIELDS:<INPUT TYPE="PASSWORD" NAME="PASSWORD">

• TEXT AREAS:<TEXTAREA NAME="RESUME" ROWS=5 COLS=30>INPUT YOUR RESUME HERE </TEXTAREA>

• Checkbox<input type="checkbox" name="checkbox" checked><input type="checkbox" name="checkbox">

• Radio Button<input type="radio" name="radio" checked><input type="radio" name="radio">

Page 61: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

Cont.• List

<select name="list"> <option value="Item 1">Item 1</option> <option value="Item 2">Item 2</option> <option value="Item 3">Item 3</option> </select>

• Multilist<select name="multilist" size="3" multiple> <option value="Item 1">Item 1</option> <option value="Item 2">Item 2</option> <option value="Item 3">Item 3</option> </select>

Page 62: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

Cont.• Submit Button

<input type="submit" name="submit" value="Submit">

• Reset Button<input type="reset" name="reset" value="Reset Fields">

• Image Button<input type="image" name="image" src="go.gif">

• File<input type="file" name="file">

Page 63: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

Tomcat• A light web server that supports servlet & JSP.• It can be integrated in Apache, IIS

For installation process, please refer:CS III: Lab assignment, servlet

http://www.cse.msstate.edu/~cs2324/spring03/

Page 64: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

What is JDBC & Servlet?• JDBC (Java DataBase Connectivity) provides

functions to access database system.• Servlet enables java for CGI programs.• Setup JDBC environment:

Please refer: CS III, Lab assignment, JDBChttp://www.cse.msstate.edu/~cs2324/spring03/

Page 65: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

JDBC : Establishing a Connection

• loading the driver DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());

• making the connection String url = "jdbc:oracle:thin:@ra.msstate.edu:1521:ACAD";

Connection con = DriverManager.getConnection(url, “loginName", “Password");

Page 66: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

Statement• Create a statement Statement stmt = con.createStatement();

• Two methods of statement 1. executeUpdate() create, alter, drop a table

Or insert, delete, update data

2. executeQuery() select

Page 67: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

Create Table• String createTableCoffees = "CREATE TABLE COFFEES " +

"(COF_NAME VARCHAR(32), SUP_ID INTEGER, PRICE FLOAT, " + "SALES INTEGER, TOTAL INTEGER)";

stmt.executeUpdate(createTableCoffees);

Page 68: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

Query Data from a Table• stmt.executeQuery (“select * from customer”);

• ResultSet rs = stmt.executeQuery( "SELECT COF_NAME, PRICE FROM COFFEES");

Page 69: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

Display Result• Method next() Initially the cursor is above the first row of data. After call the method

next(), the cursor is pointing to the first row of data.• A Sample while (rs.next()) { String s = rs.getString ("COF_NAME"); float n = rs.getFloat ("PRICE"); System.out.println (s + " " + n); }

References: http://java.sun.com/docs/books/tutorial/jdbc/index.html

Page 70: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

Methods to Call a Servlet• GET

In html: <A HREF="/servlet/dosearch?aa=12&bb=32">Return Home</A>In html forms:<FORM ACTION=“/servlet/dosearch” METHOD=“GET”>

• POST In html forms: <FORM ACTION=“/servlet/dosearch” METHOD=“POST”>

Page 71: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

Interacting with Clients Handling GET and POST Requests public void doGet (HttpServletRequest

request,HttpServletResponse response) throws ServletException, IOException

<a href="/servlet/getCustomers">List Customers</a>

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

<FORM ACTION=\"/servlet/doInsert\" METHOD=post>

Page 72: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

Output of the ResponseSet the content type of the output

response.setContentType ("text/html")

Get parameterString bookId = request.getParameter ("bookId");

Get the output stream to write to PrintWriter out = response.getWriter();

out.println(“<HTML>”);

Page 73: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

Servlet Program Structures import javax.servlet.*;

import javax.servlet.http.*;

Class must extend from class HttpServlet

Page 74: Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,

A Simple Application public class SimpleServlet extends HttpServlet { // Handle the HTTP GET method by building a simple web page. public void doGet (HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { PrintWriter out; String title = "Simple Servlet Output"; // set content type and other response header fields response.setContentType("text/html"); // then write the data of the response out = response.getWriter(); out.println("<HTML><HEAD><TITLE>"); out.println (title); out.println("</TITLE></HEAD><BODY>"); out.println("<H1>" + title + "</H1>"); out.println("<P>This is output from SimpleServlet."); out.println("</BODY></HTML>"); out.close();

}}