SERVLETS INTERVIEW QUESTIONS

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

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

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

Servlet Fudamentals. Celsina Bignoli

RESTFUL WEB SERVICES - INTERVIEW QUESTIONS

Servlets and JSP (Java Server Pages)

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

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

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

UNIT-V. Web Servers: Tomcat Server Installation:

Module 4: SERVLET and JSP

SERVLETS MOCK TEST SERVLETS MOCK TEST III

Chapter 10 Servlets and Java Server Pages

To follow the Deitel publishing program, sign-up now for the DEITEL BUZZ ON-

DESIGN PATTERN - INTERVIEW QUESTIONS

In servlet, form parsing is handled automatically. You call request.getparameter to get the value of a form parameter.

Advanced Web Technology

AJP. CHAPTER 5: SERVLET -20 marks

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

Session 8. Introduction to Servlets. Semester Project

Questions and Answers

Unit 5 JSP (Java Server Pages)

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

JdbcResultSet.java. import java.sql.*;

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

Servlet Basics. Agenda

JAVA SERVLET. Server-side Programming INTRODUCTION

Advanced Internet Technology Lab # 4 Servlets

Web based Applications, Tomcat and Servlets - Lab 3 -

Unit 4 - Servlet. Servlet. Advantage of Servlet

JAVA SERVLET. Server-side Programming PROGRAMMING

Java Servlets. Preparing your System

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

Unit-4: Servlet Sessions:

Advance Java. Configuring and Getting Servlet Init Parameters per servlet

HTTP and the Dynamic Web

Database Applications Recitation 6. Project 3: CMUQFlix CMUQ s Movies Recommendation System

Introduction to JSP and Servlets Training 5-days

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

Java Technologies Web Filters

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

Session 20 Data Sharing Session 20 Data Sharing & Cookies

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

CSC309: Introduction to Web Programming. Lecture 8

How does the Web work? HTTP and the Dynamic Web. Naming and URLs. In Action. HTTP in a Nutshell. Protocols. The canonical example in your Web browser

Java servlets CSCI 470: Web Science Keith Vertanen Copyright 2013

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

Using Java servlets to generate dynamic WAP content

Session 9. Introduction to Servlets. Lecture Objectives

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

HTML5 - INTERVIEW QUESTIONS

CIS 455 / 555: Internet and Web Systems

Handout 31 Web Design & Development

Session 8. Reading and Reference. en.wikipedia.org/wiki/list_of_http_headers. en.wikipedia.org/wiki/http_status_codes

Table of Contents. Introduction... xxi

Session 9. Deployment Descriptor Http. Reading and Reference. en.wikipedia.org/wiki/http. en.wikipedia.org/wiki/list_of_http_headers

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

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

JSP. Common patterns

Chapter 17. Web-Application Development

MAVEN INTERVIEW QUESTIONS

The Servlet Life Cycle

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

Enterprise Java and Rational Rose - Part II

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

Java E-Commerce Martin Cooke,

STRUTS2 - INTERVIEW QUESTIONS

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

Java4570: Session Tracking using Cookies *

Generating the Server Response: HTTP Response Headers

Servlets Basic Operations

AN OVERVIEW OF SERVLET AND JSP TECHNOLOGY

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

Chapter 10 Web-based Information Systems

SNS COLLEGE OF ENGINEERING, Coimbatore

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

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.

.NET-6Weeks Project Based Training

UNIT - III. Every element in a document tree refers to a Node object. Some nodes of the tree are

Advanced Internet Technology Lab # 6

CE212 Web Application Programming Part 3

ANGULARJS INTERVIEW QUESTIONS

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

UNIT I. A protocol is a precise set of rules defining how components communicate, the format of addresses, how data is split into packets

Chapter 29 Servlets: Bonus for Java Developers 1041

CS506 Web Design & Development Final Term Solved MCQs with Reference

INTERNET PROGRAMMING TEST-3 SCHEME OF EVALUATION 1.A 3 LIFE CYCLE METHODS - 3M 1.B HTML FORM CREATION - 2 M

Oracle 1Z Java EE 6 Web Component Developer(R) Certified Expert.

Advanced Java Programming

When the Servlet Model Doesn't Serve. Gary Murphy Hilbert Computing, Inc.

sessionx Desarrollo de Aplicaciones en Red A few more words about CGI CGI Servlet & JSP José Rafael Rojano Cáceres

SERVLET AND JSP FILTERS

HBASE INTERVIEW QUESTIONS

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

Handling Cookies. Agenda

UNIT -5. Java Server Page

RQs + PEs: More Servlets

Developer Resources: PIN2

Session E118011: Best practices for developing WebSphere based applications

Advanced Topics in Operating Systems. Manual for Lab Practices. Enterprise JavaBeans

Transcription:

SERVLETS INTERVIEW QUESTIONS http://www.tutorialspoint.com/servlets/servlets_interview_questions.htm Copyright tutorialspoint.com Dear readers, these Servlets Interview Questions have been designed especially to get you acquainted with the nature of questions you may encounter during your interview for the subject of Servlets Programming. As per my experience, good interviewers hardly planned to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer: What are Servlets? Java Servlets are programs that run on a Web or Application server and act as a middle layer between a request coming from a Web browser or other HTTP client and databases or applications on the HTTP server. What are the advantages of servlets over CGI? Servlets offer several advantages in comparison with the CGI. Performance is significantly better. Servlets execute within the address space of a Web server. It is not necessary to create a separate process to handle each client request. Servlets are platform-independent because they are written in Java. Java security manager on the server enforces a set of restrictions to protect the resources on a server machine. So servlets are trusted. The full functionality of the Java class libraries is available to a servlet. It can communicate with applets, databases, or other software via the sockets and RMI mechanisms that you have seen already. What are the major tasks of servlets? Servlets perform the following major tasks: Read the explicit data sent by the clients browsers. This includes an HTML form on a Web page or it could also come from an applet or a custom HTTP client program. Read the implicit HTTP request data sent by the clients browsers. This includes cookies, media types and compression schemes the browser understands, and so forth. Process the data and generate the results. This process may require talking to a database, executing an RMI or CORBA call, invoking a Web service, or computing the response directly. Send the explicit data i. e., thedocument to the clients browsers. This document can be sent in a variety of formats, including text HTMLorXML, binary GIFimages, Excel, etc. Send the implicit HTTP response to the clients browsers. This includes telling the browsers or other clients what type of document is being returned e. g., HTML, setting cookies and caching parameters, and other such tasks. Explain servlet life cycle. A servlet life cycle can be defined as the entire process from its creation till the destruction. The following are the paths followed by a servlet. The servlet is initialized by calling the init method. The servlet calls service method to process a client's request. The servlet is terminated by calling the destroy method. Finally, servlet is garbage collected by the garbage collector of the JVM.

When init method of servlet gets called? The init method is designed to be called only once. It is called when the servlet is first created, and not called again for each user request. So, it is used for one-time initializations, just as with the init method of applets. When service method of servlet gets called? Each time the server receives a request for a servlet, the server spawns a new thread and calls service. The service method checks the HTTP request type GET, POST, PUT, DELETE, etc. and calls doget, dopost, doput, dodelete, etc. methods as appropriate. When doget method of servlet to be called? A GET request results from a normal request for a URL or from an HTML form that has no METHOD specified and it should be handled by doget method. When dopost method of servlet to be called? A POST request results from an HTML form that specifically lists POST as the METHOD and it should be handled by dopost method. When destroy method of servlet gets called? The destroy method is called only once at the end of the life cycle of a servlet. For what purpose init method of a servlet is used? The init method simply creates or loads some data that will be used throughout the life of the servlet. For what purpose destroy method of a servlet is used? This method gives your servlet a chance to close database connections, halt background threads, write cookie lists or hit counts to disk, and perform other such cleanup activities. For what purpose doget method of a servlet is used? This method should be used to get data from server. For what purpose dopost method of a servlet is used? This method should be used to process data on the server. Explain working of service method of a servlet. The service method is the main method to perform the actual task. The servlet container i. e. webserver calls the service method to handle requests coming from the clientbrowsers and to write the formatted response back to the client. Each time the server receives a request for a servlet, the server spawns a new thread and calls service. The service method checks the HTTP request type GET, POST, PUT, DELETE, etc. and calls doget, dopost, doput, dodelete, etc. methods as appropriate. Here is the signature of this method: public void service(servletrequest request, ServletResponse response) throws ServletException, IOException{ } The service method is called by the container and service method invokes doge, dopost, doput, dodelete, etc. methods as appropriate. So you have nothing to do with service method but you override either doget or dopost depending on what type of request you receive from the client. How to read form data in servlet?

Servlets handles form data parsing automatically using the following methods depending on the situation: getparameter: You call request.getparameter method to get the value of a form parameter. getparametervalues: Call this method if the parameter appears more than once and returns multiple values, for example checkbox. getparameternames: Call this method if you want a complete list of all parameters in the current request. How to read name of all parameters in servlet? getparameternames method of HttpServletRequest returns complete list of all parameters in the current request. This method returns an Enumeration that contains the parameter names in an unspecified order. Once we have an Enumeration, we can loop down the Enumeration in the standard manner, using hasmoreelements method to determine when to stop and using nextelement method to get each parameter name. How to read http header information in servlet? We can use getheadernames method of HttpServletRequest to read the HTTP header infromation. This method returns an Enumeration that contains the header information associated with the current HTTP request. Once we have an Enumeration, we can loop down the Enumeration in the standard manner, using hasmoreelements method to determine when to stop and using nextelement method to get each parameter name. What is HTTPServletRequest class? When a browser requests for a web page, it sends lot of information to the web server which can not be read directly because this information travel as a part of header of HTTP request. HTTPServletRequest represents this HTTP Request. What is HTTPServletResponse class? when a Web server responds to a HTTP request to the browser, the response typically consists of a status line, some response headers, a blank line, and the document. HTTPServletResponse represents this HTTP Response. How to write html contents using servlets? Get the object of PrintWriter using request. PrintWriter out = response.getwriter(); Now print html. out.println("hello World"); How to send an authentication error from a servlet? We can use setstatusstatuscode method of HttpServletResponse to send an authentication error. // Set error code and reason. response.senderror(407, "Need authentication!!!" ); How to redirect a request from a servlet to another servlet? 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.

How sendredirect method works? This method generates a 302 response along with a Location header giving the URL of the new document. How senderror method works? This method sends a status code usually404 along with a short message that is automatically formatted inside an HTML document and sent to the client. What are servlets filters? Servlet Filters are Java classes that can be used in Servlet Programming for the following purposes: To intercept requests from a client before they access a resource at back end. To manipulate responses from server before they are sent back to the client. Name some of the servlets filters? There are various types of filters suggested by the specifications: Authentication Filters. Data compression Filters. Encryption Filters. Filters that trigger resource access events. Image Conversion Filters. Logging and Auditing Filters. MIME-TYPE Chain Filters. Tokenizing Filters. XSL/T Filters That Transform XML Content. How to do servlet filter mapping? Filters are deployed in the deployment descriptor file web.xml and then map to either servlet names or URL patterns in your application's deployment descriptor. For what purpose init method of a filter is used? This method is called by the web container to indicate to a filter that it is being placed into service. For what purpose dofilter method of a filter is used? This method is called by the container each time a request/response pair is passed through the chain due to a client request for a resource at the end of the chain. For what purpose destroy method of a filter is used? This method is called by the web container to indicate to a filter that it is being taken out of service. Can multiple filters be configured? Yes. Can filtering be done in an ordered way? If so then how to achieve it? Yes. The order of filter-mapping elements in web.xml determines the order in which the web container applies the filter to the servlet. To reverse the order of the filter, you just need to reverse the filter-mapping elements in the web.xml file.

How to configure a central error handling page in servlets? Use the error-page element in web.xml to specify the invocation of servlets in response to certain exceptions or HTTP status codes. How to configure a central error handler in servlets? If you want to have a generic Error Handler for all the exceptions then you should define following error-page instead of defining separate error-page elements for every exception: <error-page> <exception-type>java.lang.throwable</exception-type > <location>/errorhandler</location> </error-page> What are cookies? Cookies are text files stored on the client computer and they are kept for various information tracking purpose. Java Servlets transparently supports HTTP cookies. How to create a cookie using servlet? Setting cookies with servlet involves three steps: 1 Creating a Cookie object: You call the Cookie constructor with a cookie name and a cookie value, both of which are strings. Cookie cookie = new Cookie("key","value"); Keep in mind, neither the name nor the value should contain white space or any of the following characters: [ ] =, " /? @ : ; 2 Setting the maximum age: You use setmaxage to specify how long inseconds the cookie should be valid. Following would set up a cookie for 24 hours. cookie.setmaxage(60*60*24); 3 Sending the Cookie into the HTTP response headers: You use response.addcookie to add cookies in the HTTP response header as follows: response.addcookie(cookie); How to read a cookie using servlet? To read cookies, you need to create an array of javax.servlet.http.cookie objects by calling the getcookies method of HttpServletRequest. Then cycle through the array, and use getname and getvalue methods to access each cookie and associated value. How to delete a cookie using servlet? To delete cookies is very simple. If you want to delete a cookie then you simply need to follow up following three steps: Read an already exsiting cookie and store it in Cookie object. Set cookie age as zero using setmaxage method to delete an existing cookie. Add this cookie back into response header. What is session? Session provides a way to identify a user across more than one page request or visit to a Web site and to store information about that user. The session persists for a specified time period, across more than one connection or page request from the user. What is URL rewriting?

You can append some extra data on the end of each URL that identifies the session, and the server can associate that session identifier with data it has stored about that session. For example, with http://tutorialspoint.com/file.htm;sessionid=12345, the session identifier is attached as sessionid=12345 which can be accessed at the web server to identify the client. How to create a session in servlet? You would get HttpSession object by calling the public method getsession of HttpServletRequest, as below: // Create a session object if it is already not created. HttpSession session = request.getsession(); How to delete a session in servlet? When you are done with a user's session data, you have several options: Remove a particular attribute: You can call public void removeattributestringname method to delete the value associated with a particular key. Delete the whole session: You can call public void invalidate method to discard an entire session. Setting Session timeout: You can call public void setmaxinactiveintervalintinterval method to set the timeout for a session individually. Log the user out: The servers that support servlets 2.4, you can call logout to log the client out of the Web server and invalidate all sessions belonging to all the users. How to update an attribute in session in servlet? setattributestringname, Objectvalue of HTTPSession object binds an object to this session, using the name specified and can be used to update an attribute in session. How to set session timeout in servlet? setmaxinactiveintervalintinterval of HTTPSession object specifies the time, in seconds, between client requests before the servlet container will invalidate this session. How to set auto page refresh in servlet? The simplest way of refreshing a web page is using method setintheader of response object. What is internalization? This means enabling a web site to provide different versions of content translated into the visitor's language or nationality. What is localization? This means adding resources to a web site to adapt it to a particular geographical or cultural region for example Hindi translation to a web site. What is locale? This is a particular cultural or geographical region. It is usually referred to as a language symbol followed by a country symbol which is separated by an underscore. For example "en_us" represents english locale for US. How to detect locale in Servlets? Following is the method of request object which returns Locale object. java.util.locale request.getlocale() How to get country name in Servlets? Following method returns a name for the locale's country that is appropriate for display to the user.

String getdisplaycountry() What is Next? Further, you can go through your past assignments you have done with the subject and make sure you are able to speak confidently on them. If you are fresher then interviewer does not expect you will answer very complex questions, rather you have to make your basics concepts very strong. Second it really doesn't matter much if you could not answer few questions but it matters that whatever you answered, you must have answered with confidence. So just feel confident during your interview. We at tutorialspoint wish you best luck to have a good interviewer and all the very best for your future endeavor. Cheers :-) Processing math: 100%