Advance Java_merged
Advance Java_merged
J2EE Container
• The application server which control and provide services through an interface is known as a container. J2EE
container helps in deployment and execution of J2EE component
J2EE Server and Containers
• J2EE server
The runtime portion of a J2EE product. A J2EE server provides EJB and web containers.
• Enterprise JavaBeans (EJB) container
Manages the execution of enterprise beans for J2EE applications. Enterprise beans and their container run on the
J2EE server.
• Web container
Manages the execution of JSP page and servlet components for J2EE applications. web components and their
container run on the J2EE server.
• Application client container
Manages the execution of application client components. Application clients and their container run on the
client.
• Applet container
Manages the execution of applets. Consists of a web browser and Java Plug-in running on the client together.
Packaging Web Applications
• You add web components to a J2EE application in a package called a web application archive (WAR), which
is a JAR similar to the package used for Java class libraries. A WAR usually contains other resources besides
web components, including:
Server-side utility classes
Static web resources (HTML, image, and sound files, and so on)
Client-side classes (applets and utility classes)
• A WAR has a specific hierarchical directory structure. The top-level directory of a WAR is the document
root of the application. The document root is where JSP pages, client-side classes and archives, and static web
resources are stored. The document root contains a subdirectory called WEB-INF, which contains the
following files and directories:
web.xml - the web application deployment descriptor
Tag library descriptor files
classes - a directory that contains server-side classes: servlet, utility classes, and JavaBeans
components.
lib - a directory that contains JAR archives of libraries (tag libraries and any utility libraries called
by server-side classes)
Introduction to Java Web Application:
• The primary purpose of the java web application is to provide basic information about different components
in Web Application and also provide the details on how we can use Servlet and JSP to create our first java
web application.
Web Application Directory Structure:
Earliest attempts
• Applets - uses the client platform to deliver dynamic user experiences.
Common Gateway Interface (CGI) scripts - using the server platform to
generate dynamic content
• CGI scripting technology has a number of shortcomings, including
platform dependence and lack of scalability.
• To address these limitations, Java Servlet technology was created as a
portable way to provide dynamic, user-oriented content.
What Is a Servlet?
• A servlet is a Java programming language class that is used to
extend the capabilities of servers that host applications
accessed by means of a request-response programming model.
• Although servlets can respond to any type of request, they are
commonly used to extend the applications hosted by web
servers.
• For such applications, Java Servlet technology defines HTTP-
specific servlet classes.
Advantages of Servlets over CGI
1. Platform Independent
It is Process based i.e, for every request a It is thread-based i.e, for every request a new
separate process will be created and it is thread will be created and it is responsible to
responsible to generate required response. process the request.
Creation and Destruction of process for every Creation and Destruction of new thread for every
request is costly. If the number of requests request is not costly . Hence there is no effect on
increase it will effects performance of the performance even though number of requests
system.Hence CGI technology fail to the destroy increases due to this it succeeds to delevary
of scalable. scalable.
Syntax:
public void init(ServletConfig config ) throws ServletException
4. Calls the service( ) method
The service( ) method performs actual task of servlet container. The
web container is responsible to call the service method each time the
request for servlet is received. The service( ) invokes the doGet( ),
doPost( ), doPut ( ), doDelete( ) methods based on the HTTP request.
Syntax:
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException
5. Calls the destroy( ) method
The destroy( ) method is executed when the servlet container remove
the servlet from the container. It is called only once at the end of the
life cycle of servlet.
Syntax:
public void destroy( )
Web.xml
<web-app>
Defines the specific version of the servlet API in use.
<display-name>
Defines the internal name of this web application that will appear
in the servlet container management system.
<servlet>
Binds a name to a particular servlet class
<servlet-mapping>
Binds a particular servlet to a URL from the root of the servlet.
<welcome-file-list>
Defines a set of files to use as the landing page for the servlet. In
this case, the view is set to be the landing page.
CGI(Commmon Gateway Interface)
• Servlet :
Every servlet in java should implement servlet interface either
directly or indirectly. ie, Servlet interface acts as a root
interface for all java Servlets.
This interface defines the most common methods (including
life cycle methods) which are applicable for any servlet object.
• ServletRequest :
ServletRequest object can be used to hold client data.
ServletRequest interface defines several methods to acts as end
users provided data from the request object.
Ex: getParameter()
• ServletResponse :
ServletResponse object can be used to prepare and send responds to the client.
ServletResponse interface defines several methods which are required for
preparation of response.
Ex: getWriter(), setContentType()
• ServletConfig :
For every servlet , web container creates one ServletConfig object to hold its
configuration information like logical name of the Servlet , instantiation parameters
etc.
ServletConfig interface defines several methods to access servlets configuration
information.
Ex: getServletName()
getInitParameter()
• ServletContext :
For every web application, web container will create one ServletContext object to
hold application level configuration information like name of the app'n and
ServletContext parameter etc.
Note : ServletConfig is per Servlet , where as ServletContext is per web
application.
• RequestDispatcher :
By using RequestDispatcher object we can dispatch the
request from one component to another component.
This interface defines two methods.
1. forward()
2.include()
Servlet Interface - Methods
Method Description
initializes the servlet. It is the life
public void init(ServletConfig config) cycle method of servlet and invoked
by the web container only once.
provides response for the incoming
public void service(ServletRequest
request. It is invoked at each request
request,ServletResponse response)
by the web container.
is invoked only once and indicates that
public void destroy()
servlet is being destroyed.
public ServletConfig
returns the object of ServletConfig.
getServletConfig()
DemoServ.java
index.html import javax.servlet.http.*;
import javax.servlet.*;
<form action="welcome" method import java.io.*;
="get">Enter your name public class DemoServ extends HttpServlet
{
<input type="text" name="name" public void doGet(HttpServletRequest req,
HttpServletResponse res)
><br> throws ServletException,IOException
{
<input type="submit" value="logi res.setContentType("text/html");
n"> PrintWriter pw=res.getWriter();
</form> String name=req.getParameter("name");//
will return value
pw.println("Welcome "+name);
pw.close();
}}
Exception Handling
• An exception is an event, which occurs during the execution of a
program, which disrupts the normal flow of the program’s
instructions. The process of converting the system error messages
into user-friendly error messages is known as Exception Handling.
• Programmatically exception handling mechanism: The approach
to use try and catch block in the Java code to handle exceptions is
known as programmatically exception handling mechanism
• Declarative exception handling mechanism: The approach to use
the XML tags in the web.xml file to handle the exception is known
as declarative exception handling mechanism. This mechanism is
useful if exception is common for more than one servlet program
Servlet-Error Handling
javax.servlet.error.message java.lang.String
javax.servlet.error.exception java.lang.Throwable
javax.servlet.error.request_uri java.lang.String
javax.servlet.error.servlet_name java.lang.String
Servlet Exception
javax.servlet
Class ServletException
java.lang.Object
java.lang.Throwable
java.lang.Exception
javax.servlet.ServletException
Example:
Example:
request.getRequestDispacher("servlet2").
response.sendRedirect("servlet2");
forward(request,response);
ServletConfig Interface
<context-param>
<param-name>dname</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</context-param>
......
</web-app>
• Cookies
• Hidden Form Field
• URL Rewriting
• HttpSession
Cookies in Servlet
• Cookie ck[]=request.getCookies();
for(int i=0;i<ck.length;i++){
out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());
//printing name and value of cookie
}
index.html Assignment
<form action="servlet1" method="post">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
response.setContentType("text/html"); Servlet 2
PrintWriter out = response.getWriter();
Cookie ck[]=request.getCookies();
out.print("Hi …"+ck[0].getValue());
Hidden Form Field
• a hidden (invisible) textfield is used for maintaining the state
of an user.
• This approach is better if we have to submit form in all the
pages and we don't want to depend on the browser.
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.
Syntax
<input type="hidden" name="user" value=“CDAC">
URL Rewriting
• In 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&??
response.setContentType("text/html"); Servlet 1
PrintWriter out = response.getWriter();
String user=request.getParameter("userName");
out.print("Welcome "+user);
HttpSession session=request.getSession();
session.setAttribute("name“,user);
out.print("<a href='servlet2'>visit</a>");
response.setContentType("text/html"); Servlet 2
PrintWriter out = response.getWriter();
HttpSession session=request.getSession(false);
String n=(String)session.getAttribute("uname");
out.print("Hello "+n); out.close();
Session Cookies
1.Session can store any type of data 1.Cookies can store only “string”
because the value is of data type of datatype.
“object”
2. These are stored at server side. 2. They are stored at client side.
In JSP, java code can be written inside the jsp page using the
scriptlet tag.
Scripting elements
1. scriptlet tag
2. expression tag
3. declaration tag
Syntax
Declaration Tag :-It is used to declare variables.
Syntax:-
<%! Dec var %>
Example:-
<%! int var=10; %>
Java Scriplets :- It allows us to add any number of JAVA code, variables and expressions.
Syntax:-
<% java code %>
<html> welcome.jsp
<body>
<%
String name=request.getParameter(“user");
out.print("welcome "+name);
%>
</form>
</body>
</html>
JSP expression tag
<html> index.jsp
<body>
Current Time: <%= java.util.Calendar.getInstance().getTime() %>
</body>
</html>
<html> index.html
<body>
<form action="welcome.jsp">
<input type="text" name=“user"><br/>
<input type="submit" value="go">
</form>
</body>
</html>
<html> welcome.jsp
welcome.jsp
<body>
<%= "Welcome "+request.getParameter(“user") %>
</body>
</html>
JSP Declaration Tag
• The JSP declaration tag is used to declare fields and methods.
• The jsp scriptlet tag can only declare variables not methods.
<html> index.jsp(fields)
<body>
<%! int data=50; %>
<%= "Value of the variable is:"+data %>
</body>
</html>
<html> index.jsp(method)
<body>
<%! int cube(int n){ return n*n*n*; } %>
<%= "Cube of 3 is:"+cube(3) %>
</body>
</html>
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.
Object Type
JspWriter e.g. PrintWriter out=response.getWriter();
out
<% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
request HttpServletRequest e.g. <% String name=request.getParameter(“user");%>
e.g.
<%@ taglib uri="http://www.cdac.in/tags" prefix="mytag" %>
<mytag:currentDate/>
Exception Handling in JSP
• Easy to maintain
• Easy to extend
• Easy to test
• Navigation control is centralized
Session 7 & 8 (Introduction to JDBC)
Introduction to JDBC
• The term JDBC stands for Java Database Connectivity. JDBC is a specification
from Sun microsystems. JDBC is an API(Application programming interface) in
Java that helps users to interact or communicate with various databases.
• The classes and interfaces of JDBC API allow the application to send the request
to the specified database.
Purpose Of JDBC
• There are some enterprise applications created using the JAVA EE(Enterprise
Edition) technology. These applications need to interact with databases to store
application-specific information.
• Interacting with the database requires efficient database connectivity, which we
can achieve using ODBC(Open database connectivity) driver. We can use this
ODBC Driver with the JDBC to interact or communicate with various kinds of
databases, like Oracle, MS Access, Mysql, and SQL, etc.
Applications of JDBC
JDBC ResultSet:
Method Description
public void setInt(int paramIndex, int value) sets the integer value to the given parameter index.
public void setString(int paramIndex, String value) sets the String value to the given parameter index.
public void setFloat(int paramIndex, float value) sets the float value to the given parameter index.
public void setDouble(int paramIndex, double value) sets the double value to the given parameter index.
public int executeUpdate() executes the query. It is used for create, drop, insert,
update, delete etc.
public ResultSet executeQuery() executes the select query. It returns an instance of
ResultSet.
BLOB and CLOB
• BLOB Features Derby supports the java.sql.Blob interface and the BLOB-related
methods in java.sql.PreparedStatement and java.sql.ResultSet. The getBlob
methods of CallableStatement are not implemented.
• CLOB Features Derby supports the java.sql.Clob interface and the CLOB-related
methods in java.sql.PreparedStatement and java.sql.ResultSet. The getClob
methods of CallableStatement procedures are not implemented.
Session 9,10, 11
(Hibernate)
Introduction of Hibernate
@Table Name Maps this class with a database table specified by name modifier. If name is not supplied it
maps the class with a table having same name as the class
@Id Marks this class field as a primary key column
@Column Name Maps this field with table column specified by name and uses the field name if name modifier is
absent
Cascade Marks this field as the owning side of the many-to-many relationship and cascade modifier
specifies which operations should cascade to the inverse side of relationship
@ManyToMany mappedBy This modifier holds the field which specifies the inverse side of the relationship
Name For holding this many-to-many relationship, maps this field with an intermediary database join
table specified by name modifier
joinColumns Identifies the owning side of columns which are necessary to identify a unique owning object
inverseJoinColu Identifies the inverse (target) side of columns which are necessary to identify a unique target
@JoinTable
mns object
@JoinColumn Name Maps a join column specified by the name identifier to the relationship table specified by
@JoinTable
Hibernate Dialects
• To connect to any database with hibernate, we need to specify the SQL dialect
class in hibernate.cfg.xml
Ex: To connect to oracle database we need to specify oracle dialect class in
configuration xml as below.
• Dialect class is java class, which contains code to map between java language data
type database data type.
• All Dialect classes extend the Dialect abstract class.
• Dialect is used to convert HQL(Hibernate Query Language) statements to data
base specific statements
Hibernate Mapping
Types of relationships
1. One-To-One
2. Many-To-One
3. Many-To-Many
4. One-To-Many
HQL (Hibernate Query Language)
The IoC container is responsible to instantiate, configure and assemble the objects.
The IoC container gets informations from the XML file and works accordingly. The
main tasks performed by IoC container are:
• to instantiate the application class
• to configure the object
• to assemble the dependencies between the objects
There are two types of IoC containers. They are:
1. BeanFactory
2. ApplicationContext
Session 15 and 16
(Spring Boot Introduction)
• Micro Service is an architecture that allows the developers to develop and deploy
services independently. Each service running has its own process and this achieves
the lightweight model to support business applications.
Reasons for using Microservice:
• Spring Boot provides a good platform for Java developers to develop a stand-
alone and production-grade spring application that you can just run.
• You can get started with minimum configurations without the need for an entire
Spring configuration setup.
Advantages
• To ease the Java-based applications Development, Unit Test and Integration Test
Process.
• To reduce Development, Unit Test and Integration Test time by providing some
defaults.
• To increase Productivity.
Spring Boot Starters
Spring Boot is a module of Spring for packaging Spring MVC is a model view controller-based web
the Spring-based application with sensible framework under the Spring framework.
defaults.
It provides default configurations to build Spring- It provides ready to use features for building a
powered framework. web application.
There is no need to build configuration manually. It requires build configuration manually.
There is no requirement for a deployment A Deployment descriptor is required.
descriptor.
It avoids boilerplate code and wraps It specifies each dependency separately.
dependencies together in a single unit.
It reduces development time and increases It takes more time to achieve the same.
productivity.
(ThymeLeaf and Spring JPA)
Thymeleaf
• It is a server side Java template engine for web application. It's main goal is to
bring elegant natural templates to your web application.
• It can be integrate with Spring Framework and ideal for HTML5 Java web
applications.
In order to use Thymeleaf we must add it into our pom.xml file like:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
• Thymeleaf is a Java-based library used to create a web application. It provides a
good support for serving a XHTML/HTML5 in web applications.
It contains 6 types of templates as given below −
• XML
• Valid XML
• XHTML
• Valid XHTML
• HTML5
• Legacy HTML5
Spring Data JPA
• Spring Data JPA API provides JpaTemplate class to integrate spring application
with JPA.
• JPA (Java Persistent API) is the sun specification for persisting objects in the
enterprise application. It is currently used as the replacement for complex entity
beans.
• The implementation of JPA specification are provided by many vendors such as:
• Hibernate
• Toplink
• iBatis
• OpenJPA etc.
When to use Spring Data JPA?
• quickly create a JPA-based repository layer that is mainly for CRUD operations,
and you do not want to create abstract DAO, implementing interfaces, Spring Data
JPA is a good choice.
CrudRepository JpaRepository
CrudRepository does not provide any method for JpaRepository extends PagingAndSortingRepository. It
pagination and sorting. provides all the methods for implementing the
pagination.
It works as a marker interface. JpaRepository extends
both CrudRepository and PagingAndSortingReposit
ory.
It provides CRUD function only. For It provides some extra methods along with the method
example findById(), findAll(), etc. of PagingAndSortingRepository and CrudRepository.
For example, flush(), deleteInBatch().
It is used when we do not need the functions provided It is used when we want to implement pagination and
by JpaRepository and PagingAndSortingRepository. sorting functionality in an application.
Building REST services with
Spring
Introduction to web services
• REST stands for REpresentational State Transfer. REST is web standards based
architecture and uses HTTP Protocol. It revolves around resource where every
component is a resource and a resource is accessed by a common interface using
HTTP standard methods. REST was first introduced by Roy Fielding in 2000.
• In REST architecture, a REST Server simply provides access to resources and
REST client accesses and modifies the resources. Here each resource is identified
by URIs/ global IDs. REST uses various representation to represent a resource like
text, JSON, XML. JSON is the most popular one.
•
HTTP methods
• Following four HTTP methods are commonly used in REST based architecture.
• GET − Provides a read only access to a resource.
• POST − Used to create a new resource.
• DELETE − Used to remove a resource.
• PUT − Used to update a existing resource or create a new resource.
Spring Security
Introduction
• This is the filter that intercepts requests and attempts to authenticate it.
In Spring Security, it converts the request to an Authentication Object
and delegates the authentication to the AuthenticationManager.
• AuthenticationManager
It is the main strategy interface for authentication. It uses the lone method
authenticate() to authenticate the request. The authenticate() method performs the
authentication and returns an Authentication Object on successful authentication or
throw an AuthenticationException in case of authentication failure. If the method
can’t decide, it will return null. The process of authentication in this process is
delegated to the AuthenticationProvider which we will discuss next.
• AuthenticationProvider
The AuthenticationManager is implemented by the ProviderManager which
delegates the process to one or more AuthenticationProvider instances. Any class
implementing the AuthenticationProvider interface must implement the two methods
– authenticate() and supports(). First, let us talk about the supports() method. It is
used to check if the particular authentication type is supported by our
AuthenticationProvider implementation class. If it is supported it returns true or else
false. Next, the authenticate() method. Here is where the authentication occurs. If
the authentication type is supported, the process of authentication is started. Here is
this class can use the loadUserByUsername() method of
the UserDetailsService implementation. If the user is not found, it can throw a
UsernameNotFoundException.
• UserDetailsService
It is one of the core interfaces of Spring Security. The authentication of any request mostly
depends on the implementation of the UserDetailsService interface. It is most commonly
used in database backed authentication to retrieve user data. The data is retrieved with the
implementation of the lone loadUserByUsername() method where we can provide our logic
to fetch the user details for a user. The method will throw a UsernameNotFoundException if
the user is not found.
• PasswordEncoder
Until Spring Security 4, the use of PasswordEncoder was optional. The user could store
plain text passwords using in-memory authentication. But Spring Security 5 has mandated
the use of PasswordEncoder to store passwords. This encodes the user’s password using one
its many implementations. The most common of its implementations is the
BCryptPasswordEncoder. Also, we can use an instance of the NoOpPasswordEncoder for
our development purposes. It will allow passwords to be stored in plain text. But it is not
supposed to be used for production or real-world applications.
• Spring Security Context
• This is where the details of the currently authenticated user are stored on
successful authentication. The authentication object is then available throughout
the application for the session. So, if we need the username or any other user
details, we need to get the SecurityContext first. This is done with the
SecurityContextHolder, a helper class, which provides access to the security
context. We can use the setAuthentication() and getAuthentication() methods for
storing and retrieving the user details respectively.
Spring Testing
UNIT TESTS
• Running in isolation will sometimes require that you mock your dependencies
based on the class you are testing. By doing this, you're allowing yourself to test
very specific test cases end-to-end without having to worry about the overhead of
service or domain layers. Hence, using Mockito or more specifically, the
Mockito.mock() method which mocks object classes and DOES NOT replace any
objects on the web context such as @MockBean.
INTEGRATION TESTS
In unit testing each module of the software is tested In integration testing all modules of the the software are
separately. tested combined.
In unit testing tester knows the internal design of the In integration testing doesn’t know the internal design of the
software. software.
Unit testing is a white box testing. Integration testing is a black box testing.
Unit testing is basically performed by the developer. Integration testing is performed by the tester.
Detection of defects in unit testing is easy. Detection of defects in integration testing is difficult.
• @Test methods must not be private or static and must not return a value.
• The application is generally developed with multiple layers. A typical Java application has the
following layers:
• Web Layer: It exposes the services using the REST or web application.
• Business Layer: It implements the business logic of an application.
• Data Layer: It implements the persistence logic of the application.
• The responsibility of each layer is different, but there are a few common aspects that apply to all
layers are Logging, Security, validation, caching, etc. These common aspects are called cross-
cutting concerns.
What are cross-cutting concerns?
• In any application, there is some generic functionality that is needed in many places. But this
functionality is not related to the application's business logic. Suppose you perform a role-based
security check before every business method in your application. Here security is a cross-cutting
concern. It is required for any application but it is not necessary from the business point of view, it
is a simple generic functionality we have to implement in many places in the application. The
following are examples of the cross-cutting concerns for the enterprise application.
• AOP is non-invasive:
• Service or Domain classes get advice by the aspects (cross-cutting concerns) without adding Spring AOP related classes or
interfaces into the service or domain classes.
• Allows the developers to concentrate on the business logic, instead of the cross-cutting concerns.
• AOP is implemented in pure Java: There is no need for a special compilation unit or special class loader
• It uses Spring’s IOC container for dependency injection:
• Aspects can be configured as normal spring beans.
• Like any other AOP framework, it weaves cross-cutting concerns into the classes, without making a call to the cross-cutting
concerns from those classes.
• Centralizes or modularizes the cross-cutting concerns:
• Easy to maintain and make changes to the aspects.
• Changes only need to be made in one place.
• Provision to create aspects using schema-based (XML configuration) or @AspectJ annotation based style.
• Easy to configure.
Disadvantages of Spring AOP
1. A small difficulty is debugging the AOP framework-based application code.
Since the business classes are advised after the scene with aspects.
2. Since it uses proxy-based AOP, only method-level advising is supported; it does not support field-level
interception
So join-points can be at method level not at field level in a class.
3. Only methods with public visibility will be advised:
Methods with private, protected, or default visibility will not be advised.
4. There's small runtime overhead, but its negotiable:
The overhead is in nano-seconds.
5. Aspects cannot advise other Aspects - it's not possible to have aspects as targets of advice from other aspects.
Because once you mark one class as an aspect (either use XML or annotation), Spring excludes it from being
auto-proxied.
6. Local or internal method calls within an advised class don’t get intercepted by proxy, so the advice method of
the aspect does not get fired or invoked.
7. It is not for advising fine-grained objects (or domain objects)—it is best suitable for coarse-grained objects
due to performance.
Uses of Spring AOP