Java

Java Servlets Interview Questions

90 questions with answers · Java Interview Guide

Servlet lifecycle, request/response handling, filters, listeners, and session management.

bar_chartQuick stats
Total questions90
High frequency0
With code examples0
1

What is a "deployment descriptor"

Deployment descriptor (web.xml) is an XML file that configures servlets, filters, listeners, security constraints, and other settings for a web application.

2

How container controls the life cycle of the Serlet, when and what methods are called

Container instantiates servlet (constructor), calls init(), then repeatedly calls service() for requests, and finally calls destroy() on shutdown.

3

Why do you need application servers if there are server containers

Application servers provide additional services beyond container functionality: connection pooling, transaction management, JMS messaging, clustering, security, and resource management.

4

What actions need to be done when creating Servlets

Extend HttpServlet, override doGet/doPost/doPut/doDelete as needed, and deploy the compiled class with a mapping in web.xml or @WebServlet annotation.

5

In which case is it required to override the Service () method ()

Override service() only if you need custom request routing or handling logic that differs from standard HTTP method delegation; typically override specific doXxx() methods instead.

6

What is the "Container of the Servmar"

Servlet Container is the runtime environment (like Tomcat, Jetty) that manages servlet lifecycle, handles HTTP requests/responses, and provides threading and resource management.

7

How to implement the launch of the servicema simultaneously with the launch of the application

Use ServletContextListener with contextInitialized() method to initialize services when the application starts up.

8

When to use the Servetov filters, and when are the listeners

Use filters to intercept and modify request/response data; use listeners to react to application lifecycle events like initialization.

9

Why are various listener used in the Servlets

Listeners monitor servlet lifecycle events (initialization, destruction) and session/request events to execute code at specific points.

10

What do you know about the Serpent filters

Servlet filters intercept requests/responses before they reach servlets, enabling cross-cutting concerns like logging, authentication, and compression.

11

What is Servletconfig

ServletConfig holds servlet-specific configuration parameters defined in web.xml, accessible only to that particular servlet.

12

What is ServletContext

ServletContext represents the servlet container environment, accessible to all servlets, and provides shared application resources and attributes.

13

What are the differences of ServletContext and ServletConfig

ServletConfig is servlet-specific with init parameters; ServletContext is application-wide and shared across all servlets.

14

Why do I need the Servletresponse interface

ServletResponse encapsulates the HTTP response, providing methods to set headers, content type, and send data back to the client.

15

What is the Servletrequest interface for

ServletRequest encapsulates the HTTP request, providing access to parameters, headers, session, and request attributes from the client.

16

What is Request Dispatcher

RequestDispatcher forwards or includes requests to other servlets/JSPs within the same application without changing the URL.

17

How to call another Servable from one sergete

Call another servlet using RequestDispatcher.forward() or include() obtained from ServletContext.getRequestDispatcher().

18

What is the difference between Sendredirect () from Forward ()

forward() keeps the original URL and transfers control server-side; sendRedirect() changes the URL and makes the client request a new resource.

19

Why are the attributes of the Servita and how working with them is

Servlet attributes store request-scoped or application-scoped data; access via setAttribute()/getAttribute() on ServletRequest or ServletContext.

20

What are the differences between GenericServlet and HttpServlet

GenericServlet is protocol-agnostic; HttpServlet extends GenericServlet with HTTP-specific methods like doGet(), doPost().

21

Why is httpservlet class declared as an abstract

HttpServlet is abstract to force developers to override specific HTTP method handlers rather than implementing the generic service() method.

22

What are the main methods in the HTTPSERVlet class

Main HTTP methods are doGet(), doPost(), doPut(), doDelete(), doHead(), doOptions(), doTrace() called by service() based on request type.

23

Which HTTP method is not unchanged

TRACE method is typically disabled or unchanged in most implementations, used for debugging request headers across proxies.

24

What are the methods of sending data from the client to the server

GET, POST, PUT, DELETE, HEAD requests through HTML forms, AJAX calls, or direct HTTP requests to the server.

25

What is the difference between Get and Post methods

GET appends parameters to URL (limited size, cached, bookmarkable), POST sends data in request body (larger data, not cached, secure for sensitive info).

26

Is it possible to use Printwriter and ServletoutPutStream simultaneously

No, calling getWriter() and getOutputStream() simultaneously throws IllegalStateException; only one output stream can be active per request.

27

What does the URL Encoding mean, how to do it in Java

URL Encoding converts special characters to %HEX format for safe transmission; use URLEncoder.encode(string, 'UTF-8') in Java.

28

What are the most common tasks performed in the server container

Request processing (parsing, validation, routing), resource management (connection pooling, thread management), session/security handling, and response generation.

29

What are cookies

Cookies are small text files stored on client side, sent with every request, used for session tracking, preferences, and authentication tokens.

30

Why it is necessary to override the only init () method without arguments

Override init() without arguments to leverage container initialization; overriding init(ServletConfig) requires calling super.init(config) to properly initialize the servlet.

31

What is the URL REWRITING

URL Rewriting embeds session ID in URLs as parameter (jsessionid) when cookies are disabled; used as fallback session tracking mechanism.

32

What is a "session"

Session is server-side state storage for each client, persisting data across requests using session ID tracked via cookies or URL rewriting.

33

Does it make sense to determine the constructor for the servlet, which is better to initialize data

No, constructors shouldn't be overridden for initialization; use init() method instead because container controls servlet instantiation and lifecycle.

34

What is an effective way to make sure that all servus are available only for the user with the right session

Implement Filter with session validation, or use ServletFilter to check session validity before delegating to servlets; deny requests without valid session.

35

In which case is it required to override the Service () method ()

Override service() when handling multiple HTTP methods with shared logic; typically implement doGet(), doPost(), etc. instead for method-specific handling.

36

How to organize a database connection, provide journalization in Services

Use connection pooling (HikariCP, Tomcat), initialize in ServletContextListener, store in ServletContext, implement try-with-resources, and use SLF4J/Log4j for logging.

37

What authentication methods are available to the sergete

HTTP Basic Auth (base64 encoded credentials), Form-based Auth (servlet handles login form), Digest Auth (MD5 hashing), and SSL Client Certificate Auth.

38

Why do you need a jSP

JSP simplifies HTML generation by embedding Java in markup, reducing boilerplate servlet code; compiled to servlet automatically by container.

39

Tell me about the stages (phases) of the JSP life cycle.

JSP lifecycle: translation (JSP to servlet), compilation, loading, instantiation, initialization (jspInit), request processing (service), and destruction (jspDestroy).

40

What actions need to be done when creating Servlets

Create a class extending HttpServlet, override doGet/doPost/doPut/doDelete methods, implement init/destroy if needed, and configure in web.xml or use @WebServlet annotation.

41

What methods of the JSP life cycle can be redefined

Only jspInit() and jspDestroy() methods can be redefined; the service method is generated from scriptlets and cannot be overridden.

42

What is a "deployment descriptor"

A deployment descriptor (web.xml) is an XML file defining servlet mappings, filters, listeners, initialization parameters, and security constraints for a web application.

43

What is the difference between the dynamic and static contents of JSP

Dynamic content is generated at runtime based on requests (JSP/servlets), while static content is pre-existing files (HTML, images) served as-is.

44

As a serviceman container controls the life cycle of the Serlet, when and what methods are called

The container calls init() once on startup, service() for each request (which dispatches to doGet/doPost), and destroy() once on shutdown.

45

Why do you need application servers if there are server containers

Application servers provide additional services beyond servlet containers: clustering, transactions, JPA, messaging, security, and dependency injection; containers only handle HTTP requests.

46

What areas of visibility of variables exist in jSP

JSP variable scopes are: page (local to current page), request (across forward/include), session (per user), and application (global to all users).

47

What implicit objects are not available in a regular JSP page

The pageContext implicit object is not available in regular JSP pages; it's only used in JSP tag files and custom tags.

48

How to configure initialization parameters for JSP

Use <init-param> tags in web.xml or @WebInitParam annotation on the @WebServlet, then access via getInitParameter() in servlet.

49

What is the "Container of the Servmar"

A servlet container is a runtime environment that manages servlet lifecycle, handles HTTP requests/responses, and provides JSP compilation and execution.

50

What is the structure of the web project

Web project structure: src/main/java (code), src/main/webapp (static files), WEB-INF (web.xml, libraries), and build output in target directory.

51

What are the advantages of the sergete technology over CGI Common Gateway Interface

Servlets are faster than CGI (no process creation per request), support session management, can access application context, and integrate with containers' resource management.

52

Describe the general practical principles of working with JSP

Use MVC pattern: servlets handle requests, JSP handles presentation, session/request objects for data passing, avoid business logic in JSP.

53

What is the difference between JSPWRITER and the Serpent Printwriter

JspWriter is JSP-specific for writing to output stream with automatic flushing; PrintWriter is generic Java writer without JSP context.

54

Is an object of the session on the JSP page always created, is it possible to turn off its creation

Session objects are created by default; disable with <%@ page session="false" %> directive to reduce memory overhead.

55

Is it possible to use JavaScript on a JSP page

Yes, JavaScript can be embedded directly in JSP pages using <% %> tags or via the Scripting API; JSP is server-side Java that generates HTML/JavaScript.

56

How JSP is configured in the deployment descriptor

Configure JSP servlets in web.xml using <servlet> and <servlet-mapping> tags with jsp-file or explicit JSP servlet declarations; modern apps use annotations (@WebServlet).

57

How errors are processed using JSTL

JSTL uses <c:catch> tag to catch exceptions and store them in a variable, or <c:if> to conditionally handle errors; detailed error handling typically delegates to error pages.

58

How can I process JSP page errors

Configure error handling via try-catch blocks, JSP error pages (<error-page> in web.xml), or exception handling filters; use <c:catch> in JSTL for runtime error capture.

59

Why you do not need to configure standard JSP tags in Web.xml

Standard JSP tags (JSTL) are configured via taglib directives in JSP pages themselves; web.xml configuration is not required since they're part of the servlet specification.

60

How to make lines transfer to HTML by JSP

JSP automatically escapes special HTML characters using &lt;, &gt;, &amp; entities; use expression language ${variable} or JSTL tags, which handle encoding automatically.

61

Describe the general practical principles of working with JSP

Keep JSP for view logic only; use EL/JSTL instead of scriptlets; delegate business logic to servlets/controllers; leverage jsp:include for reusability.

62

What is the difference between JSPWRITER and the Printwriter

JspWriter is request/response buffered output tied to PageContext; PrintWriter is standard Java IO without JSP context.

63

Is an object of the session on the JSP page always created, is it possible to turn off its creation

Session objects are created by default on JSP; disable with <%@ page session="false" %> directive to reduce memory overhead.

64

Is it possible to use JavaScript on a JSP page

Yes, JSP pages can include JavaScript; scripting elements and client-side scripts are fully supported.

65

How JSP is configured in the deployment descriptor

JSP servlets configured via servlet and servlet-mapping elements in web.xml with URL patterns.

66

How errors are processed using JSTL

JSTL error handling via c:catch tag or error-page directive; catches exceptions and stores in pageContext.

67

How can I process JSP page errors

Use error pages via <%@ page errorPage="error.jsp" %> directive or configure <error-page> in web.xml to specify error handlers for different exception types and HTTP status codes.

68

Why you do not need to configure standard JSP tags in Web.xml

Standard JSP tags (JSTL) are built-in and automatically available; they're pre-compiled by container and don't require manual taglib registration in web.xml like custom tags do.

69

How to make lines transfer to HTML by JSP

Use JSP expression <%= value %> to output strings to HTML, or use out.println() in scriptlets; escape HTML special characters using JSTL <c:out> or Apache Commons Lang to prevent XSS.

70

Give an example of using your own tags

Custom JSP tags are created by extending SimpleTag or BodyTagSupport, defined in .tag files or tag classes, then registered in web.xml with <tag> element or via @WebServlet annotation.

71

What do you know about writing user jSP tags

Custom JSP tags are written using Tag classes implementing Tag/BodyTag interfaces or TagSupport, defining doStartTag/doEndTag methods, then registered in TLD files for use in JSP pages.

72

How can JSP functionality expand

JSP functionality expands via custom tag libraries (JSTL, custom tags), include directives, beans, servlets forwarding requests, and expression language (EL).

73

What groups of tags do the JSTL library consist of

JSTL consists of five groups: Core (flow control, variables), Formatting (dates, numbers, localization), SQL (database access), XML (XML processing), Functions (string utilities).

74

What is JSTL, JSP Standard Tag Library

JSTL (JSP Standard Tag Library) is a standard library providing reusable tags for common operations like loops, conditionals, string formatting, and database access without scriptlets.

75

What groups of tags do the JSTL library consist of

JSTL consists of five tag groups: Core, Formatting, SQL, XML, and Functions tags for control flow, formatting, database access, XML processing, and string manipulation.

76

What is JSTL, JSP Standard Tag Library

JSTL (JSP Standard Tag Library) is a collection of custom tags that provide common functionality like iteration, conditionals, and formatting in JSP pages without scriptlets.

77

Dike the implicit, internal objects of JSP EL and their differences from JSP objects

EL implicit objects (pageScope, requestScope, sessionScope, applicationScope, param, paramValues, header, headerValues, cookie, initParam) provide access to request/response data; JSP objects are scriptlet variables like request, response, session obtained directly.

78

What types of EL operators know

EL operators: arithmetic (+, -, *, /, %), comparison (==, !=, <, >, <=, >=), logical (&&, ||, !), relational (instanceof), and ternary (? :).

79

What do you know about the language of JSP, JSP Expression Language - EL

EL (Expression Language) is a simple scripting language in JSP/Servlets for accessing data and invoking methods using ${expression} syntax; supports property access, collections, operators, and implicit objects.

80

Is it possible to determine the class inside the JSP page

Yes, you can access the class using getClass() or reflection APIs in JSP, typically through request/response objects or scriptlet code, though it's better practice to handle this in servlets.

81

Why is it not recommended to use science, script elements, in jSP

Scriptlets (< % %>) in JSP are hard to maintain, debug, and test; prefer MVC pattern with servlets for logic and JSP for view layer only.

82

What are the advantages of the sergete technology over CGI Common Gateway Interface

Servlets are more efficient than CGI as they run in process, reuse threads, have persistent connections, and eliminate process creation overhead for each request.

83

What is the structure of the web project

A typical web project structure includes src/, WebContent/, WEB-INF/, web.xml (deployment descriptor), lib/ for dependencies, and jsp/ for views.

84

What is the "Container of the Servlets"

Servlet container is a runtime environment that loads, instantiates, and manages servlet lifecycles, handling HTTP requests/responses and resource management.

85

Why do you need application servers if there are server containers

Application servers provide additional features beyond servlet containers: transaction management, EJB support, clustering, security, and enterprise services.

86

As a serviceman container controls the life cycle of the Serlet, when and what methods are called

Container calls init() once on startup, then service() for each request (which delegates to doGet/doPost/etc.), and destroy() on shutdown.

87

What is a "deployment descriptor"

Deployment descriptor (web.xml) is an XML file in WEB-INF/ that configures servlets, mappings, filters, listeners, security constraints, and application parameters.

88

What actions need to be done when creating Servlets

Create a class extending HttpServlet, override doGet() and/or doPost() methods, implement request/response logic, then configure servlet mapping in web.xml.

89

In which case is it required to override the service() method

Override service() method when you need custom logic before/after HTTP method handling or to handle custom HTTP methods beyond GET/POST/PUT/DELETE.

90

Does it make sense to determine the constructor for the servlet

No, servlet constructors are called for every instantiation but shouldn't be used; use init() instead as it's called once and receives ServletConfig parameters.

Knowing the answers is half the battle

The other half is explaining them clearly under pressure.

Try a free mock interviewarrow_forward

More Java topics