0% found this document useful (0 votes)
13 views48 pages

Java Full Stack Ans

Uploaded by

cgchitrika
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views48 pages

Java Full Stack Ans

Uploaded by

cgchitrika
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Five Mark Questions:

1. Explain about Lambda expression and its uses?


• It provides a clear and concise way to represent one method
interface using an expression.
• It is very useful in collection library. It helps to iterate, filter and
extract data from collection.
• The Lambda expression is used to provide the implementation
of an interface which has functional interface. It saves a lot of
code.
• In case of lambda expression, we don't need to define the
method again for providing the implementation.
• Java lambda expression is treated as a function, so compiler
does not create .class file
Functional Interface
• Lambda expression provides implementation of functional interface.
• An interface which has only one abstract method is called functional
interface.
• Java provides an anotation @FunctionalInterface, which is used to
declare an interface as functional interface.
Why use Lambda Expression

1. To provide the implementation of Functional interface.


2. Less coding.
• Java Lambda Expression Syntax
(argument-list) -> {body}
• Java lambda expression is consisted of three components.
1) Argument-list: It can be empty or non-empty as well.
2) Arrow-token: It is used to link arguments-list and body of
expression.
3) Body: It contains expressions and statements for lambda
expression.
Example:
import [Link];
public class Main {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<Integer>();
[Link](5);
[Link](9);
[Link](8);
[Link](1);
[Link]( (n) -> { [Link](n); } );
}
}

2)Explain JSP implicit objects.


• There are 9 jsp implicit objects. These objects are created by the web
container that are available to all the jsp pages.
• The available implicit objects are out, request, config, session,
application etc
JSP out implicit object:
• For writing any data to the buffer, JSP provides an implicit object
named out. It is the object of JspWriter. In case of servlet you need to
write:
• PrintWriter out=[Link](); Example of out implicit object
• In this example we are simply displaying date and time.
[Link]
<html>
<body>
<% [Link]("Today is:"+[Link]().getTime()); %>
</body>
</html>
JSP request implicit object:
• The JSP request is an implicit object of type HttpServletRequest i.e.
created for each jsp request by the web container. It can be used to get
request information such as parameter, header information, remote
address, server name, server port, content type, character encoding etc.
• It can also be used to set, get and remove attributes from the jsp request
scope.
• Example of JSP request implicit object
• [Link]
<form action="[Link]">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
• [Link]
<%
String name=[Link]("uname");
[Link]("welcome "+name);
%>

JSP response implicit object


• In JSP, response is an implicit object of type HttpServletResponse.
The instance of HttpServletResponse is created by the web container for
each jsp request.
• It can be used to add or manipulate response such as redirect response
to another resource, send error etc.
• Example of response implicit object
• [Link]
<form action="[Link]">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
• [Link]
<%
[Link]("[Link]
%>

JSP config implicit object:


• In JSP, config is an implicit object of type ServletConfig. This object can
be used to get initialization parameter for a particular JSP page. The
config object is created by the web container for each jsp page.
• Generally, it is used to get initialization parameter from the [Link] file.
• Example of config implicit object:
• [Link]
<form action="welcome">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
JSP application implicit object
• In JSP, application is an implicit object of type ServletContext.
• The instance of ServletContext is created only once by the web container
when application or project is deployed on the server.
• This object can be used to get initialization parameter from
configuaration file ([Link]). It can also be used to get, set or remove
attribute from the application scope.
• This initialization parameter can be used by all jsp pages.
• Example of application implicit object:
• [Link]
<form action="welcome">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
session implicit object:
• In JSP, session is an implicit object of type [Link] Java
developer can use this object to set,get or remove attribute or to get
session [Link] of session implicit object
• [Link]
<html>
<body>
<form action="[Link]">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>
pageContext implicit object:
• In JSP, pageContext is an implicit object of type PageContext [Link]
pageContext object can be used to set,get or remove attribute from one
of the following scopes:page
• request
• session
• application
• In JSP, page scope is the default [Link] of pageContext implicit
object
[Link]
<html>
<body>
<form action="[Link]">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>
page implicit object:
• In JSP, page is an implicit object of type Object [Link] object is
assigned to the reference of auto generated servlet class. It is written
as:Object page=this;For using this object it must be cast to Servlet
[Link] example:<% (HttpServlet)[Link]("message"); %>Since, it is of
type Object it is less used because you can use this object directly in
[Link] example:<% [Link]("message"); %>
exception implicit object:
• In JSP, exception is an implicit object of type [Link]
class. This object can be used to print the exception. But it can only be
used in error [Link] is better to learn it after page directive. Let's see a
simple example:Example of exception implicit object:
• [Link]
<%@ page isErrorPage="true" %>
<html>
<body>

Sorry following exception occured:<%= exception %>

</body>
</html>

3.)Outline the hibernate properties.


4) Difference between Spring framework and Spring Boot:
5. Illustrate Serialization and Deserialization with an example?

• Serialization in Java is a mechanism of writing the state of an object into


a byte-stream. It is mainly used in Hibernate, RMI, JPA, EJB and JMS
technologies.
• The reverse operation of serialization is called deserialization where
byte-stream is converted into an object. The serialization and
deserialization process is platform-independent, it means you can
serialize an object on one platform and deserialize it on a different
platform.
.
Exp 1 for example:
6. Describe HQL and HCQL and its advantages.

HQL
• Hibernate Query Language (HQL) is same as SQL (Structured Query
Language) but it doesn't depends on the table of the database.
• Instead of table name, use class name in HQL. So it is database
independent query language.
Advantage of HQL
• database independent
• supports polymorphic queries
• easy to learn for Java Programmer
HCQL
• The Hibernate Criteria Query Language (HCQL) is used to fetch the
records based on the specific criteria. The Criteria interface provides
methods to apply criteria such as retreiving all the records of table
whose salary is greater than 50000 etc.
Advantage of HCQL
• The HCQL provides methods to add criteria, so it is easy for the java
programmer to add criteria. The java programmer is able to add many
criteria on a query.
Describe the terms Dependency Injection and IOC
Dependency Injection:

• Dependency injection (DI) is a process whereby objects define their

dependencies (that is, the other objects with which they work) only through

constructor arguments, arguments to a factory method, or properties that are set

on the object instance after it is constructed or returned from a factory method.

• helps in decreasing coupling and dependency between classes, so that the

program becomes maintainable and reusable. makes testing easier.

IOC – Inversion of Control


• a design principle that allows classes to be loosely coupled and,
therefore, easier to test and maintain. IoC refers to transferring the
control of objects and their dependencies from the main program to a
container or framework. IoC is a principle, not a design pattern – the
implementation details depend on the developer.
• Thus, IOC makes the code loosely coupled. In such case, there is no need
to modify the code if our logic is moved to new environment.
• In Spring framework, IOC container is responsible to inject the
dependency. We provide metadata to the IOC container either by XML
file or annotation.
Advantage of Dependency Injection
• makes the code loosely coupled so easy to maintain
• makes the code easy to test
8. Illustrate three different types of wild cards in generic method

• Unbounded Wildcards (<?>): Accept any type.


• Upper Bounded Wildcards (<? extends T>): Accept T and its subclasses.
• Lower Bounded Wildcards (<? super T>): Accept T and its superclasses.

These wildcards make generic methods more flexible and allow for a wider range of
operations while maintaining type safety.
9. Explain about JSP action tags.
• There are many JSP action tags or elements. Each JSP action tag is
used to perform some specific tasks.
• The action tags are used to control the flow between pages and to
use Java Bean

10. Describe the I/O classes in java.


• Java I/O (Input and Output) is used to process the input and produce the
output.
• Java uses the concept of a stream to make I/O operation fast. The [Link]
package contains all the classes required for input and output
operations.
• A stream can be defined as a sequence of data. There are two kinds of
Streams −
• InPutStream − The InputStream is used to read data from a source.
• OutPutStream − The OutputStream is used for writing data to a
destination.
• Byte Streams
• Java byte streams are used to perform input and output of 8-bit bytes.
Though there are many classes related to byte streams but the most
frequently used classes are, FileInputStream and FileOutputStream.
• Character Streams
• Java Byte streams are used to perform input and output of 8-bit bytes,
whereas Java Character streams are used to perform input and output
for 16-bit unicode. Though there are many classes related to character
streams but the most frequently used classes
are, FileReader and FileWriter. Though internally FileReader uses
FileInputStream and FileWriter uses FileOutputStream but here the
major difference is that FileReader reads two bytes at a time and
FileWriter writes two bytes at a time
OutputStream
• Java application uses an output stream to write data to a destination; it
may be a file, an array, peripheral device or socket.
InputStream
• Java application uses an input stream to read data from a source; it may
be a file, an array, peripheral device or socket.
11. Discuss various HTTP request methods used in URI.
12. Outline JPQL and its features.
• an object-oriented query language which is used to perform
database operations on persistent entities.
• Instead of database table, JPQL uses entity object model to operate the
SQL queries. Here, the role of JPA is to transform JPQL into SQL. Thus, it
provides an easy platform for developers to handle SQL tasks.
• JPQL is an extension of Entity JavaBeans Query Language (EJBQL)
• It can perform join operations.
• It can update and delete data in a bulk.
• It can perform aggregate function with sorting and grouping clauses.
• Single and multiple value result types
JPQL Features:
• It is a platform-independent query language.
• It is simple and robust.
• It can be used with any type of database such as MySQL, Oracle.
• JPQL queries can be declared statically into metadata or can also be
dynamically built in code.
11.)Illustrate Collection and collection framework.
• provides an architecture to store and manipulate the group of
objects.
• achieve all the operations that you perform on a data such as
searching, sorting, insertion, manipulation, and deletion.
• Java Collection means a single unit of objects. Java Collection
framework provides many interfaces (Set, List, Queue, Deque) and
classes (ArrayList, Vector,LinkedList,PriorityQueue, HashSet,
LinkedHashSet, TreeSet).

• Collection represents a single unit of objects, i.e., a group.


• framework - provides readymade architecture.
- represents a set of classes and interfaces.
• The Collection framework represents a unified architecture for storing
and manipulating a group of objects.
• It has:
• Interfaces and its implementations, i.e., classes
• Algorithm
• The [Link] package contains all the classes and interfaces for the
Collection framework.

[Link] the Servlet Life Cycle and its architecture


• 1) Servlet class is loaded
• The classloader is responsible to load the servlet class. The servlet class
is loaded when the first request for the servlet is received by the web
container.
• 2) Servlet instance is created
• The web container creates the instance of a servlet after loading the
servlet class. The servlet instance is created only once in the servlet life
cycle.
• 3) init method is invoked
• The web container calls the init method only once after creating the
servlet instance. The init method is used to initialize the servlet. It is the
life cycle method of the [Link] interface. Syntax of the init
method is given below:
• public void init(ServletConfig config) throws ServletException
• 4) service method is invoked
• The web container calls the service method each time when request for
the servlet is received. If servlet is not initialized, it follows the first three
steps as described above then calls the service method. If servlet is
initialized, it calls the service method. Notice that servlet is initialized
only once. The syntax of the service method of the Servlet interface is
given below:
• public void service(ServletRequest request, ServletResponse response)
• throws ServletException, IOException
• 5) destroy method is invoked
• The web container calls the destroy method before removing the servlet
instance from the service. It gives the servlet an opportunity to clean up
any resource for example memory, thread etc. The syntax of the destroy
method of the Servlet interface is given below:
• public void destroy()
15.)Illustrate JPA architecture and its units, advantages.
JPA architecture:

advantages.
• No need to create SQL statements
• Reduces the burden of interacting with the database
• user programming becomes easy
• Cost of creating the definition file is reduced
• Using different implementations
jpaunits

16. Illustrate Spring framework architecture and its elements.


Spring Framework Architecture:
• The Spring framework comprises of many modules such as core,
beans, context, expression language, AOP, Aspects, Instrumentation,
JDBC, ORM, OXM, JMS, Transaction, Web, Servlet, Struts etc.
• These modules are grouped into Test, Core Container, AOP, Aspects,
Instrumentation, Data Access / Integration, Web (MVC / Remoting) as
displayed in the following diagram.
Elements of Spring Module:
• Test - This layer provides support of testing with JUnit and TestNG.
1. Core Container
o Core - These modules provide IOC and Dependency Injection features.
o Beans - module provides BeanFactory, which is a sophisticated
implementation of the factory pattern.
o Context - This module supports internationalization (I18N), EJB, JMS,
Basic Remoting. module builds on the solid base provided by the Core
and Beans modules and it is a medium to access any objects defined
and configured. The ApplicationContext interface is the focal point of
the Context module.
o Expression Language - It is an extension to the EL defined in JSP. It
provides support to setting and getting property values, method
invocation, accessing collections and indexers, named variables, logical
and arithmetic operators, retrieval of objects by name etc.
The SpEL module provides a powerful expression language for querying
and manipulating an object graph at runtime.
2. Data Access / Integration - This group comprises of JDBC, ORM, OXM, JMS
and Transaction modules. These modules basically provide support to
interact with the database.
o The JDBC module provides a JDBC-abstraction layer that removes the
need for tedious JDBC related coding.
o The ORM module provides integration layers for popular object-
relational mapping APIs, including JPA, JDO, Hibernate, and iBatis.
o The OXM module provides an abstraction layer that supports
Object/XML mapping implementations for JAXB, Castor, XMLBeans,
JiBX and XStream.
o The Java Messaging Service JMS module contains features for
producing and consuming messages.
o The Transaction module supports programmatic and declarative
transaction management for classes that implement special interfaces
and for all your POJOs.
3. Web - This group comprises of Web, Web-Servlet, Web-Struts and Web-
Portlet. These modules provide support to create web application.
o The Web module provides basic web-oriented integration features such
as multipart file-upload functionality and the initialization of the IoC
container using servlet listeners and a web-oriented application
context.
o The Web-MVC module contains Spring's Model-View-Controller (MVC)
implementation for web applications.
o The Web-Socket module provides support for WebSocket-based, two-
way communication between the client and the server in web
applications.
o The Web-Portlet module provides the MVC implementation to be used
in a portlet environment and mirrors the functionality of Web-Servlet
module.
4. The AOP module provides an aspect-oriented programming
implementation allowing you to define method-interceptors and pointcuts to
cleanly decouple code that implements functionality that should be
separated.
o The Aspects module provides integration with AspectJ, which is again a
powerful and mature AOP framework.
o The Instrumentation module provides class instrumentation support
and class loader implementations to be used in certain application
servers.
o The Messaging module provides support for STOMP as the WebSocket
sub-protocol to use in applications. It also supports an annotation
programming model for routing and processing STOMP messages from
WebSocket clients.
5. The Test module supports the testing of Spring components with JUnit or
TestNG frameworks.
18. Explain Spring RESTful web service and its advantages.
REST stands for REpresentational State Transfer.
The main goal of RESTful web services is to make web services more
effective. RESTful web services try to define services using the different
concepts that are already present in HTTP. REST is an architectural approach,
not a protocol.
• It does not define the standard message exchange format. We can build
REST services with both XML and JSON. JSON is more popular format
with REST. The key abstraction is a resource in REST. A resource can be
anything. It can be accessed through a Uniform Resource Identifier
(URI). For example:
• The resource has representations like XML, HTML, and JSON. The
current state capture by representational resource. When we request a
resource, we provide the representation of the resource. The important
methods of HTTP are:
• GET: It reads a resource.
• PUT: It updates an existing resource.
• POST: It creates a new resource.
• DELETE: It deletes the resource.
Advantages of RESTful web services
• RESTful web services are platform-independent.
• It can be written in any programming language and can be executed on
any platform.
• It provides different data format like JSON, text, HTML, and XML.
• It is fast in comparison to SOAP because there is no strict specification
like SOAP.
• These are reusable.
• They are language neutral.
Ten Mark Questions:
[Link] Collection and collection framework .
Collection Framework:
• provides an architecture to store and manipulate the group of
objects.
• achieve all the operations that you perform on a data such as
searching, sorting, insertion, manipulation, and deletion.
• Java Collection means a single unit of objects. Java Collection
framework provides many interfaces (Set, List, Queue, Deque)
and classes (ArrayList, Vector,LinkedList,PriorityQueue, HashSet,
LinkedHashSet, TreeSet).
• Collection represents a single unit of objects, i.e., a group.
• framework - provides readymade architecture.
• - represents a set of classes and interfaces.
• The Collection framework represents a unified architecture for
storing and manipulating a group of objects.
• It has:
• Interfaces and its implementations, i.e., classes
• Algorithm
The [Link] package contains all the classes and interfaces for
the Collection framework
Collection Interface:
• The Collection interface is the interface which is implemented
by all the classes in the collection framework. It declares the
methods that every collection will have. In other words, we can
say that the Collection interface builds the foundation on which
the collection framework depends.
• Some of the methods of Collection interface are Boolean add (
Object obj), Boolean addAll ( Collection c), void clear(), etc.
which are implemented by all the subclasses of Collection
interface.

Iterable Interface:
• The Iterable interface is the root interface for all the collection
classes. The Collection interface extends the Iterable interface
and therefore all the subclasses of Collection interface also
implement the Iterable interface.
• It contains only one abstract method. i.e.,
• Iterator<T> iterator()
• It returns the iterator over the elements of type T.

[Link] the Servlet Life Cycle and its architecture:


• The web container maintains the life cycle of a servlet
instance. Let's see the life cycle of the servlet:
• Servlet class is loaded.
• Servlet instance is created.
• init method is invoked.
• service method is invoked.
• destroy method is invoked.

• 1) Servlet class is loaded


• The classloader is responsible to load the servlet class.
The servlet class is loaded when the first request for the
servlet is received by the web container.
• 2) Servlet instance is created
• The web container creates the instance of a servlet after
loading the servlet class. The servlet instance is created
only once in the servlet life cycle.
• 3) init method is invoked
• The web container calls the init method only once after
creating the servlet instance. The init method is used to
initialize the servlet. It is the life cycle method of the
[Link] interface. Syntax of the init method
is given below:
• public void init(ServletConfig config) throws ServletExce
ption
• 4) service method is invoked
• The web container calls the service method each time
when request for the servlet is received. If servlet is not
initialized, it follows the first three steps as described
above then calls the service method. If servlet is
initialized, it calls the service method. Notice that servlet
is initialized only once. The syntax of the service method
of the Servlet interface is given below:
• public void service(ServletRequest request, ServletResp
onse response)
• throws ServletException, IOException
• 5) destroy method is invoked
• The web container calls the destroy method before
removing the servlet instance from the service. It gives
the servlet an opportunity to clean up any resource for
example memory, thread etc. The syntax of the destroy
method of the Servlet interface is given below:
• public void destroy()
[Link] JPA ORM and its framework, mapping types.
• ORM is a functionality - used to develop and maintain a
relationship between an object and relational database
by mapping an object state to database column.
• It is capable to handle various database operations easily
such as inserting, updating, deleting etc.
JPA Providers
Vendors such as Oracle, Redhat, Eclipse, etc.
Frameworks - Hibernate, Eclipselink, Toplink, Spring Data JPA,
etc.

ORM Mapping:
Mapping directions
• Unidirectional relationship - In this relationship, only
one entity can refer the properties to another. It
contains only one owing side that specifies how an
update can be made in the database.
• Bidirectional relationship - This relationship contains an
owning side as well as an inverse side. So here every
entity has a relationship field or refer the property to
other entity.
Types of Mapping
• One-to-one - This association is represented by
@OneToOne annotation. Here, instance of each entity is
related to a single instance of another entity.
• One-to-many - This association is represented by
@OneToMany annotation. In this relationship, an
instance of one entity can be related to more than one
instance of another entity.
• Many-to-one - This mapping is defined by @ManyToOne
annotation. In this relationship, multiple instances of an
entity can be related to single instance of another entity.
• Many-to-many - This association is represented by
@ManyToMany annotation. Here, multiple instances of
an entity can be related to multiple instances of another
entity. In this mapping, any side can be the owing side.
[Link] Spring MVC architecture and its advantages.
• The Spring Web MVC framework provides a model-
view-controller architecture and ready components that
can be used to develop flexible and loosely coupled web
applications.
• The MVC pattern results in separating the different
aspects of the application (input logic, business logic,
and UI logic), while providing a loose coupling between
these elements.
• The Spring Web model-view-controller (MVC)
framework is designed around a DispatcherServlet that
handles all the HTTP requests and responses. The
request processing workflow of the Spring Web MVC
DispatcherServlet
• After receiving an HTTP request, DispatcherServlet
consults the HandlerMapping to call the appropriate
Controller.
• The Controller takes the request and calls the
appropriate service methods based on
used GET or POST method. The service method will set
model data based on defined business logic and returns
view name to the DispatcherServlet.
• The DispatcherServlet will take help
from ViewResolver to pick up the defined view for the
request.
• Once view is finalized, The DispatcherServlet passes the
model data to the view, which is finally rendered, on the
browsers.
Advantages of Spring MVC Framework:

• Separate roles - The Spring MVC separates each role,


where the model object, controller, command object,
view resolver, DispatcherServlet, validator, etc. can be
fulfilled by a specialized object.
• Light-weight - It uses light-weight servlet container to
develop and deploy your application.
• Powerful Configuration - It provides a robust
configuration for both framework and application
classes that includes easy referencing across contexts,
such as from web controllers to business objects and
validators.
• Rapid development - The Spring MVC facilitates fast and
parallel development.
• Reusable business code - Instead of creating new
objects, it allows us to use the existing business objects.
• Easy to test - In Spring, generally we create JavaBeans
classes that enable you to inject test data using the
setter methods.
• Flexible Mapping - It provides the specific annotations
that easily redirect the page.

[Link] different types of JDBC drivers?


• JDBC stands for Java Database Connectivity. JDBC is a
Java API to connect and execute the query with the
database. It is a part of JavaSE (Java Standard Edition).
JDBC API uses JDBC drivers to connect with the
database.
There are four types of JDBC drivers:
• JDBC-ODBC Bridge Driver,
• Native Driver,
• Network Protocol Driver, and
• Thin Driver
• use JDBC API to access tabular data stored in any
relational database. By the help of JDBC API, we can
save, update, delete and fetch data from the database. It
is like Open Database Connectivity (ODBC) provided by
Microsoft.
JDBC-ODBC bridge driver
The JDBC-ODBC bridge driver uses ODBC driver to connect to
the database. The JDBC-ODBC bridge driver converts JDBC
method calls into the ODBC function calls. This is now
discouraged because of thin driver.
• Oracle does not support the JDBC-ODBC Bridge from
Java 8. Oracle recommends that you use JDBC drivers
provided by the vendor of your database instead of the
JDBC-ODBC Bridge.
Advantages:
• easy to use.
• can be easily connected to any database.
Disadvantages:
• Performance degraded because JDBC method call is
converted into the ODBC function calls.
• The ODBC driver needs to be installed on the client
machine.

Native API driver
• The Native API driver uses the client-side libraries of the
database. The driver converts JDBC method calls into
native calls of the database API. It is not written entirely
in java.
• Advantage:
• performance upgraded than JDBC-ODBC bridge driver.
• Disadvantage:
• The Native driver needs to be installed on the each client
machine.
• The Vendor client library needs to be installed on client
machine.
Network Protocol driver
• The Network Protocol driver uses middleware
(application server) that converts JDBC calls directly or
indirectly into the vendor-specific database protocol. It is
fully written in java.
• Advantage:
• No client side library is required because of application
server that can perform many tasks like auditing, load
balancing, logging etc.
• Disadvantages:
• Network support is required on client machine.
• Requires database-specific coding to be done in the
middle tier.
• Maintenance of Network Protocol driver becomes costly
because it requires database-specific coding to be done
in the middle tier.
Thin driver
The thin driver converts JDBC calls directly into the
vendor-specific database protocol. That is why it is
known as thin driver. It is fully written in Java language.
Advantage:
• Better performance than all other drivers.
• No software is required at client side or server side.
Disadvantage:
• Drivers depend on the Database.

[Link] various Session tracking techniques.


Session Tracking Techniques:
1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession
Cookies
A cookie is a small piece of information that is persisted
between the multiple client requests.
A cookie has a name, a single value, and optional attributes
such as a comment, path and domain qualifiers, a maximum
age, and a version number.
• How Cookie works
• By default, each request is considered as a new request.
In cookies technique, we add cookie with response from
the servlet. So cookie is stored in the cache of the
browser. After that if request is sent by the user, cookie
is added with request by default. Thus, we recognize the
user as the old user.

• create cookie.
• Cookie ck=new Cookie("user","sonoo jaiswal");//creatin
g cookie object
• [Link](ck);//adding cookie in the response

• delete Cookie
• It is mainly used to logout or signout the user.
• Cookie ck=new Cookie("user","");//deleting value of coo
kie
• [Link](0);//changing the maximum age to 0 seco
nds
• [Link](ck);//adding cookie in the response

• get Cookies
• to get all the cookies.
Cookie ck[]=[Link]();
for(int i=0;i<[Link];i++){
[Link]("<br>"+ck[i].getName()+" "+ck[i].getValue());//print
ing name and value of cookie
}
Example:
• storing the name of the user in the cookie object and
accessing it in another servlet. As we know well that
session corresponds to the particular user. So if you
access it from too many browsers with different values,
you will get the different value.

• Advantage of Cookies
• Simplest technique of maintaining the state.
• Cookies are maintained at client side.
• Disadvantage of Cookies
• It will not work if cookie is disabled from the browser.
Only textual information can be set in Cookie object
• Cookie ck=new Cookie("user","sonoo jaiswal");//creatin
g cookie object
• [Link](ck);//adding cookie in the response

• delete Cookie
• It is mainly used to logout or signout the user.
• Cookie ck=new Cookie("user","");//deleting value of coo
kie
• [Link](0);//changing the maximum age to 0 seco
nds
• [Link](ck);//adding cookie in the response

• get Cookies
• to get all the cookies.
Cookie ck[]=[Link]();
for(int i=0;i<[Link];i++){
[Link]("<br>"+ck[i].getName()+" "+ck[i].getValue());//print
ing name and value of cookie
}
Hidden Form Field:
• In case of Hidden Form Field a hidden (invisible)
textfield is used for maintaining the state of an user.
• In such case, we store the information in the hidden
field and get it from another servlet. This approach is
better if we have to submit form in all the pages and we
don't want to depend on the browser.
• Let's see the code to store value in hidden field.
• <input type="hidden" name="uname" value="Vimal Jais
wal">
• Here, uname is the hidden field name and Vimal Jaiswal
is the hidden field value.

• Real application of hidden form field


• It is widely used in comment form of a website. In such
case, we store page id or page name in the hidden field
so that each page can be uniquely identified.
• Advantage of Hidden Form Field
• It will always work whether cookie is disabled or not.
• Disadvantage of Hidden Form Field:
• It is maintained at server side.
• Extra form submission is required on each pages.
• Only textual information can be used.
URL rewriting
• URL rewriting, we append a token or identifier to the
URL of the next Servlet or the next resource. We can
send parameter name/value pairs using the following
format:
• url?name1=value1&name2=value2&??
• A name and a value is separated using an equal = sign, a
parameter name/value pair is separated from another
parameter using the ampersand(&). When the user
clicks the hyperlink, the parameter name/value pairs
• Advantage of URL Rewriting
• It will always work whether cookie is disabled or not
(browser independent).
• Extra form submission is not required on each pages.
• Disadvantage of URL Rewriting
• It will work only with links.
• It can send Only textual information.
HttpSession interface:
• In such case, container creates a session id for each
[Link] container uses this id to identify the particular
[Link] object of HttpSession can be used to perform
two tasks:
1. bind objects
2. view and manipulate information about a session, such as
the session identifier, creation time, and last accessed
time.
The HttpServletRequest interface provides two methods to
get the object of HttpSession:
public HttpSession getSession():Returns the current session
associated with this request, or if the request does not have
a session, creates one.
Explain about AOP and its uses.
• Aspect Oriented Programming (AOP) compliments OOPs
in the sense that it also provides modularity. But the key
unit of modularity is aspect than class.
• AOP breaks the program logic into distinct parts (called
concerns). It is used to increase modularity by cross-
cutting concerns.
• A cross-cutting concern is a concern that can affect the
whole application and should be centralized in one
location in code as possible, such as transaction
management, authentication, logging, security etc.

Elements of Hibernate Architecture:


• Hibernate framework uses many objects such as
session factory, session, transaction etc. along with
existing Java API such as JDBC (Java Database
Connectivity), JTA (Java Transaction API) and JNDI (Java
Naming Directory Interface).
• Configuration([Link])
➢ first Hibernate object create in any Hibernate
application.
➢ It is usually created only once during application
initialization.
➢ It represents a configuration or properties file required
by the Hibernate.
• two keys components −
• Database Connection − This is handled through one or
more configuration files supported by Hibernate. These
files are [Link] and [Link].
• Class Mapping Setup − This component creates the
connection between the Java classes and database
tables.

Elements of Spring Module

• Test - This layer provides support of testing with JUnit


and TestNG.
1. Core Container
o Core - These modules provide IOC and Dependency
Injection features.
o Beans - module provides BeanFactory, which is a
sophisticated implementation of the factory pattern.
o Context - This module supports internationalization
(I18N), EJB, JMS, Basic Remoting. module builds on the
solid base provided by the Core and Beans modules and
it is a medium to access any objects defined and
configured. The ApplicationContext interface is the focal
point of the Context module.
o Expression Language - It is an extension to the EL
defined in JSP. It provides support to setting and getting
property values, method invocation, accessing
collections and indexers, named variables, logical and
arithmetic operators, retrieval of objects by name etc.
The SpEL module provides a powerful expression
language for querying and manipulating an object graph
at runtime.
2. Data Access / Integration - This group comprises of JDBC,
ORM, OXM, JMS and Transaction modules. These modules
basically provide support to interact with the database.
o The JDBC module provides a JDBC-abstraction layer that
removes the need for tedious JDBC related coding.
o The ORM module provides integration layers for popular
object-relational mapping APIs, including JPA, JDO,
Hibernate, and iBatis.
o The OXM module provides an abstraction layer that
supports Object/XML mapping implementations for
JAXB, Castor, XMLBeans, JiBX and XStream.
o The Java Messaging Service JMS module contains
features for producing and consuming messages.
o The Transaction module supports programmatic and
declarative transaction management for classes that
implement special interfaces and for all your POJOs.
3. Web - This group comprises of Web, Web-Servlet, Web-
Struts and Web-Portlet. These modules provide support to
create web application.
o The Web module provides basic web-oriented
integration features such as multipart file-upload
functionality and the initialization of the IoC container
using servlet listeners and a web-oriented application
context.
o The Web-MVC module contains Spring's Model-View-
Controller (MVC) implementation for web applications.
o The Web-Socket module provides support for
WebSocket-based, two-way communication between
the client and the server in web applications.
o The Web-Portlet module provides the MVC
implementation to be used in a portlet environment and
mirrors the functionality of Web-Servlet module.
4. The AOP module provides an aspect-oriented
programming implementation allowing you to define
method-interceptors and pointcuts to cleanly decouple code
that implements functionality that should be separated.
o The Aspects module provides integration with AspectJ,
which is again a powerful and mature AOP framework.
o The Instrumentation module provides class
instrumentation support and class loader
implementations to be used in certain application
servers.
o The Messaging module provides support for STOMP as
the WebSocket sub-protocol to use in applications. It
also supports an annotation programming model for
routing and processing STOMP messages from
WebSocket clients.
5. The Test module supports the testing of Spring
components with JUnit or TestNG frameworks.

Spring Boot

• Spring Boot is a project that is built on the top of the


Spring Framework. It provides an easier and faster way
to set up, configure, and run both simple and web-based
applications.
• It is a Spring module that provides the RAD (Rapid
Application Development) feature to the Spring
Framework. It is used to create a stand-alone Spring-
based application that you can just run because it needs
minimal Spring configuration.
Features:
1. Autoconfiguration: Developers can automatically configure their Spring
application. However, Spring Boot is also capable of changing the
configuration based on the dependencies you list. For example, when you list
“MySQL” as a dependency, it will configure your Spring application with the
“MySQL connector” included. And if you want to add a custom configuration,
you can create a class that overrides the default configuration for your
“MySQL connector”.
2. Standalone: There’s no need to deploy your application to a web server. You
simply enter the run command to start the application.
3. Opinionated: On the official page, we find that Spring Boot decides for you
which defaults to use for the configuration. Also, it decides which packages to
install for the dependencies you require. For example, if you include the
Spring Boot starter “pom” for “JPA”, it will autoconfigure an in-memory
database, a hibernate entity manager, and a simple data source. This is an
example of an opinionated default configuration that you can override. While
some developers might feel this is too opinionated, Spring Boot’s opinionated
setup helps developers to get started quickly on their projects.

Advantages:
• Fast and easy development of Spring-based applications;
• No need for the deployment of war files;
• The ability to create standalone applications;
• Helping to directly embed Tomcat, Jetty, or Undertow into an application;
• No need for XML configuration;
• Reduced amounts of source code;
• Additional out-of-the-box functionality;
• Easy start;
• Simple setup and management;
• Large community and many training programs to facilitate the familiarization
period.

Disadvantages:
• Lack of control. Spring Boot creates a lot of unused dependencies, resulting in
a large deployment file;
• The complex and time-consuming process of converting a legacy or an
existing Spring project to a Spring Boot application;
• Not suitable for large-scale projects. Although it’s great for working with
microservices, many developers claim that Spring Boot is not suitable for
building monolithic applications.
Annotation
• Annotation is a tag that represents the metadata
• Annotations start with ‘@’.
• Annotations do not change the action of a compiled
program.
• Annotations help to associate metadata (information) to
the program elements i.e. instance variables,
constructors, methods, classes, etc.
• Annotations are not pure comments as they can change
the way a program is treated by the compiler.
• Annotations in Java are used to provide additional
information, so it is an alternative option for XML and
Java marker interfaces.
• There are broadly 5 categories of annotations as listed:
• Marker Annotations
• Single value Annotations
• Full Annotations
• Type Annotations
• Repeating Annotations
@Override
• @Override annotation assures that the subclass method
is overriding the parent class method. If it is not so,
compile time error occurs.
• Sometimes, we does the silly mistake such as spelling
mistakes etc. So, it is better to mark @Override
annotation that provides assurity that method is
overridden.
• class Parent {
• void display() {
• [Link]("Parent display");
• }
• }

• class Child extends Parent {
• @Override
• void display() {
• [Link]("Child display");
• }
• }
@Deprecated

This annotation marks a method or class as deprecated, meaning it should not be


used because it may be removed in the future.
class Example {
@Deprecated
void oldMethod() {
[Link]("This method is deprecated");
}
}
@SuppressWarnings

This annotation tells the compiler to suppress specific warnings.


class Example {
@SuppressWarnings("unchecked")
void method() {
List rawList = new ArrayList();
[Link]("example");
}
}
Java Custom Annotations/ Java User-defined annotations
• are easy to create and use.
• The @interface element is used to declare an
annotation. For example:
@interface MyAnnotation{}
Here, MyAnnotation is the custom annotation name.
• There are few points that should be remembered by the
programmer.
1. Method should not have any throws clauses
2. Method should return one of the following: primitive
data types, String, Class, enum or array of these data
types.
3. Method should not have any parameter.
4. We should attach @ just before interface keyword to
define annotation.
5. It may assign a default value to the method.
@Target

This annotation indicates the kinds of program elements to which an annotation type
is applicable.

• An annotation that has no method, is called marker


annotation. For example:
• @interface MyAnnotation{}
• The @Override and @Deprecated are marker
annotations.
• An annotation that has one method, is called single-
value annotation. For example
@interface MyAnnotation{
int value();
}
• We can provide the default value also. For example:
@interface MyAnnotation{
int value() default 0;
}
• How to apply Single-Value Annotation
• Let's see the code to apply the single value annotation.
• @MyAnnotation(value=10)
• The value can be anything.
. @Retention

This annotation specifies how long annotations with the annotated type are to be
retained.
@Retention([Link])
@interface MyAnnotation {
String value();
}

Tabulate Basic jPQL operations and advanced operatio


Sent by you: Tabulate Basic jPQL operations and advanced operatio
Table

Operation Type Operation Description Example

Basic SELECT Retrieve data from entities.


SELECT s FROM Student s

JPQL does not support INSERT


directly. Use entity
INSERT manager’s persist method. [Link](student);

UPDATE Modify existing data in entities. UPDATE Student s SET [Link] = 23 WHERE [Link] = 'John'

DELETE Remove data from entities. DELETE FROM Student s WHERE [Link] = 'John'

WHERE Filter records. SELECT s FROM Student s WHERE [Link] > 20

ORDER BY Sort records. SELECT s FROM Student s ORDER BY [Link] DESC

Combine rows from two or more


JOIN entities. SELECT [Link], [Link] FROM Student s JOIN [Link] c

| Advanced | GROUP BY | Group rows that have the same values.


| SELECT COUNT(s), [Link] FROM Student s GROUP BY
[Link] | | | HAVING | Filter groups. | SELECT COUNT(s),
[Link] FROM Student s GROUP BY [Link] HAVING
COUNT(s) > 1 | | | Subqueries | Nested queries. | SELECT s FROM
Student s WHERE [Link] > (SELECT AVG([Link]) FROM
Student s2) | | | Fetch Joins | Retrieve associated entities. | SELECT
s FROM Student s JOIN FETCH [Link] | | | Named Queries |
Predefined queries. | @NamedQuery(name =
"[Link]", query = "SELECT s FROM Student
s WHERE [Link] = :name") | | | Bulk Updates | Update multiple
entities. | UPDATE Student s SET [Link] = 'active' WHERE
[Link] = 'inactive' | | | Bulk Deletes | Delete multiple entities.
| DELETE FROM Student s WHERE [Link] = 'inactive'

You might also like