Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Abhishek Singh. Web Application: A web application is an application accessible from the web. A web application is composed of web components like Servlet,"— Presentation transcript:

1 Abhishek Singh

2 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.

3 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.

4 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

5 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.

6 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..

7 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

8 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.

9 Http Request Methods HTTP Request Description GETAsks 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. PUTSays to put the enclosed info (the body) at the requested URL. DELETESays to delete the resource at the requested URL. OPTIONSAsks for a list of the HTTP methods to which the thing at the request URL can respond

10 What is the difference between Get and Post? GETPOST 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 bookmarkedPost 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.

11 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.

12 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.

13 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.

14 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.

15 Generic Servlet & HTTP Servlet GenericServlet service ( ) Server Client HTTPServlet service ( ) HTTP Server Browser request response doGet ( ) doPost( ) request response 15

16 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

17 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

18 Initialization init() Service service() doGet() doPost() doDelete() doHead() doTrace() doOptions() Destruction destroy() Concurrent Threads of Execution Servlet Life Cycle 18

19 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

20 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

21 HttpServletResponse - Methods java.io.PrintWritergetWriter() Returns a PrintWriter object that can send character text to the client voidsetContentType (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

22 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.

23

24 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.

25 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.

26 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

27 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- -:

28 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.

29 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

30 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); –....

31 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.c om"); response.setStatus(response.SC _MOVED_TEMPORARILY); response.setHeader("Location", site); }

32 Web.xml.... PageRedirect PageRedirect /PageRedirect PageRedirect

33 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.

34 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

35

36 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()….

37 Types of servlets (cont..) Generic servlet – service(Request, Response) throws ServletException, IOException HttpServlet – doGet(HttpServletRequest req, HttpServletResponse res)

38 Basic Servlet example import 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(“ HELLO, WORLD! ”); }

39 POST Example import 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();

40 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); }

41 Counter example import ….; 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

42 What is the problem with the above example??

43 Synchonized counter import ….; 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

44 Servlet Life Cycle Initialize using init method Servlet handles requests/clients Server removes the servlet using destroy method

45 Servlets vs. Applets Similarities – Neither has a main() – Both have init() and destroy() – Both are part of a larger application made for the web

46 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 – …

47 Servlet Session I: Cookie API

48 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

49 Cookies and Focused Advertising

50 Creating Cookies

51  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.

52 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);

53 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:  [ ] ( ) =, “ / ? @ ;

54 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

55 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);

56 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.

57 JDBC & Servlet By: Abhishek Singh

58 Outline HTML Forms Tomcat Functions in JDBC & Servlet

59 HTML Forms An interface controls to collect data from the user and transmit it to server.

60 Element in Forms TEXT CONTROLS: PASSWORD FIELDS: TEXT AREAS: INPUT YOUR RESUME HERE Checkbox Radio Button

61 Cont. List Item 1 Item 2 Item 3 Multilist Item 1 Item 2 Item 3

62 Cont. Submit Button Reset Button Image Button File

63 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/

64 What is JDBC & Servlet? JDBC (Java DataBase Connectivity) provides functions to access database system. Servlet enables java for CGI programs. Setup JDBC environment: Please r efer: CS III, Lab assignment, JDBC http://www.cse.msstate.edu/~cs2324/spring03/

65 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");

66 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

67 Create Table String createTableCoffees = "CREATE TABLE COFFEES " + "(COF_NAME VARCHAR(32), SUP_ID INTEGER, PRICE FLOAT, " + "SALES INTEGER, TOTAL INTEGER)"; stmt.executeUpdate(createTableCoffees);

68 Query Data from a Table stmt.executeQuery (“select * from customer”); ResultSet rs = stmt.executeQuery( "SELECT COF_NAME, PRICE FROM COFFEES");

69 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

70 Methods to Call a Servlet GET In html: Return Home In html forms: POST In html forms:

71 Interacting with Clients Handling GET and POST Requests public void doGet (HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException List Customers public void doPost (HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException

72 Output of the Response  Set the content type of the output response.setContentType ("text/html")  Get parameter String bookId = request.getParameter ("bookId");  Get the output stream to write to PrintWriter out = response.getWriter(); out.println(“ ”);

73 Servlet Program Structures  import javax.servlet.*; import javax.servlet.http.*;  Class must extend from class HttpServlet

74 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(" "); out.println (title); out.println(" "); out.println(" " + title + " "); out.println(" This is output from SimpleServlet."); out.println(" "); out.close(); }


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

Similar presentations


Ads by Google