Introduction to Servlets. Introduction Servlet is a language to develop the server side applications, and it is also server side component. It can develop.

Slides:



Advertisements
Similar presentations
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 10 Servlets and Java Server Pages.
Advertisements

Objectives Ch. D - 1 At the end of this chapter students will: Know the general architecture and purpose of servlets Understand how to create a basic servlet.
WEB1P servintro1 Introduction to servlets and JSP Dr Jim Briggs.
An introduction to Java Servlet Programming
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 34 Servlets.
2/16/2004 Dynamic Content February 16, /16/2004 Assignments Due – Message of the Day Part 1 Due – Reading and Warmup Work on Message of the Day.
Introduction to Servlet & JSP
Comp2513 Java Servlet Basics Daniel L. Silver, Ph.D.
Java Server and Servlet CS616 Team 9 Kim Doyle, Susan Kroha, Arunima Palchowdhury, Wei Xu.
Chapter 4 Servlets Concept of Servlets (What, Why, and How) Servlet API Third-party tools to run servlets Examples of Using Servlets HTML tag with GET.
Definition Servlet: Servlet is a java class which extends the functionality of web server by dynamically generating web pages. Web server: It is a server.
Servlets Compiled by Dr. Billy B. L. Lim. Servlets Servlets are Java programs which are invoked to service client requests on a Web server. Servlets extend.
Servlets. Our Project 3-tier application Develop our own multi-threaded server Socket level communication.
Chapter 10 Servlets and Java Server Pages. A servlet is a Java class designed to be run in the context of a special servlet container An instance of the.
Java Servlets. What Are Servlets? Basically, a java program that runs on the server Basically, a java program that runs on the server Creates dynamic.
Gayle J Yaverbaum, PhD Professor of Information Systems Penn State Harrisburg.
1 Servlet How can a HTML page, displayed using a browser, cause a program on a server to be executed?
FALL 2005CSI 4118 – UNIVERSITY OF OTTAWA1 Part 4 Web technologies: HTTP, CGI, PHP,Java applets)
Servlets Pranav Maydeo. What is a Servlet ? Servlets are modules of Java code that run in a server application to answer client requests. Servlets are.
Servlets. - Java technology for Common Gateway Interface (CGI) programming. - It is a Java class that dynamically extends the function of a web server.
Objectives Java Servlet Web Components
Java support for WWW Babak Esfandiari (sources: Qusay Mahmoud, Roger Impey, textbook)
CSC 2720 Building Web Applications
Chapter 5 Java Servlets. Objectives Explain the nature of a servlet and its operation Use the appropriate servlet methods in a web application Code the.
Li Tak Sing COMPS311F. Static attributes in Servlets Since Servlets are also Java classes, you can also use static attributes to store values that can.
COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction.
CMPUT 391 – Database Management Systems Department of Computing Science University of Alberta CMPUT 391 Database Management Systems Web based Applications,
Web Server Programming 1. Nuts and Bolts. Premises of Course Provides general introduction, no in-depth training Assumes some HTML knowledge Assumes some.
JAVA SERVER PAGES. 2 SERVLETS The purpose of a servlet is to create a Web page in response to a client request Servlets are written in Java, with a little.
Chapter 3 Servlet Basics. 1.Recall the Servlet Role 2.Basic Servlet Structure 3.A simple servlet that generates plain text 4.A servlet that generates.
Java Servlets & Java Server Pages Lecture July 2013.
Java Servlets Lec 27. Creating a Simple Web Application in Tomcat.
1 CS122B: Projects in Databases and Web Applications Spring 2015 Notes 03: Web-App Architectures Professor Chen Li Department of Computer Science CS122B.
20-Nov-15introServlets.ppt Intro to servlets. 20-Nov-15introServlets.ppt typical web page – source Hello Hello.
Java Servlet API CGI / HTTP Concepts Java Servlet API.
@2008 Huynh Ngoc Tin Chapter #2 JAVA SERVLET PRGRAMMING.
Introduction to Server-Side Web Development Introduction to Server-Side Web Development Session II: Introduction to Server-Side Web Development with Servlets.
Li Tak Sing COMPS311F. A web page that counts the number of times that you have visited the page. You can try the page at:
Java Servlets and Java Server Pages Norman White Stern School of Business.
Copyright © 2002 ProsoftTraining. All rights reserved. Java Servlets.
1 Java Servlets l Servlets : programs that run within the context of a server, analogous to applets that run within the context of a browser. l Used to.
Middleware 3/29/2001 Kang, Seungwoo Lee, Jinwon. Description of Topics 1. CGI, Servlets, JSPs 2. Sessions/Cookies 3. Database Connection(JDBC, Connection.
CSI 3125, Preliminaries, page 1 SERVLET. CSI 3125, Preliminaries, page 2 SERVLET A servlet is a server-side software program, Responds oriented other.
1 Introduction to Servlets. Topics Web Applications and the Java Server. HTTP protocol. Servlets 2.
CSI 3125, Preliminaries, page 1 SERVLET. CSI 3125, Preliminaries, page 2 SERVLET A servlet is a server-side software program, written in Java code, that.
J2EE T ECHNOLOGIES These are the technologies required to build large scale distributed applications, can be divided into – Component Technologies eg.
©SoftMooreSlide 1 Session Tracking with Servlets.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 21 Java Servlets Wed. 11/22/00 based on material.
Java Servlets and Java Server Pages
Session Tracking Parts of this presentation was provided by SSE.
Introduction To HTML Dr. Magdi AMER. HTML elements.
How CGI and Java Servlets are Run By David Stein 14 November 2006.
Java Programming: Advanced Topics 1 Building Web Applications Chapter 13.
Bayu Priyambadha, S.Kom. Static content  Web Server delivers contents of a file (html) 1. Browser sends request to Web Server 3. Web Server sends HTML.
8-Mar-16 More About Servlets Session Tracking. Persistent information A server site typically needs to maintain two kinds of persistent (remembered) information:
S ERVLETS Form Data 19-Mar-16. F ORM P ROCESSING You must have come across many situations when you need to pass some information from your browser to.
Servlets.
Servlet Fudamentals.
Java Servlets By: Tejashri Udavant..
Session Tracking in Servlets
Pre-assessment Questions
Java Servlets II: Session Tracking
Servlet.
Chapter 26 Servlets.
Servlet APIs Every servlet must implement javax.servlet.Servlet interface Most servlets implement the interface by extending one of these classes javax.servlet.GenericServlet.
Objectives In this lesson you will learn about: Need for servlets
Servlets Servlets are modules that extend the functionality of a “java-enabled” web-server They normally generate HTML code and web content dynamically.
Servlets Servlets are modules that extend the functionality of a “java-enabled” web-server They normally generate HTML code and web content dynamically.
Pre-assessment Questions
CS122B: Projects in Databases and Web Applications Winter 2019
Presentation transcript:

Introduction to Servlets

Introduction Servlet is a language to develop the server side applications, and it is also server side component. It can develop web-based applications, and it is provide component-based platform independent methods. Servlet is a server as well as platform independent. It gives a freedom to you for selecting your server, platforms and tools. Web developers can create fast and efficient web based applications using by servlet.

HTTP Servlet HTTP Servlet is a base class of servlet program; it is used to dynamic content. HTML submitted data to store the process. The dynamic content getting the result of a database and returning to the client, and manage the information of the stateless HTTP. Hyper Text Markup Language (HTML) is the describe inside of web documents Hypertext Transfer Protocol (HTTP) is the language used to describe how documents are sent over the internet.

Servlets role in J2EE

Life cycle of Servlet

Advantages of Java Servlets Portability Servlets are written in java and follow well known standardized APIs so they are highly portable across operating systems and server implementations.They are write once, run anywhere (WORA) program. Powerful Servlets can talk directly to the web server while the CGI programs can't do. Servlets can share data among each other, they even make the database connection pools easy to implement. They can maintain the session by using the session tracking mechanism which helps them to maintain information from request to request. Efficiency When the servlet get loaded in the server, it remains in the server's memory as a single object instance. However with servlets there are N threads but only a single copy of the servlet class. Multiple concurrent requests are handled by separate threads so we can say that the servlets are highly scalable.

Advantages of Java Servlets Safety As servlets are written in java, servlets inherit the strong type safety of java language. Java's automatic garbage collection and a lack of pointers means that servlets are generally safe from memory management problems. In servlets we can easily handle the errors due to Java's exception handling mechanism. If any exception occurs then it will throw an exception. Integration Servlets are tightly integrated with the server. Servlet can use the server to translate the file paths, perform logging, check authorization, and MIME type mapping etc. Extensibility The servlet API is designed in such a way that it can be easily extensible. The servlet API support Http Servlets, but in later date it can be extended for another type of servlets. Inexpensive There are number of free web servers available for personal use or for commercial purpose. Web servers are relatively expensive. So by using the free available web servers you can add servlet support to it.

Simple Example import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class DisplayingDate extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ PrintWriter pw = response.getWriter(); Date today = new Date(); pw.println(" "+" Today Date is "); pw.println(" "+ today+" "+ " "); } }

HTTP Request HTTP: Hypertext Transfer Protocol is the language used to describe how the documents are sent over the internet. HTTP recommends the rules by which browser make request and servers provide response. This rules or protocol includes, – Document name – Data format – User name – Decide handle outdated resources – Indicate the request

HTTP request mode Basic HTTP Client and Server Communication A key consideration is this model is stateless After a TCP connection is created, the client request and server response is communicated. Client Request: The HTTP client sends a request message formatted by the rules of the HTTP standard an HTTP request. Information provided to be provided to the server. Server Response: server received the clients request and interprets the request. It takes action on the client request and server creates an HTTP response message and sends back to client. If request was successful the response message

The HttpServletRequest class getParameter() getParameterValues() getParameterNames() getParameterMap().

getParameter() This method is used to get the client request parameter It is returns the value of a request parameter as a String value. HTTP Servlet parameter are contained in the query string or posted form data. While client request only one at a time, method can be get the parameter string. This method cannot get more than one parameter value.

getParameterValues() This method is used to get the parameter values from the client request. It is return an array of string objects. If the string values are null the parameter does not exist. This method can get more than one parameter and its value also. The String objects containing all of the values the given request parameter If the parameter return single value the array values is one.

getParameterNames() This method is used to get the request parameter and return the string objects name This method derived the Enumeration class. The string objects containing the parameters name contained in this request. If the request has no parameters, the method returns a null/empty Enumeration.

getParameterMap(). This method derived Map class, this method returns parameter values as map values using by parameter name as key. The parameter name has the key of type as String, and the parameter map values type as String array.

Attribute in Servlet An attribute in servlet is an object that can be set, get or removed from one of the following scopes: request scope session scope application scope The servlet programmer can pass informations from one servlet to another using attributes. It is just like passing object from one class to another so that we can reuse the same object again and again.

Attribute specific methods There are following 4 attribute specific methods. public void setAttribute(String name,Object object):sets the given object in the application scope. public Object getAttribute(String name):Returns the attribute for the specified name. public Enumeration getInitParameterNames():Returns the names of the context's initialization parameters as an Enumeration of String objects. public void removeAttribute(String name):Removes the attribute with the given name from the servlet context.

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class DemoServlet1 extends HttpServlet{ public void doGet(HttpServletRequest req,HttpServletResponse res) { try{ res.setContentType("text/html"); PrintWriter out=res.getWriter(); ServletContext context=getServletContext(); context.setAttribute("company","IBM"); out.println("Welcome to first servlet"); out.println(" visit "); out.close(); }catch(Exception e){out.println(e);} }}

SendRedirect in servlet The sendRedirect() method of HttpServletResponse interface can be used to redirect response to another resource, it may be servlet, jsp or html file. It accepts relative as well as absolute URL. It works at client side because it uses the url bar of the browser to make another request. So, it can work inside and outside the server.

Difference between forward() and sendRedirect() method forward() methodsendRedirect() method The forward() method works at server side. The sendRedirect() method works at client side. It sends the same request and response objects to another servlet. It always sends a new request. It can work within the server only. It can be used within and outside the server. Example: request.getRequestDispacher("servlet2").forward(request,response); Example: response.sendRedirect("servlet2");

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class DemoServlet extends HttpServlet{ public void doGet(HttpServletRequest req,HttpServlet Response res) throws ServletException,IOException { res.setContentType("text/html"); PrintWriter pw=res.getWriter(); response.sendRedirect(" pw.close(); }}

Output

Session Tracking Http is a stateless protocol- means that it can't persist the information. It always treats each request as a new request. In Http client makes a connection to the server, sends the request., gets the response, and closes the connection. In session management client first make a request for any servlet or any page The container receives the request and generate a unique session ID and gives it back to the client along with the response. This ID gets stores on the client machine

Ways of Session Tracking Hidden Form Fields: This is one of the way to support the session tracking. The hidden form field are sent back to the server when the form is submitted. In hidden form fields the html entry will be like this :. In this session ID information would be embedded within the form as a hidden field and submitted with the Http POST command.

URL Rewriting: URLRewriting can be used in place where we don't want to use cookies. It is used to maintain the session. Whenever the browser sends a request then it is always interpreted as a new request because http protocol is a stateless protocol as it is not persistent. In session tracking firstly a session object is created when the first request goes to the server. Then server creates a token which will be used to maintain the session. The token is transmitted to the client by the response object and gets stored on the client machine. By default the server creates a cookie and the cookie get stored on the client machine.

Cookies: When cookie based session management is used, a token is generated which contains user's information, is sent to the browser by the server. The cookie is sent back to the server when the user sends a new request. By this cookie, the server is able to identify the user. Cookie is nothing but a name- value pair, which is stored on the client machine. By default the cookie is implemented in most of the browsers. If we want then we can also disable the cookie. For security reasons, cookie based session management uses two types of cookies.

Session Example import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class CheckingTheSession extends HttpServlet{ protected void doGet(HttpServletRequest request, HttpServlet Response response)throws ServletException, IOException { response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.println("Checking whether the session is new or old "); HttpSession session = request.getSession(); if(session.isNew()){ pw.println("You have created a new session"); } else{ pw.println("Session already exists"); } } }

Get Session ID import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class SessionIdServlet extends HttpServlet{ protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{ response.setContentType("text/html"); PrintWriter pw = response.getWriter(); HttpSession session = request.getSession(); String id = session.getId(); pw.println("Session Id is : " + id); } }

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class CounterServlet extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(true); response.setContentType("text/html"); PrintWriter out = response.getWriter(); Integer count = new Integer(0); String head; if (session.isNew()) { head = "This is the New Session"; } else { head = "This is the old Session"; Integer oldcount =(Integer)session.getValue("count"); if (oldcount != null) { count = new Integer(oldcount.intValue() + 1); } } session.putValue("count", count); out.println(" \n" + " " + head + " \n" + " \n” + " \ n" +" Information Type Session Count\n“ +" \n" +" Total Sessio n Accesses\n" + " " + count + "\n" + " \n" +" " ); } }

Cookie Introduction Cookies are small pieces of information that are sent in response from the web server to the client. Cookiesare the simplest technique used for storing client state. Cookies are stored on client's computer. They have a lifespan and are destroyed by the client browser at the end of that lifespan.

Cookies API Cookies are created using Cookie class present in Servlet API. Cookies are added to response object using the addCookie() method. This method sends cookie information over the HTTP response stream. getCookies() method is used to access the cookies that are added to response object.

Cookies API

Cookie Example

index.html Name: Password:

MyServlet.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class MyServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); String name = request.getParameter("user"); String pass = request.getParameter("pass"); if(pass.equals("1234")) { Cookie ck = new Cookie("username",name); response.addCookie(ck); response.sendRedirect("First"); } } }

First.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class First extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF- 8"); PrintWriter out = response.getWriter(); Cookie[] cks = request.getCookies(); out.println("Welcome "+cks[0].getValue()); } }

Registration form in Servlet

Create a Table in your Database create table Student ( name varchar(60), varchar(60), pass varchar(100) ) Index.html Register form Name: ID: Password:

Register.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.sql.*; public class Register extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String name = request.getParameter("name"); String = request.getParameter(" "); String pass = request.getParameter("pass"); try{ Class.forName("com.mysql.jdbc.Driver"); con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","username","pas sword"); PreparedStatement ps=con.prepareStatement ("insert into Student values(?,?,?)"); ps.setString(1, name); ps.setString(2, ); ps.setString(3, pass); int i=ps.executeUpdate(); if(i>0) { out.println("You are sucessfully registered"); } } catch(Exception se) { se.printStackTrace(); } } }