HttpServlet ( Class ) -- we will extend this class to handle GET / PUT HTTP requests

Similar documents
Servlet Fudamentals. Celsina Bignoli

The Basic Web Server CGI. CGI: Illustration. Web based Applications, Tomcat and Servlets - Lab 3 - CMPUT 391 Database Management Systems 4

Questions and Answers

Advance Java. Configuring and Getting Servlet Init Parameters per servlet

Enterprise Java Unit 1- Chapter 4 Prof. Sujata Rizal Servlet API and Lifecycle

Introduction to Java Servlets. SWE 432 Design and Implementation of Software for the Web

Session 8. Introduction to Servlets. Semester Project

4.1 The Life Cycle of a Servlet 4.2 The Java Servlet Development Kit 4.3 The Simple Servlet: Creating and compile servlet source code, start a web

Servlets and JSP (Java Server Pages)

Java Servlets. Preparing your System

Java Enterprise Edition. Java EE Oct Dec 2016 EFREI/M1 Jacques André Augustin Page 1

Servlets1. What are Servlets? Where are they? Their job. Servlet container. Only Http?

SERVLETS INTERVIEW QUESTIONS

Advanced Web Technology

The Servlet Life Cycle

INTRODUCTION TO SERVLETS AND WEB CONTAINERS. Actions in Accord with All the Laws of Nature

********************************************************************

Web based Applications, Tomcat and Servlets - Lab 3 -

Enterprise Java Technologies (Part 1 of 3) Component Architecture. Overview of Java EE. Java Servlets

Module 4: SERVLET and JSP

Chapter 10 Servlets and Java Server Pages

Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 2

Table of Contents. Introduction... xxi

UNIT-V. Web Servers: Tomcat Server Installation:

JAVA SERVLET. Server-side Programming INTRODUCTION

This tutorial will teach you how to use Java Servlets to develop your web based applications in simple and easy steps.

This course is intended for Java programmers who wish to write programs using many of the advanced Java features.

Fast Track to Java EE 5 with Servlets, JSP & JDBC

Servlet Basics. Agenda

LAB 1 PREPARED BY : DR. AJUNE WANIS ISMAIL FACULTY OF COMPUTING UNIVERSITI TEKNOLOGI MALAYSIA

Introduction to JSP and Servlets Training 5-days

AJP. CHAPTER 5: SERVLET -20 marks

Servlets. An extension of a web server runs inside a servlet container

ive JAVA EE C u r r i c u l u m

Type of Classes Nested Classes Inner Classes Local and Anonymous Inner Classes

DVS WEB INFOTECH DEVELOPMENT TRAINING RESEARCH CENTER

Session 9. Introduction to Servlets. Lecture Objectives

ADVANCED JAVA COURSE CURRICULUM

AN ISO 9001:2008 CERTIFIED COMPANY ADVANCED. Java TRAINING.

a. Jdbc:ids://localhost:12/conn?dsn=dbsysdsn 21. What is the Type IV Driver URL? a. 22.

Unit 5 JSP (Java Server Pages)

Advanced Internet Technology Lab # 4 Servlets

Fast Track to Java EE

Servlets Basic Operations

Enterprise Java Unit 1- Chapter 3 Prof. Sujata Rizal Introduction to Servlets

Servlet And JSP. Mr. Nilesh Vishwasrao Patil, Government Polytechnic, Ahmednagar. Mr. Nilesh Vishwasrao Patil

SNS COLLEGE OF ENGINEERING, Coimbatore

Writing Servlets and JSPs p. 1 Writing a Servlet p. 1 Writing a JSP p. 7 Compiling a Servlet p. 10 Packaging Servlets and JSPs p.

Session 20 Data Sharing Session 20 Data Sharing & Cookies

Java servlets CSCI 470: Web Science Keith Vertanen Copyright 2013

Module 3 Web Component

Unit 4 - Servlet. Servlet. Advantage of Servlet

CIS 455 / 555: Internet and Web Systems

LTBP INDUSTRIAL TRAINING INSTITUTE

CSC309: Introduction to Web Programming. Lecture 8

Integrating Servlets and JavaServer Pages Lecture 13

JAVA 2 ENTERPRISE EDITION (J2EE)

/ / JAVA TRAINING

One application has servlet context(s).

Java E-Commerce Martin Cooke,

Using Java servlets to generate dynamic WAP content

Session E118011: Best practices for developing WebSphere based applications

About the Authors. Who Should Read This Book. How This Book Is Organized

Java Servlet Specification Version 2.3

1Z Java EE 6 Web Component Developer Certified Expert Exam Summary Syllabus Questions

Oracle Containers for J2EE

Servlets by Example. Joe Howse 7 June 2011

&' () - #-& -#-!& 2 - % (3" 3 !!! + #%!%,)& ! "# * +,

Application Development in JAVA. Data Types, Variable, Comments & Operators. Part I: Core Java (J2SE) Getting Started

Public Draft. Java Servlet Specification v2.3 PUBLIC REVIEW DRAFT 1 PUBLIC REVIEW DRAFT 1

Oracle EXAM - 1Z Java Enterprise Edition 5 Web Component Developer Certified Professional Exam. Buy Full Product

Topics. Advanced Java Programming. Quick HTTP refresher. Quick HTTP refresher. Web server can return:

Session 9. Data Sharing & Cookies. Reading & Reference. Reading. Reference http state management. Session 9 Data Sharing

PSD1B Advance Java Programming Unit : I-V. PSD1B- Advance Java Programming

A- Core Java Audience Prerequisites Approach Objectives 1. Introduction

CS506 Web Design & Development Final Term Solved MCQs with Reference

HTTP and the Dynamic Web

J2EE Development. Course Detail: Audience. Duration. Course Abstract. Course Objectives. Course Topics. Class Format.

Enterprise Java and Rational Rose - Part II

JSP. Common patterns

Tapestry. Code less, deliver more. Rayland Jeans

Java- EE Web Application Development with Enterprise JavaBeans and Web Services

PRIMIX SOLUTIONS. Core Labs. Tapestry : Java Web Components Whitepaper

The Structure and Components of

Advanced Java Programming

COURSE DETAILS: CORE AND ADVANCE JAVA Core Java

Introduction to Web applications with Java Technology 3- Servlets

Introduction... xv SECTION 1: DEVELOPING DESKTOP APPLICATIONS USING JAVA Chapter 1: Getting Started with Java... 1

RQs + PEs: More Servlets

Learn Java/J2EE Basic to Advance level by Swadeep Mohanty

ddfffddd CS506 FINAL TERMS SOLVED BY MCQS GHAZAL FROM IEMS CAMPUS SMD CS506 Mcqs file solved by ghazal

Data Source Name (Page 150) Ref: - After creating database, you have to setup a system Data Source Name (DSN).

Chettinad College of Engineering and Technology CHETTINAD COLLEGE OF ENGINEERING AND TECHNOLOGY DEPARTMENT OF COMPUTER SCIENCE AND TECHNOLOGY

ADVANCED JAVA TRAINING IN BANGALORE

SSC - Web applications and development Introduction and Java Servlet (I)

INTRODUCTION TO.NET. Domain of.net D.N.A. Architecture One Tier Two Tier Three Tier N-Tier THE COMMON LANGUAGE RUNTIME (C.L.R.)

JAVA SERVLET. Server-side Programming ADVANCED FEATURES

LTBP INDUSTRIAL TRAINING INSTITUTE

JavaServer Pages (JSP)

A Servlet-Based Search Engine. Introduction

Transcription:

What is the servlet? Servlet is a script, which resides and executes on server side, to create dynamic HTML. In servlet programming we will use java language. A servlet can handle multiple requests concurrently. What is the architechture of servlet package? Servlet Interface is the central abstraction. All servlets implements this Servlet Interface either direclty or indirectly ( may implement or extend Servlet Interfaces sub classes or sub interfaces) Servlet Generic Servlet HttpServlet ( Class ) -- we will extend this class to handle GET / PUT HTTP requests MyServlet What is the difference between HttpServlet and GenericServlet? A GenericServlet has a service() method to handle requests. HttpServlet extends GenericServlet added new methods doget() dopost() dohead() doput() dooptions() dodelete() dotrace() methods Both these classes are abstract. What's the difference between servlets and applets? Servlets executes on Servers. Applets executes on browser. Unlike applets, however, servlets have no graphical user interface. 1 / 13

What are the uses of Servlets? A servlet can handle multiple requests concurrently, and can synchronize requests. Servlets can forward requests to other servers and servlets. Thus servlets can be used to balance load among several servers. When doget() method will going to execute? When we specified method='get' in HTML Example : < form name='sss' method='get'> When dopost() method will going to execute? When we specified method='post' in HTML < form name='sss' method='post' > What is the difference between Difference between doget() and dopost()? GET Method : Using get method we can able to pass 2K data from HTML All data we are passing to Server will be displayed in URL (request string). POST Method : In this method we does not have any size limitation. All data passed to server will be hidden, User cannot able to see this info on the browser. What is the servlet life cycle? When first request came in for the servlet, Server will invoke init() method of the servlet. There after if any user request the servlet program, Server will directly executes the service() method. When Server want to remove the servlet from pool, then it will execute the destroy() method Which code line must be set before any of the lines that use the PrintWriter? setcontenttype() method must be set. Which protocol will be used by browser and servlet to communicate? HTTP 2 / 13

In how many ways we can track the sessions? Method 1) By URL rewriting Method 2) Using Session object Getting Session form HttpServletRequest object HttpSession session = request.getsession(true); Get a Value from the session session.getvalue(session.getid()); Adding values to session cart = new Cart(); session.putvalue(session.getid(), cart); At the end of the session, we can inactivate the session by using the following command session.invalidate(); Method 3) Using cookies Method 4) Using hidden fields How Can You invoke other web resources (or other servelt / jsp )? Servelt can invoke other Web resources in two ways: indirect and direct. Indirect Way : Servlet will return the resultant HTML to the browser which will point to another Servlet (Web resource) 3 / 13

Direct Way : We can call another Web resource (Servelt / Jsp) from Servelt program itself, by using RequestDispatcher object. You can get this object using getrequestdispatcher("url") method. You can get this object from either a request or a Context. Example : RequestDispatcher dispatcher = request.getrequestdispatcher("/jspsample.jsp"); if (dispatcher!= null) dispatcher.forward(request, response); } How Can you include other Resources in the Response? Using include method of a RequestDispatcher object. Included WebComponent (Servlet / Jsp) cannot set headers or call any method (for example, setcookie) that affects the headers of the response. Example : RequestDispatcher dispatcher = getservletcontext().getrequestdispatcher("/banner"); if (dispatcher!= null) dispatcher.include(request, response); } What is the difference between the getrequestdispatcher(string path) ServletRequest interface and ServletContext interface? The getrequestdispatcher(string path) method of ServletRequest interface accepts parameter the path to the resource to be included or forwarded to, which can be relative to the request of the calling servlet. If the path begins with a "/" it is interpreted as relative to the current context root. The getrequestdispatcher(string path) method of ServletContext interface cannot accepts 4 / 13

relative paths. All path must sart with a "/" and are interpreted as relative to curent context root. If the resource is not available, or if the server has not implemented a RequestDispatcher object for that type of resource, getrequestdispatcher will return null. Your servlet should be prepared to deal with this condition. What is the use of ServletContext? Using ServletContext, We can access data from its environment. Servlet context is common to all Servlets so all Servlets share the information through ServeltContext. can we create more than ServletContext and ServletConfig in your application?? ServletContext which is managed by webcontainer, For the whole web application only one servletcontext will be there... In ServletConfig, this is also managed by webcontainer, for every request object one servletconfig object will be there.. Question: What is ServletContext? Answer: ServletContext is an Interface that defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file. There is one context per "web application" per Java Virtual Machine. (A "web application" is a collection of servlets and content installed under a specific subset of the server's URL namespace such as /catalog and possibly installed via a.war file.) Question: What is meant by Pre-initialization of Servlet? Answer: When servlet container is loaded, all the servlets defined in the web.xml file does not initialized by default. But the container receives the request it loads the servlet. But in some cases if you want your servlet to be initialized when context is loaded, you have to use a concept called pre-initialization of Servlet. In case of Pre-initialization, the servlet is loaded when context is loaded. You can specify <load-on-startup>1</load-on-startup> in between the <servlet></servlet> tag. 5 / 13

Question: What mechanisms are used by a Servlet Container to maintain session information? Answer: Servlet Container uses Cookies, URL rewriting, and HTTPS protocol information to maintain the session. Question: What do you understand by servlet mapping? Answer: Servlet mapping defines an association between a URL pattern and a servlet. You can use one servlet to process a number of url pattern (request pattern). For example in case of Struts *.do url patterns are processed by Struts Controller Servlet. Question: What must be implemented by all Servlets? Answer: The Servlet Interface must be implemented by all servlets. Question: What are the differences between Servlet and Applet? Answer: Servlets are server side components that runs on the Servlet container. Applets are client side components and runs on the web browsers. Servlets have no GUI interface. Question: What are the uses of Servlets? Answer: * Servlets are used to process the client request. * A Servlet can handle multiple request concurrently and be used to develop high performance system * A Servlet can be used to load balance among serveral servers, as Servlet can easily forward request. Question: What are the objects that are received when a servlets accepts call from client? Answer: The objects are ServeltRequest and ServletResponse. The ServeltRequest encapsulates the communication from the client to the server. While ServletResponse encapsulates the communication from the Servlet back to the client. Question: What is a Session? Answer: A Session refers to all the request that a single client makes to a server. A session is specific to the user and for each user a new session is created to track all the request from that user. Every user has a separate session and separate session variable is associated with that session. In case of web applications the default time-out value for session variable is 20 6 / 13

minutes, which can be changed as per the requirement. Question: What is Session ID? Answer: A session ID is an unique identification string usually a long, random and alpha-numeric string, that is transmitted between the client and the server. Session IDs are usually stored in the cookies, URLs (in case url rewriting) and hidden fields of Web pages. Question: What is Session Tracking? Answer: HTTP is stateless protocol and it does not maintain the client state. But there exist a mechanism called "Session Tracking" which helps the servers to maintain the state to track the series of requests from the same user across some period of time. Question: What are different types of Session Tracking? Answer: Mechanism for Session Tracking are: a) Cookies b) URL rewriting c) Hidden form fields d) SSL Sessions Question: What is HTTPSession Class? Answer: HttpSession Class provides a way to identify a user across across multiple request. The servlet container uses HttpSession interface to create a session between an HTTP client and an HTTP server. The session lives only for a specified time period, across more than one connection or page request from the user. Question: Why do u use Session Tracking in HttpServlet? Answer: In HttpServlet you can use Session Tracking to track the user state. Session is required if you are developing shopping cart application or in any e-commerce application. Question: What are the advantage of Cookies over URL rewriting? Answer: Sessions tracking using Cookies are more secure and fast. Session tracking using Cookies can also be used with other mechanism of Session Tracking like url rewriting. 7 / 13

Cookies are stored at client side so some clients may disable cookies so we may not sure that the cookies may work or not. In url rewriting requites large data transfer from and to the server. So, it leads to network traffic and access may be become slow. Question: What is session hijacking? Answer: If you application is not very secure then it is possible to get the access of system after acquiring or generating the authentication information. Session hijacking refers to the act of taking control of a user session after successfully obtaining or generating an authentication session ID. It involves an attacker using captured, brute forced or reverse-engineered session IDs to get a control of a legitimate user's Web application session while that session is still in progress. Question: What is Session Migration? Answer: Session Migration is a mechanism of moving the session from one server to another in case of server failure. Session Migration can be implemented by: a) Persisting the session into database b) Storing the session in-memory on multiple servers. Question: How to track a user session in Servlets? Answer: The interface HttpSession can be used to track the session in the Servlet. Following code can be used to create session object in the Servlet: HttpSession session = req.getsession(true); Question: How you can destroy the session in Servlet? Answer: You can call invalidate() method on the session object to destroy the session. e.g. session.invalidate(); Collection of large number of Servlet Interview Questions. These questions are frequently asked in the Java Interviews. 8 / 13

Question: What is a Servlet? Answer: Java Servlets are server side components that provides a powerful mechanism for developing server side of web application. Earlier CGI was developed to provide server side capabilities to the web applications. Although CGI played a major role in the explosion of the Internet, its performance, scalability and reusability issues make it less than optimal solutions. Java Servlets changes all that. Built from ground up using Sun's write once run anywhere technology java servlets provide excellent framework for server side processing. Question: What are the types of Servlet? Answer: There are two types of servlets, GenericServlet and HttpServlet. GenericServlet defines the generic or protocol independent servlet. HttpServlet is subclass of GenericServlet and provides some http specific functionality linke doget and dopost methods. Question: What are the differences between HttpServlet and Generic Servlets? Answer: HttpServlet Provides an abstract class to be subclassed to create an HTTP servlet suitable for a Web site. A subclass of HttpServlet must override at least one method, usually one of these: doget, if the servlet supports HTTP GET requests dopost, for HTTP POST requests doput, for HTTP PUT requests dodelete, for HTTP DELETE requests init and destroy, to manage resources that are held for the life of the servlet getservletinfo, which the servlet uses to provide information about itself There's almost no reason to override the service method. service handles standard HTTP requests by dispatching them to the handler methods for each HTTP request type (the doxxx methods listed above). Likewise, there's almost no reason to override the dooptions and dotrace methods. GenericServlet defines a generic, protocol-independent servlet. To write an HTTP servlet for use on the Web, extend HttpServlet instead. GenericServlet implements the Servlet and ServletConfig interfaces. GenericServlet may be directly extended by a servlet, although it's more common to extend a protocol-specific subclass such as HttpServlet. 9 / 13

GenericServlet makes writing servlets easier. It provides simple versions of the lifecycle methods init and destroy and of the methods in the ServletConfig interface. GenericServlet also implements the log method, declared in the ServletContext interface. To write a generic servlet, you need only override the abstract service method. Question: Differentiate between Servlet and Applet. Answer: Servlets are server side components that executes on the server whereas applets are client side components and executes on the web browser. Applets have GUI interface but there is not GUI interface in case of Servlets. Question: Differentiate between doget and dopost method? Answer: doget is used when there is are requirement of sending data appended to a query string in the URL. The doget models 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. POST 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 GET. POST 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. For real security you have to look into encryption which is an entirely different topic Question: What are methods of HttpServlet? Answer: The methods of HttpServlet class are : * doget() is used to handle the GET, conditional GET, and HEAD requests * dopost() is used to handle POST requests * doput() is used to handle PUT requests * dodelete() is used to handle DELETE requests * dooptions() is used to handle the OPTIONS requests and * dotrace() is used to handle the TRACE requests Question: What are the advantages of Servlets over CGI programs? 10 / 13

Answer: Question: What are methods of HttpServlet? Answer: Java Servlets have a number of advantages over CGI and other API's. They are: Platform Independence Java Servlets are 100% pure Java, so it is platform independence. It can run on any Servlet enabled web server. For example if you develop an web application in windows machine running Java web server. You can easily run the same on apache web server (if Apache Serve is installed) without modification or compilation of code. Platform independency of servlets provide a great advantages over alternatives of servlets. Performance Due to interpreted nature of java, programs written in java are slow. But the java servlets runs very fast. These are due to the way servlets run on web server. For any program initialization takes significant amount of time. But in case of servlets initialization takes place very first time it receives a request and remains in memory till times out or server shut downs. After servlet is loaded, to handle a new request it simply creates a new thread and runs service method of servlet. In comparison to traditional CGI scripts which creates a new process to serve the request. This intuitive method of servlets could be use to develop high speed data driven web sites. Extensibility Java Servlets are developed in java which is robust, well-designed and object oriented language which can be extended or polymorphed into new objects. So the java servlets takes all these advantages and can be extended from existing class the provide the ideal solutions. Safety Java provides a very good safety features like memory management, exception handling etc. Servlets inherits all these features and emerged as a very powerful web server extension. Secure Servlets are server side components, so it inherits the security provided by the web server. Servlets are also benefited with Java Security Manager. Question: What are the lifecycle methods of Servlet? Answer: The interface javax.servlet.servlet, defines the three life-cycle methods. These are: public void init(servletconfig config) throws ServletException public void service( ServletRequest req, ServletResponse res) throws ServletException, IOException public void destroy() The container manages the lifecycle of the Servlet. When a new request come to a Servlet, the container performs the following steps. 1. If an instance of the servlet does not exist, the web container * Loads the servlet class. * Creates an instance of the servlet class. * Initializes the servlet instance by calling the init method. Initialization is covered in Initializing a Servlet. 11 / 13

2. The container invokes the service method, passing request and response objects. 3. To remove the servlet, container finalizes the servlet by calling the servlet's destroy method. Question: What are the type of protocols supported by HttpServlet? Answer: It extends the GenericServlet base class and provides an framework for handling the HTTP protocol. So, HttpServlet only supports HTTP and HTTPS protocol. Question: What are the directory Structure of Web Application? Answer: Web component follows the standard directory structure defined in the J2EE specification Question: What is ServletContext? Answer: ServletContext is an Interface that defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file. There is one context per "web application" per Java Virtual Machine. (A "web application" is a collection of servlets and content installed under a specific subset of the server's URL namespace such as /catalog and possibly installed via a.war file.) Question: What is meant by Pre-initialization of Servlet? Answer: When servlet container is loaded, all the servlets defined in the web.xml file does not initialized by default. But the container receives the request it loads the servlet. But in some cases if you want your servlet to be initialized when context is loaded, you have to use a concept called pre-initialization of Servlet. In case of Pre-initialization, the servlet is loaded when context is loaded. You can specify <load-on-startup>1</load-on-startup> in between the <servlet></servlet> tag. Question: What mechanisms are used by a Servlet Container to maintain session information? Answer: Servlet Container uses Cookies, URL rewriting, and HTTPS protocol information to maintain the session. Question: What do you understand by servlet mapping? Answer: Servlet mapping defines an association between a URL pattern and a servlet. You can use one servlet to process a number of url pattern (request pattern). For example in case of Struts *.do url patterns are processed by Struts Controller Servlet. 12 / 13

Question: What must be implemented by all Servlets? Answer: The Servlet Interface must be implemented by all servlets. Question: What are the differences between Servlet and Applet? Answer: Servlets are server side components that runs on the Servlet container. Applets are client side components and runs on the web browsers. Servlets have no GUI interface. Question: What are the uses of Servlets? Answer: * Servlets are used to process the client request. * A Servlet can handle multiple request concurrently and be used to develop high performance system * A Servlet can be used to load balance among serveral servers, as Servlet can easily forward request. Question: What are the objects that are received when a servlets accepts call from client? Answer: The objects are ServeltRequest and ServletResponse. The ServeltRequest encapsulates the communication from the client to the server. While ServletResponse encapsulates the communication from the Servlet back to the client. 13 / 13