Java EE - Interview Questions

Java Servlets

Following are some frequently asked questions in Java Servlets


What are Servlets?

FAQKey Concept

Servlets are Java technology based components that generate dynamic content, and are considered to be the core building blocks of Java based web applications.

Servlets are contained within and managed by containers, called ‘servlet engines’ or ‘servlet containers’ or ‘web containers’, which are extensions to web servers.

Servlets interact with clients through a request and response model that the servlet container implements. A servlet processes the request sent from the client via the servlet container and generates dynamic content that is sent back to the client via the servlet container.


What is a servlet container?

FAQKey Concept

A servlet container is part of a web server that contains and manages servlets through their lifecycle.

In addition to managing servlets, the servlet container provides the network services over which the request to and responses from the servlet are sent.

The servlet container also performs other functions such as mapping requests to servlets, decoding requests to the servlet and formatting responses that are send back from the servlet.

Servlet containers support HTTP and HTTPS as protocols for requests and responses.


What is the difference between Web Server, Web Container and Application Server?

FAQKey Concept

Web Server - A web server processes HTTP Requests from web clients and responds back with Http Responses. A web server can process and respond to HTTP requests for static content, but it cannot process requests for dynamic content by itself.

Apache Http Server and IBM Http Server are examples of commonly used Web Servers.

Web Container - In Java based web applications the dynamic content is processed by servlets that run in a ‘web container’, also called as ‘servlet container’. Web servers utilize web containers to respond to requests for dynamic data.

A web container implements the Java Servlet specification (including JSP and JSTL). The servlet container contains and manages servlets through their lifecycle.

Apache Tomcat and Jetty are example of web/servlet containers.

Application Server - An application server contains the web container or implements the Servlet API, contains the EJB container which manages EJBs, and implements the complete Java EE specification – JMS, JTA, JNDI, JAX-RPC, JavaMail etc.

Unlike web servers, which support only Http protocol, application servers supports various protocols such as Http, TCP/IP, IIOP, RMI, JRMP etc.

The application server provides various scalability and fault-tolerance techniques, resource pooling, component life cycle management, transaction management, messaging, security etc.

IBM Websphere, Weblogic and JBoss are some of the commonly used Application servers.


Describe the steps in the HTTP Request and Response flow from a Servlet?

FAQKey Concept

The request from a web client to a server for a resource, the processing of that request by the server, and returning of the corresponding response from the server to the web client - goes through a well-defined flow.

Following are the key steps in this flow.

1. A web client accesses a web server via a browser and makes a request for a resource via the HTTP protocol.

2. The web server receives the request, and checks if the resource requested is static (HTML pages, Text files, Images etc.) or dynamic (Servlet, JSP etc.)

3.If the requested resource is static, the web server accesses the resource and returns it to the client as a response via the HTTP protocol. The static resources such as HTML files, Image files, Text files etc. are usually hosted on the web server’s publicly accessible folder system.

4. If the resource requested is dynamic, the web container forwards the request to the servlet container for further processing.

5.The servlet container determines which servlet to invoke based on the servlet mapping defined in the application’s configuration file, and calls the service() method of the servlet. The servlet container passes objects representing the request and response as arguments to the service() method of the servlet.

6.The servlet used the request object to access the parameters sent by web client, performs the program logic, generates the dynamic content and sets it within the response object.

7.After the service() method completes, the web container sends back the response with the dynamic content back to the web server.

8. The web server sends the response with the dynamic content to the client via HTTP protocol.


What are the key packages defined in the Servlet API?

Key Concept

The Servlet API consists of two key packages – ‘javax.servlet’ and ‘javax.servlet.http

Two other packages ‘javax.servlet.annotation’ and ‘javax.servlet.descriptor’ were introduced in version 3.0 of the API to provide annotation functionality and aggregation.

Javax.servlet - The javax.servlet package contains a number of classes and interfaces that describe and define the contracts between a servlet class and the runtime environment provided for an instance of such a class by a conforming servlet container.

Javax.servlet.http - The javax.servlet.http package contains a number of classes and interfaces that describe and define the contracts between a servlet class running under the HTTP protocol and the runtime environment provided for an instance of such a class by a conforming servlet container.

Javax.servlet.annotation - The javax.servlet.annotation package contains a number of annotations that allow users to use annotations to declare servlets, filters, listeners and specify the metadata for the declared component.

Javax.servlet.descriptor - The Javax.servlet.descriptor packageProvides programmatic access to a web application's configuration information that was aggregated from the web.xml and web-fragment.xml descriptors.


What are the key interfaces and classes defined in javax.servlet package?

Key Concept

Following are the interfaces and classes defined in javax.servlet package.

Interfaces - Servlet, Filter, ServletRequest, ServletResponse, ServletContext, ServletConfig, RequestDispatcher

Classes - GenericServlet, ServletInputStream, ServletOutputStream


What are the key interfaces and classes defined in javax.servlet.http package?

Key Concept

Following are the interfaces and classes defined in javax.servlet.http package.

Interfaces - HttpSession, HttpServletRequest, HttpServletResponse

Classes - HttpServlet, Cookie


What are the life cycle methods that are defined in the Servlet API?

FAQKey Concept

The lifecycle methods specified in the Servlet API are the init(), service() and destroy() methods of the Servlet interface that all servlets implement either directly or indirectly through the GenericServlet and HttpServlet abstract classes.


What is the difference between Servlet, GenericServlet and HttpServlet?

FAQ

Servlet - The Servlet interface is the base interface defined in the Java Servlet API that every servlet has to implement. Servlet interface defines the life-cycle methods of a servlet - to initialize a servlet, to service requests, and to remove a servlet from service.

Every servlet implements this interface either directly, or more commonly, by extending a class that implements this interface.

GenericServlet - GenericServlet, which implements Servlet interface defines a generic protocol-independent servlet. A servlet can directly extend GenericServlet, though it’s more common to extend a protocol-specific subclass such as HttpServlet.

HttpServlet - HttpServlet extends from GenericServlet and provides HTTP protocol specific functionality.


What are the handler methods defined in the HttpServlet class?

FAQKey Concept

HttpServlet overrides the service() method to handle HTTP requests and dispatch them to one of the doXXX() handler methods depending on the Http request type (GET, POST, PUT, DELETE, HEAD, OPTIONS, TRACE).

Following are the seven doXXX() methods that the request is dispatched to from the service() method.

doGet() – Handles Http GET requests

doPost() – Handles Http POST requests

doPut() – Handles Http PUT requests

doDelete() – Handles Http DELETE requests

doHead() – Handles Http HEAD requests

doOptions() – Handles Http OPTIONS requests

doTrace() – Handles Http TRACE requests


How does a servlet handle multiple requests?

FAQKey Concept

By default, the servlet container instantiates only one instance of a servlet per JVM. The servlet container sends multiple concurrent requests to the service() method of the servlet to process, via a separate thread for each request. Hence the service() method and the servlet has to be designed to be thread safe for concurrent processing with multiple threads.


How do you make a servlet single threaded?

FAQKey Concept

A servlet can be forced to handle only one thread at a time by implementing SingleThreadModel. In this case, the servlet container creates a new instance of the servlet for each request thread.

When a servlet implements SingleThreadModel, the servlet container guarantees that only one thread at a time accesses the service method. The servlet container does this by either serializing access to the service method or by maintaining a pool of servlet instances.

Due to performance impacts, implementing SingleThreadModel is not recommended. SingleThreadModel interface is deprecated since Servlet API version 3.0


What is the difference between Request attributes and Request parameters?

FAQKey Concept

Request Parameters - Request parameters are extra information sent from the client to the servlet container as part of its request. For HTTP servlets, request parameters are contained either in the URI query string or POST form data. The servlet container sets these parameter into an HttpServletRequest object and passes this object as an argument to the servlet’s service() method.

Request Attributes - Request Attributes are objects associated with a request. Attributes can be set by the servlet container to make custom information available about a request, or can be set programatically by a servlet to communicate information to another servlet.


How does servlets process files send from clients?

FAQKey Concept

Files can be send to the servlet container for processing by requests that are of type Multipart/form-data.

HttpServletRequest defines following methods for handling Multipart data.

getParts() - Gets all the Part components of this request, provided that it is of type multipart/form-data. If this request is of type multipart/form-data, but does not contain any Part components, the returned collection will be empty.

getPart(String name) - Gets the Part with the given name. The Part with the given name, or null if this request is of type multipart/form-data, but does not contain the requested Part.


How do servlets read the body of requests as streams?

FAQKeyConcept

The ServletRequest interface defines the following methods to read the body of the request as a stream.

getInputStream() - Retrieves the body of the request as binary data using a ServletInputStream object.

getReader() - Retrieves the body of the request as character data using a BufferedReader object. The reader translates the character data according to the character encoding used on the body.


How do servlets get more information about client?

FAQKeyConcept

The ServletRequest interface defines the following methods to get more information about the client or the last proxy that send the request.

getRemoteAddr() - Returns the Internet Protocol (IP) address of the client or last proxy that sent the request.

getRemoteHost() - Returns the fully qualified name of the client or the last proxy that sent the request.

getRemotePort() - Returns the Internet Protocol (IP) source port of the client or last proxy that sent the request.

HttpServletRequest interface that extends from ServletRequest interface inherits above methods.


How do you get Http headers from a client request using Servlet API?

FAQ

The HttpServletRequest interface defines the following methods to access the headers of an HTTP request.

getHeader() - Returns the value of the specified request header as a String.

getHeaders() - Returns all the values of the specified request header as an Enumeration of String objects.

getHeaderNames() - Returns an enumeration of all the header names this request contains.

getIntHeader() - Returns the value of the specified request header as an int.

getDateHeader() - Returns the value of the specified request header as a long value that represents a Date object.


How do you get session information associated with a client request?

FAQKey Concept

The HttpServletRequest interface defines a number of methods to get more information about the session that is associated with the request.

Out of these methods, following methods are important and are frequently used.

getSession() - Returns the current session associated with this request, or if the request does not have a session, creates one.

getSession(boolean create) - Returns the current HttpSession object associated with this request or, if there is no current session and create is true, returns a new session. If create is false and the request has no valid HttpSession, this method returns null.


How do you check if the client request is transmitted via a secure protocol such as HTTPS using Servlet API?

FAQKey Concept

A servlet can check if a request has been transmitted over a secure protocol, such as HTTPs, by calling the isSecure() method of the ServletRequest interface.


How do you authenticate a client request using Servlet API?

FAQKey Concept

The ServletRequest interface defined in Servlet API provides the following methods for authentication.

authenticate() - Uses the container's login mechanism configured for the ServletContext to authenticate the user making this request.

getAuthType() - Returns the name of the authentication scheme used to protect the servlet.

getUserPrincipal() - Returns a java.security.Principal object containing the name of the current authenticated user.

isUserInRole() - Returns a boolean indicating whether the authenticated user is included in the specified logical role.

login() - Validate the provided username and password in the password validation realm used by the web container login mechanism configured for the ServletContext.

logout() - Establish null as the value returned when getUserPrincipal(), getRemoteUser(), and getAuthType() is called on the request.


What is the difference between ServletRequest.getRequestDispatcher() and ServletContext.getRequestDispatcher?

FAQKey Concept

ServletContext.getRequestDispatcher() method takes a String argument describing a path within the scope of the ServletContext. This path must be relative to the root of the ServletContext and begin with a ‘/’, or be empty.

ServletRequest.getRequestDispatcher() method takes a String argument describing a path relative to the path of the current request.


What is the difference between include() and forward() methods defined in RequestDispatcher interface?

FAQKey Concept

include() - The include() method defined in RequestDispatcher interface sets the contents of a resource (servlet, JSP page, HTML file) in the response. Basically, this method enables programmatic server-side includes.

forward() The forward() method defined in RequestDispatcher interface forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server. This method allows one servlet to do preliminary processing of a request and another resource to generate the response.


What is difference between ServletResponse.sendRedirect() and RequestDispatcher.forward() method?

FAQKey Concept

Following are the key differences between RequestDispatcher.forward() and ServletResponse.sendRedirect() methods.

1. RequestDispatcher.forward() sends the request from one resource (servlet or JSP) to another resource via the servlet container. ServletResponse.sendRedirect() sends the request to another resource via the browser

2. RequestDispatcher.forward() sends the request from one resource to another resource within the same domain and context. ServletResponse.sendRedirect() sends the request to another resource that may be on a different domain or server.

2. RequestDispatcher.forward() preserves the request and response object and sends them to the new resource. ServletResponse.sendRedirect() does not preserve the request and response objects. These are not send to the new resource.

3. RequestDispatcher.forward() method is not transparent to the client. The URL on the browser does not change. RequestDispatcher.forward() method is transparent to the client. This is a new request from the browser and the browser URL changes.

4. RequestDispatcher.forward() is faster than ServletResponse.sendRedirect()


How do you set the response text in servlet to send to the client?

FAQ

You can use ServletResponse object to send the response text back to the client.

The ServletResponse interface defines following two methods that return streams which can be used to set content to send back to the client.

getOutputStream() - Returns a ServletOutputStream object which is suitable for writing binary data.

getWriter() - Returns a PrintWriter object which is suitable for writing character data to the response.


How do you set the buffer size of response send to the client?

FAQKey Concept

The servlet container usually buffers output going to the client to increase efficiency. The servlet container allows servlet to specify buffering parameters.

The ServletResponse interface provides the following method that allow the servlet to set buffering information.

setBufferSize() – Sets the buffer size. This method must be called before content is written using a ServletOutputStream and writer.


How do you set headers on HTTP response from a servlet to the client?

FAQ

You can set HTTP headers on the response to the client by calling the setHeader() method on HttpServletResponse interface.


How do you set HTTP status codes on HTTP response from a servlet to the client?

FAQ

You can set HTTP headers on the response to the client by calling the setHeader() method on HttpServletResponse interface.


JavaServer Pages

Following are some frequently asked questions in JavaServer Pages


Question?

FAQ

Answer


JavaServer Faces

Following are some frequently asked questions in JavaServer Faces


What is JavaServer Faces technology?

FAQ

JavaServer Faces technology is a server-side component framework for building Java technology based web applications. JavaServer Faces technology is built on top of Java Servlet technology and provides a well-defined programming model API and various tag libraries.

The JavaServer Faces API is used for represents components and managing their state, server-side validation, event handling, data conversion, defining page navigation and for supporting internationalization

JavaServer Faces technology provides Tag Libraries for adding components to web pages and for connecting components to server-side objects.


What are the benefits of JavaServer Faces technology?

FAQ

JavaServer Faces technology provides a clean separation of presentation and behavior for Java technology based web applications.

JavaServer Faces leverages existing Java based server technologies. JavaServer Faces technology is built on top the familiar Java Servlet technology.

JavaServer Faces technology does not force you to use a particular scripting technology or markup language. You can use existing Java scripting languages such as JSTL.


Describe the user interface component model of JavaServer Faces technology?

FAQ

Java ServerFaces components form the building blocks of a JavaServerFaces view. A component may be a UI component or a non-UI component.

JavaServer Faces's component architecture provides the following features.

Component Behavior - A set of javax.faces.component.UIComponent classes for specifying the state and behavior of UI components.

Component Rendering - A rendering model that defines how to render the components in various ways

Conversion Model - A conversion model that defines how to register data converters onto a component

Event and Listener ModelAn event and listener model that defines how to handle component events.

Validation Model - A validation model that defines how to register validators onto a component


Describe the component rendering model in JavaServer Faces technology?

FAQ

JavaServer Faces technology architecture separates component functional logic from its rendering logic by delegating the rendering functionality to separate renderer classes and packaging them in a render kit.

A render kit defines how component classes map to component tags that are appropriate for a particular client.

The render kit defines a set of javax.faces.render.Renderer classes for each component that it supports. Each Renderer class defines a different way to render the particular component to the output defined by the render kit.


Describe the component conversion model in JavaServer Faces technology?

FAQ

JavaServer Faces technology architecture provides the option of linking a component to a managed Java bean object. The application sets and gets the data on the Java bean object

When a component is bound to a Java bean, then the component has two views.

1. The model view,in which data is represented with primitive data types such as int or double.

2. The presentation view, in which the data is formatted to render to the clievet view.

The JavaServer Faces implementation automatically converts the component's data between these two views.


Describe the navigation model of JavaServer Faces technology?

FAQ

JavaServer Faces technology provides a flexible navigation model which makes it easy to define the sequence in which the pages are loaded.

User defined navigation rules can be defined in one or more application configuraton resoirce files.


Describe the event and listener model of JavaServer Faces technology?

FAQ

The JavaServer Faces event and listener model has strongly typed event and listener interfaces that an application can use to handle events generated by components.

The JavaServer Faces defines three kinds of events - application events, system events, data-model events

Application Events - Application events are tied to a application and are generated by component of type UIComponent

System Events - System events are generated by Java objects of type Object and not by UIComponent and apply to the entire application rather than to a specific component.

Data-model event - A data model event occurs when a new row of a UIData component is selected.


Describe the validation model of JavaServer Faces technology?

FAQ

The JavaServer Faces technology provides a mechanism of validating data of editable components such as text fields and text areas.

The JavaServer Faces technology provides a set of in-built standard classes that perform common data validation checks.

A validator can be registered on a component by nesting the validator's tag within the components tag.


Describe the lifecycle of a JavaServer Faces application?

FAQ

A standard JavaServer Faces application goes through the following sequence of events

1. Restore View - Builds view of the page, wires event handlers and validators to components of the view, saves the view in FacesContext instance.

2. Apply Request values - In this phase the components of the tree view are updated with their new values from the request.

3. Process validations - In this phase, all validation registered on the components are processed.

4. Update model values -

6. Invoke Application -

10. Render Response


What are Facelets?

FAQ

Facelets, a part of JavaServer Faces technology, is the preferred presentation technology for building JavaServer Faces technology based web applications. Facelets is a lightweight page declaration language that is used to build JavaServer Faces views and to build component trees.


How do you configure a Facelets application in a web deployment descriptor?

FAQ

A JavaServer Faces application has to be configured in two locations.

1. Map the JavaFaces servlet in web deployment desc.

2. Add bean definitions, navigation rules and resource bundle declarations to application configuration resource file faces-config.xml.

<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>

What are Facelet Templates?

FAQ

The JavaServer Faces technology provides templates that act as a base or template for other pages.

Templating enables code reuse, enables a constant look and feel for the application and prevents construction of multiple similar pages.


What are composite components in JavaServer Faces technology?

FAQ

The JavaServer Faces technology provides templates that act as a base or template for other pages.

Templating enables code reuse, enables a constant look and feel for the application and prevents construction of multiple similar pages.


What are the two standard tag libraries used by JavaServer Faces web page?

FAQ

The JavServer Faces web pages refer to following two standard tag libraries.

1. The JavaServer Faces HTML render kit tag library - this tag library defines tags that represent common HTML user interface components.

2. The JavaServer Faces core tag library - this library defines tags that represent core actions


List some common tags defined in the JavaServer Faces render kit tag library?

FAQ

The JavServer Faces web pages refer to following two standard tag libraries.

1. The JavaServer Faces HTML render kit tag library - this tag library defines tags that represent common HTML user interface components.

2. The JavaServer Faces core tag library - this library defines tags that represent core actions


List some common tags defined in the JavaServer Faces core tag library?

FAQ

The JavServer Faces web pages refer to following two standard tag libraries.

1. The JavaServer Faces HTML render kit tag library - this tag library defines tags that represent common HTML user interface components.

2. The JavaServer Faces core tag library - this library defines tags that represent core actions


How do you use Ajax with JavaServer Faces technology?

FAQ

The JavServer Faces web pages refer to following two standard tag libraries.

1. The JavaServer Faces HTML render kit tag library - this tag library defines tags that represent common HTML user interface components.

2. The JavaServer Faces core tag library - this library defines tags that represent core actions


Java API for XML Processing (JAXP)

Following are some frequently asked questions in Java API for XML Processing (JAXP)


What is the JAXP API?

FAQ

JAXP - Java API for XML processing - is an API provided in Java SE that is used for parsing XML documents using Java programming language. JAXP supports XML parser standards - Simple API for XML Parsing (SAX), Document Object Model (DOM) and Streaming API for XML (StAX).

JAXP also supports 'Extensible Stylesheet Language Transformation (XSTL)' that can be used to convert the XML data to other XML documents as well as other formats such as HTML.


What is SAX parser? How is it supported in the JAXP API

FAQ

Simple API for XML (SAX) parser processes the XML document element-by-element. SAX parser is event driven and uses serial-access mechanism to process the XML document.

javax.xml.parsers package in Java SE provides the SAX specific APIs.


What is DOM parser? How is it supported in the JAXP API

FAQ

Document Object Model (DOM) parser processes an XML document into a tree structure of objects and stores the entire object model to memory. Once the object model is stored in memory, it can be traversed, accessed and manipulated by a Java program.

javax.xml.parsers package in Java SE provides the DOM specific APIs.


What is StAX parser? How is it supported in the JAXP API

FAQ

Streaming API for XML (StAX) parser processes an XML document element-by-element and is based on Java streaming.

javax.xml.stream package in Java SE provides the StAX specific APIs.

StAX has a simpler programming model compaed to SAX, and is more memory efficient compared to DOM.


What are the key classes and interfaces defined in the JAXP API that supports SAX parsers?

FAQ

The JAXP API provides the following classes and interfaces for processing XML documents using a SAX parser.

SAXParserFactory - SAXParserFactory creates an instance of SAXParser.

SAXParser - SAXParser interface defines overloaded parse() methods. Generally you pass the source XML document and an handler object that implements the interface DefaultHandler to the parse() method.

SAXReader - SAXReader is wrapped by the SAXParser. SAXReader is used for readinmg the XML document and communicating with the SAX event handlers.

ContentHandler - ContentHandler interface defines methods such as startDocument, endDocument, startElement, endElement which are invoked when an XML element is processed.

ErrorHandler - ErrorHandler interface defines the methods error(), fatalError() and warning() which are invoked when the parser encounters error while parsing the XML document.

DTDHandler - DTDHandler defines methods that are used for processing a DTD document.

DefaultHandler - DefaultHandler class implements the ContentHandler, ErrorHandler, DTDHandler, and EntityResolver interfaces. You generally extend DefaultHandler and override only the appropriate methods.


Java API for JSON Processing (JSON-P)

Following are some frequently asked questions in Java API for JSON Processing (JSON-P)


What is the role of JSON-P API in Java EE?

FAQ

The Java API for JSON Processing (JSON-P) enables Java EE applications to parse, transform, and query JSON data using either the Object model or the Streaming model.

JSON is a text-based data exchange format derived from JavaScript that is used in Web Services and other connected applications.

JSON-P is introduced in the Java EE 7 platform.


What are the two programming models used for generating and parsing JSON data?

FAQ

There are two programming models used for generating and parsing JSON data. Object model and Streaming model.

The Object model creates a tree structure in memory that represents the JSON data. The tree can then be navigated, analyzed, or modified.

The Streaming model uses an event-based parser that reads JSON data one element at a time. Each element can be processed or discarded by the application code, and then the parser proceeds to the next event.

The parser generates events and stops for processing when an object or an array begins or ends, when it finds a key, or when it finds a value.


What are the key packages provided in the JSON-P API?

FAQ

The JSON-P API provides the following key packages to generate and parse JSON data.

javax.json - This package contains interfaces and classes for generation and parsing JSON data using Object model.

javax.json.stream - This package contains interfaces and classes for generating and parsing JSON data using Streaming model.


What are the key classes and interfaces provided in javax.json package?

FAQ

javax.json package contains the following key classes and interfaces to generate and parse JSON objects using the object model.

Json - Contains static methods to create instances of JSON parsers, builders and generators.

JsonReader - Reads JSON data as stream and create an object model in memory.

JsonObjectBuilder - Creates object model in memory by adding elements through application code.

JsonWriter - Writes an object model from memory to a stream.


What are the key classes and interfaces provided in javax.json.stream package?

FAQ

javax.json.stream package contains the following key classes and interfaces to generate and parse JSON objects using the stream model.

JsonParser - Event based parser that can read JSON data from a stream.

JsonGenerator - Generates JSON data to a stream, one element at a time.


How do you create a JSON object model from JSON data using JSON-P API?

FAQ

You can create an object model using JSON data using following steps

1. Create an instance of JsonReader class from the Json utility class and pass the JSON data file as a parameter.

2. Call read() method on the reader instance which returns the JSON object model.

JsonReader reader = Json.createReader(new FileReader('jsondata.txt'));
JsonStructure jsons = reader.read();

How do you create a JSON object model from application code using JSON-P API?

FAQ

You can create a JSON object model using application code using following steps

1. Create an instance of JsonObject class using the Json utility class.

Add key value pairs, objects or arrays to the instance of JsonObject.

JsonObject modelObject = Json.createObjectBuilder();
modelObject.add('firstName', 'Java');
modelObject.add('lastName', 'Guru');
modelObject.add('city', 'San Francisco');
modelObject.build();

How do you write a JSON object model to a stream using JSON-P API?

FAQ

You can output a JSON object model to a stream by following steps.

1. Create an instance of JsonWriter by using the Json utility class.

2. Call the method writeObject() on the instance of JsonWriter and pass the instance of JSON model as a parameter.

StringWriter writer = new StringWriter();
JsonWriter jsonWriter = Json.createWriter(writer);
jsonWriter.writeObject(model);
jsonWriter.close();

//print the json data
String jsonData = stWriter.toString();
System.out.println(jsonData);

Java Message Service API (JMS)

Following are some frequently asked questions in Java Message Service API (JMS)


What is messaging? How is it different compared to other means of communication

FAQ

Messaging is a means of data exchange between software applications or components. The sending application sends messages to a destination and the recipient application retrieves the messages from the destination.

Unlike most other means of communication, messaging is loosely coupled. The sending application sends messages to a destination and does not know anything about the receiving application. The receiving application retrieves the message from the destination and does not know anything about the sending application.

The sender and receiver need not be available at the same time to successfully exchange messages. For example, the sending application can continue to send messages to the destination even when the receiving application is not available. When the receiving application becomes available again, it can retrieve the messages from the destination.


What is JMS API?

FAQ

Java Message Service is a Java API that enables software applications or components written in Java programming language to communicate with messaging implementations.

JMS makes it easier for a programmer to develop messaging applications by providing high level interfaces and components to create, send, receive and read messages.

JMS API provides a standard for JMS product implementors ensuring the portability of JMS applications across different JMS providers.


What are key benefits of JMS?

FAQ

Loosely Coupled - Messaging is loosely coupled. The sending application sends messages to a destination and does not know anything about the receiving application. The receiving application retrieves messages from the destination and does not know anything about the sending application.

Asynchronous - Messaging is asynchronous. The sending application and receiving application need not be available at the same time. The sending application can send the message and continue processing its other tasks. The receiving application can retrieve the messages at a later time.

Reliable - Any messaging product that implements JMS API ensures that messages are delivered once and only once. Lower levels of reliability can be set if it is ok for an application to either miss messages or receive duplicate messages.


What messaging styles does JMS API support?

FAQ

JMS supports two messaging styles - point-to-point and publish-subscribe.

Point-to-Point - In point-to-point messaging, the sending application sends messages to a destination from which only one receiving application can consume the messages. The destination to which messages are send to is known as a queue.

Publish-Subscribe - In publish-subscribe messaging the sending application sends messages to a destination from which messages can be consumed by multiple different receiving applications. The destination to which publish-subscribe style messages are send to is known as a topic.


What are the differences between queues and topics?

FAQ

Queues are the destination in point-to-point messaging. Sending application sends messages to the queue and receiving application retrieves messages from the queue. Only a single receiving application can retrieve messages from the queue.

Topics are destinations in publish-subscribe messaging. Sending application sends messages to the topic and receiving application retrieves messages from the topic. Multiple receiving applications can subscribe to the same topic. Hence the same message for the topic can be send to multiple receiving application.


What are the key components of JMS API?

FAQ

Following are the key components of a JMS application.

Connection Factory - Connection factory is an object provided in the JMS API that is used to create a connection to the destination queue or topic. A connection factory is an instance of ConnectionFactory, QueueConnectionFactory or TopicConnectionFactory interfaces provided by the JMS API. Connection factory is an administered object in a JMS API implementor such as a Java EE server.

Connection - A connection represents a virtual connection to the JMS provider. Connection is created from the connection factory object through a JMSContext object.

Session - A session is s single threaded context for producing and consuming messages. Similar to a connection, session is created from connection factory by creating a JMSContext object.

JMSContext object - A JMSContext object encapsulates a connection and a session and is created from the connection factory. JMSContext is used to create message producers, message consumers and messages.

Message Producer - A message producer is an object used for sending messages to a destination. Message producer implements the JMSProducer interface provided the the JMS API. A message producer is created from the JMS context object.

Message Consumers - A message consumer is an object used from consuming messages from a destination. A message consumer implements the JMSConsumer interface provided by JMS API. A message consumer is created from the JMS context object.

Message - Message contains the data that the sending application sends to a destination or the data that a receiving application retrieves from.


How is JMS connection factory created in a JMS application?


JMS connection factory is an administered object and is injected into the JMS application code using its JNDI name.


How are JMS destinations created or referenced to in a JMS application?


JMS destinations i.e. queues and topics, are administered object and are injected into the JMS application code using its JNDI name.


What role does JMSContext object perform in a JMS program?


JMSContext object encapsulates the connection and session required to connect to a JMS provider

JMSContext is created from the connection factory by calling its createContext() method.

JMSContext object is used to create message producer by calling its createProducer(). JMSContext object is used to create message consumer by calling its createConsumer() method.


What role does JMSProducer object perform in a JMS program?


JMSProducer object is used to send messages to a destination. JMSProducer object is created from a JMSContext object by calling its createProducer() method.


What role does JMSConsumer object perform in a JMS program?


JMSConsumer object is used to retrieve messages from a destination. JMSConsumer object is created from a JMSContext object by calling its createConsumer() method.


What role do message listeners perform in a JMS program?


A message listener acts an asynchronous event handler for consuming messages. A message listener implements MessageListener interface and overwrites its onMessage() method.

The message listener is registered to a message consumer by calling its setMessageListener() method.

Once a message listener is registered to a message consumer, the JMS provider automatically sends any messages put on the destination to the listeners onMessage() method.


What are the different parts of a JMS message?


A JMS message has three different parts - Header, Properties and Body.

Header - A JMS message header contains a number of pre-defined header fields that are used to identify and route messages. Some examples of header fields are destination, delivery mode, delivery time, priority and expiration time of the message.

Properties - In addition to the fields defined in the header, you can create and set additional fields if needed in the properties section of the message.

Body - JMS message body contains the actual data of the message that is send to the destination by the sender and retrieved by the receiver. The message body can contain messages of six different types - text, map, bytes, stream, object and message which is used when no data is required to be send.


What are the different message types supported by JMS API?


JMS API supports six different types of messages.

Text Message - Message containing text of type java.lang.String

Map Message - Message containg key-value pairs. Key is of type java.lang.String and value is any of the primitive data types defined in Java programming language.

Bytes Message - Message containing a stream of bytes

Stream Message - Message containing a stream of primitive data types.

Object Message - Message containing a serializable Java object.

Message - Does not contain a message body. Used when only header and properties are required ti be send.


What are the key exceptions in JMS API?


The root class for all checked exceptions in JMS API is JMSException

The root cause of all unchecked exceptions in JMS API is JMSRuntimeException.


How do you make messages persistent or non-persistent in JMS API?


A message can be set to be persistent or non-persistent by calling the setDeliveryMode() method on the JMSProducer interface and setting the mode to be persistent or non-persistent.


How do you set message priorities in JMS API?


Priority of a message can be set by calling the setPriority() method on the JMSProducer interface and setting the priority value. The priority value can range from 0 to 9, 0 being the lowest and 9 the highest.


How do you set message expiration time in JMS API?


A message can be set to expire after a certain period of time. You can set the expiration time by calling the setTimeToLive() method on the JMSProducer interface and setting the expiration time.


Java Persistance API (JPA)

Following are some frequently asked questions in Java Persistance API (JPA)


What is the role of Java Persistance API (JPA) in Java EE?

FAQ

The Java Persistance API (JPA) provides the capability of object relational mapping for managing relational data in Java applications.

The Java Persistance API provides features for mapping relational data to Java objects or entities, managing the entities, querying the entities and also in creating the database schema.


What are Entity classes in JPA? What are the requirements for an Entity class?

FAQ

An Entity class is a lightweight persistence class, that is typically mapped to a relational table. An Entity class is decorated with the annotation javax.persistence.Entity. Each Entity class instance corresponds to a row in a relational table.

Fields or properties in an entity class are mapped to the relational data by decorating them with annotations.


What are the requirements for an Entity class?

FAQ

An Entity class must follow the following requirements.

  • The class must be annotated with the javax.persistence.Entity annotation.
  • The class must have a public or protected no-argument constructor
  • The Entity class, it's methods and persistent variables should not be declared final.
  • The persistent instance variables must be declared as private, protected or default (package-private). They can only be accessed through accessor methods.
  • The Entity class must implement the Serializable interface if it's instance needs to be passed as value.
  • Entities can extend from either another Entity class or a Non-Entity class.

@Entity
public class Order { ... }

What is the annotation used for persistence fields of type Collection in an Entity class?

FAQ

Persistent fields in an Entity class which are of type Collection are annotated with the javax.persistence.ElementCollection annotation.

@Entity
public class Order {
 @ElementCollection
 protected List orderLines = new ArrayList<>();
}

For persistent fields of type collection, how do you specify if the collection elements have to be loaded eagerly or lazily?

FAQ

The javax.persistence.ElementCollection has an attribute fetch which can be specified with two values either 'LAZY' or 'EAGER'

//Load order lines eagerly
@Entity
public class Order {
 @ElementCollection(fetch=EAGER)
 protected List orderLines = new ArrayList<>();
}

How do you define a simple primary key in a JPA Entity class?

FAQ

You can define a field as a primary key in an Entity class by annotating the field with javax.persistence.id annotation.

@Entity
public class Order {
 @id
 protected String orderId
}

How do you define a composite primary key in a JPA Entity class?

FAQ

Composite primary key consists of more than one attribute, which corresponds to a set of single persistent properties or fields.

Composite primary keys must be defined in a primary key class.

Composite primary keys are annotated using the javax.persistence.EmbeddedId and javax.persistence.IdClass annotations.


What are the different kinds of multiplicity relationships between JPA Entity classes?

FAQ

There are four multiplicity relationships between JPA Entity classes.

1. One-to-one - Each instance of an entity is related to a single instance of another entity. One-to-one relationships use the javax.persistence.OneToOne annotation on the corresponding persistent property or field.

2. One-to-many - Each instance of an entity is related to multiple instances of another entity. One-to-many relationships use the javax.persistence.OneToMany annotation on the corresponding persistent property or field.

3. Many-to-one - Multiple instances of an entity are related to a single instance of another entity. Many-to-one relationships use the javax.persistence.ManyToOne annotation on the corresponding persistent property or field.

4. Many-to-Many - Multiple instances of an entity are related to multiple instances of another entity. Many-to-many relationships use the javax.persistence.ManyToMany annotation on the corresponding persistent property or field.


What are the different kinds of directional relationships between JPA Entity classes?

FAQ

There are two kinds of directional relationships between JPA entity classes.

Bidirectional - In a bidirectional relation ship, each entity has a field or property that refers to the other entity.

Unidirectional - In a unidirectional entity, only one entity has a field or property that refers to the pother entity.


What are the different kinds of cascade operations applicable for relationships between JPA Entity classes?

FAQ

Cascade operations defines the dependency of an entity object on the existence of another entity object, where there is a dependency between the two objects.

There are six different types of cascade operations.

1. DETACH - Is parent entity is detached from the persistence context, then the related entity will also be detached.

2. MERGE - If the parent entity is merged into the persistence context, then the related entity will also be merged.

3. PERSIST - If the parent entity is persisted into the persistence context, then the related entity will also be persisted.

4. REFRESH - If the parent entity is refreshed in the persistence context, then the related entity will also be refreshed.

5. REMOVE - If the parent entity is removed from the persistence context then the related entity will also be removed.

6. ALL - All the cascade operations will be applied to the parent entity's related entity.

@OneToMany(cascade=REMOVE)
public List getOrdersLines() { return ordersLines; }

What are JPA Embedded classes?

FAQ

Embedded classes represent part of the state of an entity, but do not have a persistent identity of their own. Entity classes are annotated with the javax.persistence.Embeddable annotation.

@Entity
public class Person {
 @Id
 protected long id
 protected String fname;
 protected String lname;
 @Embedded
 protected Address address;
 ...
}

Java Transaction API (JTA)

Following are some frequently asked questions in Java Transaction API (JTA)


What are transactions in Java EE Application?

FAQ

Transactions in Java EE application are a series of actions that all must be completed successfully, or else the changes in each action are backed out. If all the actions are successful then the changes from all actions are committed. If any one of the actions is unsuccessful then the changes from all the actions are rolled back.


What is JTA (Java Transaction API) in Java EE?

FAQ

Java Transaction API is an API specified in Java EE that provides applications a standard way to access transactions independent of any specific implementation. JTA transactions are controlled by Java EE transaction manager. Transaction are started, committed or rolled back by calling corresponding methods on the UserTransaction API.


How are transactions maintained in an EJB application?

FAQ

Transactions in EJB application are either Container-Managed or Bean-Managed

Container-Managed Transactions - In Container-Managed transactions the transaction boundaries are set in the EJB container. Container-managed transactions can be set for both session beans as well as message-driven beans.

Bean-Managed Transactions - In Bean-Managed transactions the transaction boundaries are set specifically within the bean's code. Bean managed transactions can be set for session beans as well as message-driven beans. Bean manages transaction can either use JDBC transactions or JTA transactions.


What are transaction attributes in Container-Managed transactions?

FAQ

Transaction attribute determines the scope of a transaction across beans. For example, if methodA() of Bean A starts a transaction and calls methodB() of bean b, then does methodB() run within the transaction started by methodA()? This is determined by the transaction attribute set on methodB()

A transaction attribute can have one of the following values -

1. Required

2. RequiresNew

3. Mandatory

4. NotSupported

5. Supports

6. Never


What is 'Required' transaction attribute that can be defined in Container-Managed transactions?

FAQ

If a client has an associated transaction and calls a container-managed bean's method then the method executes within the client transaction.

If the client is not associated with a transaction then the container starts a new transaction before calling the bean's method.


What is 'RequiresNew' transaction attribute that can be defined in Container-Managed transactions?

FAQ

If a client has an associated transaction and calls a container-managed bean's method then the container suspends the clients transaction, starts a new transaction, starts the call to the method and starts the clients transaction after method completes.

If the client is not associated with a transaction then the container starts a new transaction before calling the beans method.


What is 'Mandatory' transaction attribute that can be defined in Container-Managed transactions?

FAQ

If a client has an associated transaction and calls a container-managed bean's method then the method executes within the client transaction.

If a client is not associated with a transaction then the container throws a TransactionRequiredException


What is 'NotSupported' transaction attribute that can be defined in Container-Managed transactions?

FAQ

If a client has an associated transaction and calls a container-managed bean's method then the container suspends the clients transaction, calls the bean's method, and starts the clients transaction after method execution completes.

If a client is not associated with a transaction, then the container does not start a new transaction before calling the bean's method.


What is 'Supports' transaction attribute that can be defined in Container-Managed transactions?

FAQ

If a client has an associated transaction and calls a container-managed bean's method then the method executes within the client transaction.

If a client is not associated with a transaction, then the container does not start a new transaction before calling the bean's method.


What is the Never transaction attribute that can be defined in Container-Managed transactions?

FAQ

If a client has an associated transaction and calls a container-managed bean's method then the container throws a RemoteException.

If a client is not associated with a transaction, then the container does not start a new transaction before calling the bean's method.


How do you set transaction timeouts in container-managed and bean-managed transactions?

FAQ

Container-Managed Transaction - In container managed transactions the transaction timeout is set at the container's administration console.

Bean-Managed Transactions - In Bean-managed transactions, the transaction timeout is set by calling the setTransactionTimeout() method of the UserTransaction interface.


JAX-WS

Following are some frequently asked questions in JAX-WS


What are the APIs provided in Java EE to support web services?

FAQ

Java EE provides two different APIs JAX-WS and JAX-RS to support web services.

JAX-WS - Java EE provides the JAX-WS (Java API for XML Web Services) for building web services and clients for SOAP/XML based Web Services.

JAX-RS - Java EE provides the JAX-RS (Java API for RESTful Web Services) for building web services and clients for RESTful Web Services


What are the key advantages of JAX-WS API that is provided in Java EE?

FAQ

Java EE provides the JAX-WS API to support Web Services that use XML-based protocols such as SOAP.

The JAX-WS API hides the complexity of SOAP messages and protocol from the developer. The JAX-WS API converts the API calls or requests to the corresponding SAOP messages, hence the developer does not have to generate or parse the SOAP messages programmatically.

JAX-WS uses the standard W3C technologies HTTP, SOAP and WSDL. A JAX-WS client can access a web service that is not running on Java platform and vice versa.


What are service endpoint interfaces and service endpoint implementations?

FAQ

A service endpoint interface is a Java interface that declares the methods that a client can invoke on the web service. A service endpoint implementation is a class that implements the methods defined in the service endpoint interface.


What are key annotations used in a JAX-WS service endpoint implementation?

FAQ

Following are the key annotations used in a JAX-WS service endpoint implementation.

@WebService - A Java class is annotated as a JAX-WS web service endpoint using the @WebService annotation.

@WebMethod - A Java method is exposed to Web Service clients using the @WebMethod annotation.

import javax.jws.WebService;
import javax.jws.WebMethod;

@WebService
public class OrderService {

 public OrderService() { ... }

 @WebMethod
 public String getOrder(String orderNumber) { ... }
}

What are the key requirements of a JAX-WS Web Service endpoint?

FAQ

JAX-RS endpoints have to follow certain requirements.

  • The implementing class must be annotated with either the @WebService or the @WebServiceProvider annotation.
  • The implementing classs must not be declared final.
  • The implementing class must not be declared abstract.
  • The implementing class must not define the finalize method.
  • Methods which are exposed to Web Service clients must be annotated with @WebMethod annotation.

  • How does the conversion happen between Java objects and XML documents in JAX-WS API?

    FAQ

    The JAX-WS API leverages the JAXB API and tools as the binding technology for mapping between Java objects and XML documents.


    What are the two approaches to developing JAX-RS Web Services?

    FAQ

    JAX-RS Web Services can be developed via either of the following approaches.

    1. Develop a JAX-RS Web Service from a WSDL (Top-Down Development) - In this approach the JAX-RS Web Service is created from an existing WSDL file using JavaBeans. The base Web Service endpoint classes and interfaces are generated via the 'wsimport' tool provided in the JAX-RS API.

    2. Develop a JAX-WS Web service from a JavaBean (bottom-up development) - In this approach the JAX-WS Web Service endpoint interfaces and classes are created first using annotations. After the Web Service endpoint interfaces and classes are created, the WSDL file is generated by using the 'wsgen' tool provided in the JAX-RS API.


    Java API for RESTful Web Services (JAX-RS)

    Following are some frequently asked questions in Java API for RESTful Web Services (JAX-RS)


    What do you understand by REST?


    REST, which stands for 'Representational State Transfer', is a client-server architecture style of transferring representations of resources through requests and responses.

    Following are the key attributes of REST architectural style.

    1. Data and functionality are considered as REST resources.

    2. REST Resources are accessed using URIs (Uniform Resource Identifiers), which are usually web links.

    3. REST resources are represented by documents. Example - XML document, JSON document, HTML page, Image file etc.

    4. REST Resources can be retrieved and updated using simple well-defined operations.


    What are RESTful web services?

    FAQ

    RESTful web services are simple, lightweight and loosely coupled web services used for creating APIs to REST resources, and are well suited for clients on the internet.

    Following are the key principles of RESTful web services which make them lightweight and fast.

    1. Resource access through URIs - A RESTful web service exposes a set of REST resources through URIs which are standard links on the Internet.

    2. Stateless - RESTful web services are stateless and designed to be used with a stateless protocol, usually HTTP.

    3. Uniform interface - A RESTful web service provides a standard set of four operations to create, read, update and delete resources - GET, PUT, POST and DELETE. These correspond to the GET, PUT, POST and DELETE methods of the HTTP protocol.

    4. Multiple document formats - Resources are decoupled from their representation. So the same content can be accessed in a variety of formats such as XML, JSON, PDF, JPEG etc.


    Describe the key features of JAX-RS API that is provided in Java EE?

    FAQ

    JAX-RS is a set of Java APIs, provided in Java EE, that are used for the development of RESTful web services.

    Following are the key features of the JAX-RS API.

    1. POJO-based API - The JAX-RS API provides a set of annotations and corresponding classes and interfaces that can be used with POJOs to expose them as web services.

    2. HTTP-based API - The JAX-RS API is designed for HTTP as the base protocol. The API supports HTTP usage patters and provides mapping between HTTP actions and corresponding API classes and annotations.

    3. Format Independent - The JAX-RS API is applicable to a wide variety of HTTP entity body content types.

    4. Container Independent - JAX-RS applications can be deployed in a Java EE container, Servlet container or can be plugged in as a JAX-WS provider.


    What are the key annotations provided in the JAX-RS API?

    FAQ

    The JAX-RS API provides a set of annotations and its corresponding classes and interfaces that can be used on POJOs to expose them as RESTful web services.

    Following are some key annotations defined in the JAX-RS API

    @Path - @path annotation defines the relative URI path for the RESTful resource.

    @GET - The @GET annotation is a request method designator. A Java method that is designated with this annotation will process HTTP GET requests.

    @POST - The @POST annotation is a request method designator. A Java method that is designated with this annotation will process HTTP POST requests.

    @PUT - The @PUT annotation is a request method designator. A Java method that is designated with this annotation will process HTTP PUT requests.

    @DELETE - The @DELETE annotation is a request method designator. A Java method that is designated with this annotation will process HTTP DELETE requests.

    @HEAD - The @HEAD annotation is a request method designator. A Java method that is designated with this annotation will process HTTP HEAD requests.

    @PathParam - The @PathParam annotation is the URI path parameter that you can extract and use in your resource class.

    @QueryParam - The @QueryParam annotation is the URI query parameters that you can extract and use in your resource class.


    What are RESTful Root Resource Classes in JAX-RS API?

    FAQ

    Root Resource classes are POJOs (Plain Old Java Objects) that are either annotated with @Path - or have at least one method annotated with @Path or a request method designator such as @GET, @POST, @PUT, @DELETE etc.

    import javax.ws.rs.Path;

    /**
    * Root resource (exposed at 'service' path)
    */
    @Path('service')
    public class OrderService { ... }

    What are request method designator annotations in JAX-RS API?

    FAQ

    Request method designator annotations are the runtime annotations @GET, @PUT, @POST, @DELETE and @HEAD, defined in the JAX-RS API, that can be applied to Java methods. Request method designator annotations correspond to the corresponding HTTP request methods GET, PUT, POST, DELETE and HEAD.

    import javax.ws.rs.Path;

    /**
    * Root resource (exposed at 'myservice' path)
    */
    @Path('myservice')
    public class OrderService {

     @GET
     public String getOrder() {...} 
    }

    What is the role of @path annotation in JAX-RS API?

    FAQ

    The @Path annotation identifies the URI path template to which the resource responds and is specified at the class or method level of a resource.

    URI path templates are URIs with variables embedded within the URI text.

    import javax.ws.rs.Path;

    /**
    * Root resource (exposed at '/orders/' path)
    */
    @Path('/orders/{orderNumber}')
    public class OrderService {

     @GET
     public String getOrder() {...} 
    }

    What is the role of @Produces annotation in JAX-RS API?

    FAQ

    The @Produces annotation specifies the MIME media types or representations that a resource can produce and send back to the client.

    If @Produces is applied at the class level, all the methods in a resource can produce the specified MIME types by default. If applied at the method level, the annotation overrides any @Produces annotations applied at the class level.

    If no methods in a resource are able to produce the MIME type in a client request, the JAX-RS runtime sends back an HTTP '406 Not Acceptable' error.

    import javax.ws.rs.Path;

    /**
    * Root resource (exposed at '/orders/' path)
    */
    @Path('/orders/{orderNumber}')
    public class OrderService {

     @GET
     @Produces('text/xml')
     public String getOrder() {...} 
    }

    What is the role of @Consumes annotation in JAX-RS API?

    FAQ

    The @Consumes annotation is used to specify which MIME media types of representations a resource can accept, or consume, from the client. If @Consumes is applied at the class level, all the response methods accept the specified MIME types by default. If applied at the method level, @Consumes overrides any @Consumes annotations applied at the class level.

    If a resource is unable to consume the MIME type of a client request, the JAX-RS runtime sends back an HTTP 415 ('Unsupported Media Type') error.

    The value of @Consumes is an array of String of acceptable MIME types, or a comma-separated list of MediaType constants.


    What are the key steps to create a client request using JAX-RS API?

    FAQ

    The JAX-RS API provides a high-level API for accessing JAX-RS services as well as other REST services. The JAX-RS Client API is defined in the javax.ws.rs.client package.

    Following are the key steps to create a client request.

    1. Obtain an instance of the javax.ws.rs.client.Client interface. The client instance can be created calling newClient() method javax.ws.rs.client.Client class.

    2. Configure the client with the target URI to call. This is done by calling the target() method on the client instance and passing the target URI as a parameter.

    3. Create a request based on the target URI and set the required attributes such as media type.

    4. Call the request by invoking one of the request methods on the target service.


    How do you set message headers in client request using JAX-RS API?

    FAQ

    You can set HTTP headers on the request by calling the header() method on the client target.


    How do you set cookies in client request using JAX-RS API?

    FAQ

    You can add HTTP cookies to the request by calling the cookie() method on the client target, which takes a name-value pair as parameters.


    How do you set filters in client request or response using JAX-RS API?

    FAQ

    You can register custom filters with the client request or the response received from the target resource. To register filter classes when the Client instance is created, call the Client.register method.

    You can also register the filter classes on the target by calling WebTarget.register.


    How do you make asynchronous client request calls using JAX-RS API?

    FAQ

    In the JAX-RS Client API, the Invocation.Builder.async() method is used when constructing a client request to indicate that the call to the service should be performed asynchronously. An asynchronous invocation returns control to the caller immediately, with a return type of java.util.concurrent.Future and with the type set to the return type of the service call. Future objects have methods to check if the asynchronous call has been completed, to retrieve the final result, to cancel the invocation, and to check if the invocation has been canceled.


    How do you configure JAX-RS applications?

    FAQ

    A JAX-RS application consists of resource classes that are packaged within a war file. There are two ways to configure a JAX-RS application

    1. By using the @ApplicationPath annotation in a subclass of javax.ws.rs.core.Application packaged within the WAR.

    2. By using the servlet-mapping tag within the WAR's web.xml deployment descriptor.


    Java Database Connectivity API (JDBC)

    Following are some frequently asked questions in Java Database Connectivity API (JDBC)


    Question?

    FAQ

    Answer


    Security

    Java and JEE Security is a key and a complex topic that spans across multiple knowledge areas. Hence, most candidates find it difficult to prepare for, as well as answer confidently, interview questions on security.

    Following are some frequently asked questions in Security


    What is declarative and programmatic security?

    FAQ

    Declarative Security - Declarative security specifies an application's security requirements by using either deployment descriptors or annotations.

    Programmatic Security - Programmatic security implements an application's security within the application code.


    What are the key characteristics of application security?

    FAQ

    Following are the key characteristics of application security.

    Authentication - Authentication is the means by which a user or client proves to a server that it is authorized to access a specific resource and vice-versa.

    Authorization - Authorization is the means by which a server determines if a user has permissions to access a specific resource or data.

    Data Integrity - Data integrity means that the data that is exchanged by a client and server is not modified by an unauthorized third party.

    Confidentiality or Data privacy - This ensures that information is send to only those users or clients that are authorized to access the data.

    Non-repudiation - This means that you can prove that a transaction or action has occurred. So a user who has performed a certain action, cannot deny doing so.


    What are some of the security features and APIs provided in Java SE?

    FAQ

    Java Authentication and Authorization Service (JAAS) - Java SE provides the JAAS API which enable services to authenticate and enforce access controls. JAAS forms the underlying and base technology for Java EE security mechanisms.

    Java Generic Security Services (JGSS) - Java SE provides the JGSS API which is used to securely exchange messages between applications by using tokens.

    Java Cryptography Extension (JCE) - Java SE provides the JCE API which provides a framework and implementation for encryption, key generation and key agreement.

    Java Secure Sockets Extension (JSSE) - Java SE provides the JSSE API which provides a framework and an implementation for a Java version of the Secure Sockets Layer (SSL) and Transport Layer Security (TLS) protocols. JSSE includes functionality for data encryption, server authentication, message integrity, and optional client authentication to enable secure Internet communications.

    Simple Authentication and Security Layer (SASL) - SASL is an Internet standard that specifies a protocol for authentication and optional establishment of a security layer between client and server applications.

    Java SE also provides a set of tools for managing keystores, certificates, and policy files; generating and verifying JAR signatures; and obtaining, listing, and managing Kerberos tickets.


    What are some of the security mechanisms provided in Java EE?

    FAQ

    Java EE provides three different security mechanisms based on the layer at which the security has to be applied.

    Application-Layer Security - In Java EE applications, the application-layer security is provided by the component containers.

    Transport-Layer Security - Transport-Layer security is provided by the transport mechanism used to transmit data between the client and server. Java EE application relies on the secure HTTPS protocol using Secure Sockets Layer (SSL).

    Message-Layer Security - Message-Layer security secures the SOAP messages that are exchanged between client and server using XML web services.


    What are Realms, Users, Groups and Roles?

    FAQ

    Realms - Realms are security domains or protection spaces setup for web or application servers. Each realm has its own authentication scheme and contains a collection of Users and Groups.

    Users - Users are individual or application entities defined in an identity store that access the application resources.

    Group - Groups are abstratct entities defined in Java EE that contains a set of users having common traits.

    Roles - Roles are are abstratct entities defined in Java EE that has permissions to access a set of secured resources in an application. Users or Groups are mapped to Roles.


    How do you secure web applications?

    FAQ

    Java web applications can be secured by either declarative security or programmatic security. Declarative security can be setup either in the deployment descriptor or via annotations.


    What are security constraints in Web applications?

    FAQ

    Security constraints define access privileges to a collection of web resources using their URL mappings.

    If an application uses servlets, the security constraint can be set by using the annotations @HttpConstraint and @HttpMethodConstraint within the annotation @ServletSecurity.

    If an application does not use servlets, the security constraint can be set using <security-constraint> element in the deployment descriptor.

    <security-constraint> contains the following sub-elements. <web-resource-collection>, <auth-constraint>, and <user-data-constraint>.

    <security-constraint>
     <web-resource-collection>
      <web-resource-name>employee</web-resource-name>
      <url-pattern>/secure/employee/*</url-pattern>
     </web-resource-collection>
     <auth-constraint>
      <role-name>MANAGER</role-name>
     </auth-constraint>
     <user-data-constraint>
      <transport-guarantee>CONFIDENTIAL</transport-guarantee>
     </user-data-constraint>
    </security-constraint>

    What are the authentication mechanisms used to secure web applications?

    FAQ

    Http Basic authentication

    Form-based authentication

    Digest authentication


    How do you specify the authentication mechanism in web applications declaratively?

    FAQ

    Authentication mechanism for a web application can be defined using the element in web.xml deployment . The sub-element configures the authentication mechanism and its value can be BASIC, DIGEST, FORM or CLIENT-CERT.

    The sub-element indicates the realm name to use when the basic authentication scheme is chosen for the web application.

    The sub-element specifies the login and error pages that should be used when form-based login is specified.


     FORM
     
      /login.html
      /error.html
     

    How do you specify security roles in web applications declaratively?

    FAQ

    The element contains the element which specifies the role that has access to this protected resource.

    You can use the element to define roles that are used in the application. These roles can also be used to map to users and groups defined in the application server.


     manager

    How do you specify the authentication mechanism in web applications programmatically?

    FAQ

    Sometimes declarative security alone is not sufficient to specify the complete security requirements of an application. Programmatic security is used in addition to declarative security in such cases.

    HttpServletRequest interface provides following methods that can be used to authenticate users for a web application.

    authenticate

    login

    logout


    How do you declare security roles in web applications?

    FAQ


    How do you secure an enterprise bean programmatically?

    FAQ


    How do you secure an enterprise bean declaratively?

    FAQ


    What are digital certificates? How are they used for securing applications?

    FAQ


    What are Server certificates? How are they used to secure applications?

    FAQ


    What is the Keystore tool used for?

    FAQ


    Client Authentication?

    FAQ


    Mutual Authentication?

    FAQ


    Mutual Authentication?

    FAQ



     
    Ad
    LEARN HOW TO EARN PASSIVE INCOME AND SIDE INCOME.

    Hundreds of people are transitioning out of their full-time jobs every day by creating businesses that they are passioniate about.

    You can be the next. Click below to learn more.

Subscribe to our Newsletter

Ad
EARN SIDE INCOME

Earn income using your skills and hobbies that you are passioniate about.

Earn Side Income with Photos
Earn Side Income with Writing
Ad
FINANCIAL INDEPENDENCE

Transition out of you full-time job by creating businesses that you are passioniate about.