Servlet
Servlet
HTTP stands for Hyper Text Transfer Protocol which is an application level protocol for transferring textual data
between client and server.
HTTP is stateless protocol.
Web Client such as web browser sends the request to server, server responds and sends the requested data (such as
a HTML document) or returns error code and closes the connection. Once the response is returned, server
doesnt remember anything about the client.(even the very next request)
Http request methods and Headers
eg : URL -- http://www.server.com:8080/bank/login.jsp
Whenever the client sends the request to server for any resource such as a HTML document, it specifies
1. HTTP method (get/post/put/delete....)
2. Request URI (eg : /bank/login.jsp)
3. Protocol version
4. Optional Header information(eg : accept , cookies)
After the client sends the request, server processes the request and sends the response.
HTTP Response contains
1. Response status information(eg : 404/200)
2. Response headers (eg : cookies/resp cont type
eg : text/html, application/json image/gif.... /cont length)
3. Response data.
Following is an example of HTTP request which uses GET request method to ask for a HTML document named
tutorial.html using HTTP protocol version 1.1
GET /tutorial.html HTTP/1.1
Following is the example of request header, which provides additional information about the request.
User-Agent: Mozilla/4.0 (compatible; MSIE 4.0; Windows 95)
Accept: image/gif, image/jpeg, text/*, */*
Above header specifies the information about the client software and what MIME(Multi-purpose Internet Mail
Extension) type the client accepts in response, using User-Agent and Accept headers.
Http request methods
The request method indicates to the server what action to perform on the resource identified by the request-URI.
HTTP 1.1 specifies these request methods:
GET, POST , HEAD,OPTIONS, PUT, TRACE, DELETE, CONNECT.
Servlets can process any of the above requests.
But GET and POST methods are most commonly used.
The GET request method -- safe(doesn't change state of the resource) & idempotent (repeated reqs do not have
any further side effects after the first request)
The GET request is used typically for getting static information from the server such as HTML document, images,
and CSS files.
It can be used to retrieve dynamic information also by appending query string at the end of request URI.
Query String
Query string is used to pass additional request parameters along with the request.
Query string format
URL?name1=value1&name2=value&name3=value3 .
eg -- http://www.abc.com/test/login.jsp?userid=abc
The POST request method
The POST request method is typically used to access dynamic resources.
POST request is used to
1. send the large amount of data to the server.
2. upload files to servers
3. send serializable Java objects or raw bytes.
GET Vs POST
1. GET request sends the request parameters as query string appended at the end of the request URL, whereas
POST request sends the request parameters as part of the HTTP request body.
2.Unlike GET, POST request sends all the data as part of the HTTP request body, so it doesnt appear in browser
address bar and cannot be bookmarked.
3. GET -- non-secure, POST -secure
GET -- idempotent
POST---non-idempotent
Typically use GET -- to retrieve stuff from server.
use POST -- for changing some state on server(something like update)
4. Some web servers limit the length of the URL.
So if in GET request -- too many parameters are appended in query string and URL exceeds this length, some
web servers might not accept the request.
For POST -- no such limitations.
A web server is the combination of computer and the program installed on it.
Web server interacts with the client through a web browser. It delivers the web pages to the client and to an
application by using the web browser and the HTTP protocols respectively.
We can also define the web server as the package of large number of programs installed on a computer
connected to Internet or intranet for downloading the requested files using File Transfer Protocol, serving e-mail
and building and publishing web pages.
A web server works on a client server model. A computer connected to the Internet or intranet must have a server
program. While talking about Java language then a web server is a server that is used to support the web
component like the Servlet and JSP. Note that the web server does not support to EJB (business logic component)
component.
A computer connected to the Internet for providing the services to a small company or a departmental store may
contain the HTTP server (to access and store the web pages and files), SMTP server (to support mail services),
FTP server ( for files downloading) and NNTP server (for newsgroup). The computer containing all the above
servers is called the web server.
Internet service providers and large companies may have all the servers like HTTP server, SMTP server, FTP
server and many more on separate machines. In case of Java, a web server can be defined as the server that only
supports to the web component like servlet and jsp. Notice that it does not support to the business component like
EJB.
* The term web server can refer to either the hardware (the computer) or the software (the computer application)
that helps to deliver web content that can be accessed through the Internet.
* The most common use of web servers is to host websites, but there are other uses such as gaming, data storage
or running enterprise applications.
* The primary function of a web server is to deliver web pages to clients. The communication between client and
server takes place using the Hypertext Transfer Protocol (HTTP). Pages delivered are most frequently HTML
documents, which may include images, style sheets and scripts in addition to text content.
* A user agent, commonly a web browser or web crawler, initiates communication by making a request for a
specific resource using HTTP and the server responds with the content of that resource or an error message if
unable to do so. The resource is typically a real file on the server's secondary storage, but this is not necessarily
the case and depends on how the web server is implemented.
* While the primary function is to serve content, a full implementation of HTTP also includes ways of receiving
content from clients. This feature is used for submitting web forms, including uploading of files.
* Many generic web servers also support server-side scripting using Active Server Pages (ASP), PHP, or other
scripting languages. This means that the behaviour of the web server can be scripted in separate files, while the
actual server software remains unchanged. Usually, this function is used to create HTML documents dynamically
("on-the-fly") as opposed to returning static documents. The former is primarily used for retrieving and/or
modifying information from databases. The latter is typically much faster and more easily cached but cannot
deliver dynamic content.
Content Type
Content Type is also known as MIME (Multipurpose internet Mail Extension) Type. It is a HTTP header that
provides the description about what are you sending to the browser.
MIME is an internet standard that is used for extending the limited capabilities of email by allowing the insertion
of sounds, images and text in a message.
List of Content Types
There are many content types. The commonly used content types are given below:
text/html, text/plain, application/msword, application/jar , application/pdf , mages/jpeg , images/png ,images/gif,
audio/mp3, video/mp4
Version Java EE 7 (J2EE 1.7)
What is J2EE ?
Consists of specifications only .
Which specs ? (Rules or contract )
Specifications of services required for any enterprise application.
What is enterprise application ?
-An enterprise application (EA) is a large software system platform designed to operate in a corporate
environment -It includes online shopping and payment processing, interactive product catalogs, computerized
billing systems, security, content management, IT service management, business intelligence, human resource
management, manufacturing, process automation, enterprise resource planning ....
These specifications include ---
Servlet API,JSP(Java server page) API,Security,Connection pooling ,EJB (Enterprise Java Bean), JNDI(Naming
service -- Java naming & directory i/f),JPA(java persistence API),JMS(java messaging service),Java Mail, Java
Server Faces , Java Transaction API, Webservices support etc...
* Vendor of J2EE specs -- Oracle / Sun.
Implementation -- left to vendors (J2EE server vendors)
J2EE compliant web server --- Apache -- Tomcat (web container)
Services implemented --- servlet API,JSP API,Security,Connection pooling,JNDI(naming service)
These specifications include ---
Servlet API,JSP(Java server page) API,Security,Connection pooling ,EJB (Enterprise Java Bean), JNDI(Naming
service -- Java naming & directory i/f),JPA(java persistence API),JMS(java messaging service),Java Mail, Java
Server Faces , Java Transaction API, Webservices support etc...
* Vendor of J2EE specs -- Oracle / Sun.
Implementation -- left to vendors (J2EE server vendors)
J2EE compliant web server --- Apache -- Tomcat (web container)
Services implemented --- servlet API,JSP API,Security,Connection pooling,JNDI(naming service)
WHY J2EE
1. Can support different types of clnts --- thin client(web clnt)
thick clnt --- application clnt
smart clnts -- mobile clnts
2. J2EE server independence --- Create & deploy server side appln --on ANY J2ee compliant server ---
guaranteed to produce SAME results w/o touching or re-deploying on ANY other J2EE server
3. Ready made implementation of primary services(eg --- security, conn,pooling,email....)--- so that J2EE
developer DOESn't have to worry about primary services ---rather can concentrate on actual business logic.
-------------------------------------------------------------------------------------------------------------------
Layers involved in HTTP request-response flow
Web browser sends the request (URL)
eg : http://www.abc.com:8080/day1.1/index.html
/day1.1 --- root / context path /web app name
----------------------------------------------------------------------
What is a Session?
* Session is a conversional state between client and server and it can consists of multiple request and response
between client and server. Since HTTP and Web Server both are stateless, the only way to maintain a session is
when some unique information about the session is passed between server and client in every request and
response.
* HTTP protocol and Web Servers are stateless, what it means is that for web server every request is a new
request to process and they cant identify if its coming from client that has been sending request previously.
* But sometimes in web applications, we should know who the client is and process the request accordingly. For
example, a shopping cart application should know who is sending the request to add an item and in which cart the
item has to be added or who is sending checkout request so that it can charge the amount to correct client
What is the need of session tracking?
1. To identify the clnt among multiple clnts
2. To remember the conversational state of the clnt(eg : list of the purchased books/ shopping cart)
throughout current session
session = Represents duration or time interval
* Consists of all requests/resps coming from/to same clnt from login to logout or till session expiration tmout.
(def tmout for Tomcat =30mins)
There are several techniques for session tracking.
1. Plain Cookie based scenario
2. HttpSession interface
3. HttpSession + URL rewriting
Techniques
1. Plain Cookie based scenario
What is a cookie?
Cookie is small amount of text data.
Created by -- server (servlet or JSP prog) & downloaded (sent) to clnt browser---within response header
Cookie represents data shared across multiple dyn pages from the SAME web appln.
Steps :
1. Create cookie/s instance/s
javax.servlet.http.Cookie(String cName,String cVal)
2.Add the cookie/s to the resp hdr.
HttpServletResponse API :
void addCookie(Cookie c)
3. To retrieve the cookies :
HttpServletRequest :
Cookie[] getCookies()
4.Cookie class methods :
String getName()
String getValue()
void setMaxAge(int ageInSeconds)
def age =-1 ---> browser stores cookie in cache
=0 ---> clnt browser should delete cookie
>0 --- persistent cookie --to be stored on clnt's hard disk.
int getMaxAge()
Disadvantages of pure cookie based scenario
0. Web dev (servlet prog) has to manage cookies.
1. Cookies can handle only text data : storing Java obj or bin data difficult.
2. As no of cookies inc., it will result into increased net traffic.
3. In cookie based approach : entire state of the clnt is saved on the clnt side. If the clnt browser rejects the
cookies: state will be lost : session tracking fails.
How to redirect client automatically to next page ? (in the NEXT request)
API of HttpServletResponse
public void sendRedirect(String redirectLoc)
eg : resp.sendRedirect("s2");
IMPORTANT :
WC -- throws
java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed(eg :
pw.flush(),pw.close()...)
Technique # 2 : Session tracking based on HttpSession API
In this technique , entire state of the client is saved on the server side data structure (Http Sesion object)
BUT the key to this Http Session object is STILL sent to client in form of a cookie.
*Above mentioned , disadvantages ---0, 1 & 2 are reomved.
BUT entire session tracking again fails , if cookies are disabled.
Steps for javax.servlet.http.HttpSession i/f based session tracking.
1. Get Http Session object from WC
API of HttpServletRequest ---
HttpSession getSession()
Desc --- Servlet requests WC to either create n return a NEW HttpSession object(for new clnt) or ret the existing
one from WC's heap.
* Above method creates either a NEW HTTP session obj for new user or returns existing HTTP session object for
old user.
HttpSession --- i/f from javax.servlet.http
NEW --- HttpSession<String,Object> --empty map
String,Object ---- (entry)= attribute
OR
HttpSession getSession(boolean create)
2. : How to save data in HttpSession?(scope=entire session)
API of HttpSession i/f
public void setAttribute(String attrName,Object attrVal)
equivalent to map.put(k,v)
eg : hs.setAttribute("cart",l1);
3. For retrieving session data(getting attributes)
public Object getAttribute(String attrName)
4. To get session ID (value of the cookie whose name is jsessionid -- unique per client)
String getId()
4.5 How to remove attribute from the session scope?
public void removeAttribute(String attrName
5. How to invalidate session?
HttpSession API
public void invalidate()
(WC marks HS object on the server side for GC ---BUT cookie is NOT deleted from clnt browser)
6. HttpSession API
public boolean isNew()
7.How to find all attr names from the session ?
public Enumeration<String> getAttributeNames()
--rets java.util.Enumeration of attr names.
What is an attribute ?
* Attribute = server side object(entry/mapping=key value pair)
* Who creates server side attrs ? -- web developer (servlet or JSP prog)
Each attribute has --- attr name(String) & attr value (java.lang.Object)
Attributes can exist in one of 3 scopes --- req. scope,session scope or application scope
1. Meaning of req scoped attr = attribute is visible for current req.
2. Meaning of session scoped attr = attribute is visible for current session.(shared across multiple reqs
coming from SAME clnt)
3. Meaning of application scoped attr = attribute is visible for current web appln.(shared across multiple
reqs from ANY clnt BUT for the SAME web application)
-----------------------------------------------------------------------------------------------------------------------------
Why J2EE
1. can support diff clnts 2. server inde. (How -- separation bet specs & imple)
3. rdy imple of prim services
what is it ?
specs --- rules/contract
prim services/ enterprise services
eg : servlet / JSP /JB,conn pooling , security,JTA..... * vendor -- Oracle/sun
Request response flow(Layers)
URL --- http://www.abc.com:8080/day2_web/validate?em=abc&pass=1234
Layers --- Host(IP) ---Web Server(Tomcat --TCP)--WC(s.s JVM , run time env dyn web comps --
servlets,JSP,Filter)---web app (/day2_web)--
URI ---/ctx path /url-pattern ? query string
J2EE compliant web app folder structure
<day2_web>
<WEB-INF> -- web.xml , <classes> , <lib>
private from clnt
root (WebContent) --public
html/JSP/css/js/images...
<src> -- java source files
What is a Servlet ?
Its jobs
1. rq processing 2. B.L 3. page navigation
(taking clnt from 1 pgae to another ---clnt pull / server pull)
4. Manage DAO 5. resp gen.
How do you create n deploy a servlet ?
public class Test exetnds H.S{
@Override
protected/public void doGet(HSReq rq,HSResp rs) throws SE,IOExc
{ }
}
javax.servlet.ServeltException
public ServletException(String message,
Throwable rootCause)
Centralized err handling in Servlets
How ?
@Override
public void init() throws ServletException
{
try {
// create dao inst
} catch(Exception e)
{
throw new ServletException("err in init" +getClass().getName(),e);
}
}
eg : @WebServlet("/validate)
public class LoginServlet extends H.S {....}
OR xml tags
1. What will happen if u don't add / in url pattern ? --error(web app doesn't get deployed --- invalid url pattern
(IllegalArgumentException))
2. What will happen --if u add "/url-pattern" in form action or href ? --- HTTP 404 (uses absolute url eg :
http://host:port/hi)
load-on-startup
@WebServlet annotation
load-on startup --def value =-1
eg : @WebServlet(value={"/hi","/hello"},loadOnStartup=1)
public class Servlet1 extends H.S {...}
@WebServlet("/test")
public class Servlet2 extends H.S {...}
use case of loadOnStartup
--in case of time consuming init methods(eg : DAO inst DispatcherServlet of Spring MVC)
How to read request params sent from the clnt ?
javax.servlet.ServletRequest i/f methods
1. public String getParameter(String paramName)
2. public String[] getParameterValues(String paramName)
Servlet--JDBC integration
Layers involved
Servlet --DAO(DBUtils) -- POJO -- DB
LoginServlet
D.M -- dao
init --- DAO inst
destroy --- Dao's clean up
doGet
1. set cont type
2. pw
3. read rq params
4. invoke Dao's --validate
null --- Invalid login --retry link
not null ---mesg , display customer dtls
Objective
Complete login--logout flow
(login.html -- LoginServlet --successful login --redirect to DetailsServlet --logout link --LogOutServlet
How to redirect client ?
Page navigation --client pull
Refer to page navigation techniques.
What will happen if u explicitely flush/close PrintWriter & then invoke sendRedirect ?
WC throws ---java.lang.IllegalStateException --
reason --Can't redirect the clnt (empty the buffer's contents) after committing the response.
* IMPORTANT --- copy context.xml from "j2ee_help\day1_help\config files" in your <tomcat>/conf
**What will happen if you invoke sendRedirect after committing the response(pw.flush/pw.close)?
ANS-----WC throws java.lang.IllegalStateException
* Standard practise : Don't access PW or set content type in case of redirect.
* HttpServletRequest ---getSession vs getSession(create)
JSP-Java Servlet Pages
What is JSP? (Java server pages)
Dynamic Web page (having typically HTML markup) , can embed Java code directly.
Dynamic web component , whose life-cycle is managed by WC(JSP container/Servlet container/Servlet engine)
WHY JSP?
1. JSP allows developer to separate presentation logic(dyn resp generation) from Business logic or data
manipulation logic.
Typically JSPs -- used for P.L(presentation logic)
Java Beans or Custom Tags(actions) --- will contain Business logic.
2. Ease of development --- JSP pages are auto. translated by W.C in to servlet & compiled & deployed.
3. Can use web design tools -- for faster development (RAD --rapid application development) tools.
JSP API
jsp-api.jar --- <tomcat>/lib
Contains JSP API implementation classses.
0. javax.servlet.Servlet -- super i/f
1. javax.servlet.jsp.JspPage -- extends Servlet i/f
1.1 public void jspInit()
1.2 public void jspDestroy()
Can be overridden by JSP page author
2. Further extended by javax.servlet.jsp.HttpJspPage
2.1 public void _jspService(HttpServletRequest rq,HttpServletResponse rs) throws ServletExc,IOExc.
Never override _jspService ---JSP container auto translates JSP tags (body) into _jspService.
**JSP life-cycle**
1. Clnt sends the 1st request to the JSP (test.jsp)
2. Web-container invokes the life cycle for JSP
3. Translation Phase : handled by the JSP container.
I/p : test.jsp O/p : test_jsp.java (name : specific to the Tomcat container)
Meaning : .jsp is translated into corresponding servlet page(.java)
Translation time errs : syntactical errs in using JSP syntax.
In case of errs : life-cycle is aborted.
4. Compilation Phase : handled by the JSP container.
I/p : Translated servlet page(.java) O/p : Page Translation class(.class)
Meaning : servlet page auto. compiled into .class file
Compilation time errs: syntacticle errs in generated Java syntax.
5. Request processing phase / Run time phase. : typically handled by the Servlet Container.
6. S.C : will try to locate,load,instantiate the generated servlet class.
7. The 1st it calls : public void jspInit() : one time inits can be performed.(jspInit availble from
javax.servlet.jsp.JspPage)
8. Then it will call follwing method using thrd created per clnt request :
public void _jspService(HttpServlet Rq,HttpServletResponse) throws ServletException,IOException(API avlble
from javax.servlet.jsp.HttpJspPage)
When _jspService rets , thread's run method is over & thrd rets to the pool, where it can be used for servicing
some other or same clnt's req.
9.. At the end ...(server shutting down or re-deployment of the context) : the S.C calls
public void jspDestroy()
After this : translated servlet page class inst. will be GCEd....
10 For 2nd req onwards ...... : SC will invoke step 8 onwards.
------------------------------------------------------------------------------------------------------------------------------------
JSP 2.0/2.1/2.2 syntax
1. JSP comments
1.1 server side comment
syntax : <%-- comment text --%>
significance : JSP translator & compiler ignores the commented text.
1.2 clnt side comment
syntax : <!-- comment text -->
significance : JSP translator & compiler does not ignore the commented text BUT clnt browser will ignore it.
2. JSP's implicit objects (available only to _jspService) -- avlable to scriptlets,exprs
2.1 out - javax.servlet.jsp.JspWriter : represents the buffered writer stream connected to the clnt via
HttpServletResponse(similar to your PW in servlets)
Has the same API as PW(except printf)
usage eg : out.print("some text sent to clnt");
2.2 request : HttpServletRequest (same API)
2.3 response : HttpServletResponse
2.4 config : ServletConfig (used for passing init params)
2.4 session : HttpSession (By def. all JSPs participate in session tracking i.e session obj is created)
2.5 exception : java.lang.Throwable (available only to err handling pages)
2.6 pageContext : current page environment : javax.servlet.jsp.PageContext(this class stores references to page
specific objects viz -- exception,out,config,session)
2.7 application : ServletContext(used for Request dispatching, server side logging, for creating context
listeners,to avail context params, to add/get context scoped attrs)
2.8 page --- current translated page class instance created for 'this' JSP
3. Scripting elements : To include the java content within JSP : to make it dynamic.
3.1 Scriptlets : can add the java code directly . AVOID scriptlets . (till Javabeans & custom tags or JSTL, we will
use use the scriptlets to add : Req. processing logic, B.L & P.L)
syntax : <% java code...... %>
location inside the translated page : within _jspService
usage : till JBs or cust. tags are introduced : scriptlets used for control flow/B.L/req. proc. logic
3.2 JSP expressions :
syntax : <%= expr to evaluate %>
--Evaluates an expression --converts it to string --send it to clnt browser.
eg : <%= new Date() %>
expr to evaluate : java method invocation which rets a value OR
const expr or attributes(getAttribute) or variables(instance vars or method local)
location inside the translated page : within _jspService
significance : the expr gets evaluated---> to string -> automatically sent to clnt browser.
eg <%= new Date() %>
eg <%= request.getAttribute("user_dtls") %>
<%= 12*34*456 %>
<%= session.getAttribute("user_dtls") %>
<%= session.setAttribute("nm",val) %>
<%= session.getId() %>
Better alternative to JSP Expressions : EL syntax (Expression Lang. : avlble from JSP 1.2 onwards)
syntax : ${expr to evaluate} (to be added directly in body tag)
EL syntax will evaluate the expr ---toString --sends it clnt browser.
JSP implicit object --- request,response,session....---accessible from scriptlets & JSP exprs. --- accessible to
scriptlets/exprs
EL implicit objects --- can be accessible only via EL syntax
param = map of request parameters
pageScope=map of page scoped attrs
requestScope=map of request scoped attrs
sessionScope=map of session scoped attrs
applicationScope=map of application(=context) scoped attrs
pageContext --- instance of PageContext's sub class
---avlable ONLY to EL syntax ${...}
---to be added directly within <body> ...</body>
eg : ${param.user_nm} ---to string ---clnt browser
***request.getParameter("user_nm") ---to string --sent to clnt browser.
-*- ${requestScope.abc} ---request.getAttribute("abc") ---to string --sent to clnt browser.
eg : suppose ctx scoped attr --- loan_scheme
${applicationScope.loan_scheme} --- getServletContext().getAttirbute("loan_scheme") ---to string --sent to clnt
${user_dtls} --- null -- blank
${abc} ---
pageContext.getAttribute("abc") ---not null -- to string -clnt
null
--request.getAttribute("abc") -- not null -- to string -clnt
null
session.getAttribute("abc") ---
null
getServletContext().getAttirbute("abc") --not null -- to string -clnt
null ---BLANK to clnt browser.
eg : ${sessionScope.nm}
${pageContext.session.id}
--pageContext.getSession().getId() --- val of JessionId cookie w/o java code.
--${pageContext.request.contextPath} ---/day5_web
--${pageContext.session.maxInactiveInterval}
----
${param}
{user_nm=asdf, user_pass=123456}
eg : ${param.f1} ---> request.getParameter("f1").toString()---> sent to browser
param ----map of req parameters.
* param : req. param map
--${requestScope.abc} ----- out.print(request.getAttribute("abc").toString())
**${abc} -----pageCotext.getAttribute("abc")----null ---request ---session---application ---null ---EL prints blank.
JSP Directives --- commands/messages for JSP Engine(=JSP container=WC) -- to be used @Translation time.
Syntax ---
<%@ Directive name attrList %>
1. page directive
--- all commands applicable to current page only.
Syntax
<%@ page import="comma separated list of pkgs" contentType="text/html" %>
eg -- <%@ page import="java.util.*,java.text.SimpleDateFormat" contentType="text/html" %>
Imp page directive attributes
1. import --- comma separated list of pkgs
2. session --- boolean attribute. def=true.
To disable session tracking, spectify session="false"
3. errorPage="URI of err handling page" ---
tells WC to forward user to err handler page.
4. isErrorPage="true|false" def = false
If u enable this to true--- one can access 'exception' implicit object from this page.
--This exception obj is stored under current page ---i.e under pageContext (type=javax.servlet.jsp.PageContext --
class which represents curnt JSP)
EL expresssion to display error mesg
${pageContext.exception.message}
-- evals to pageContext.getException().getMessage()
Additional EL syntax
EL syntax to be used in error handling pages
ERR causing URI : ${pageContext.errorData.requestURI }<br/>
ERR code : ${pageContext.errorData.statusCode}<br/>
ERR Mesg : ${pageContext.exception.message} <br/>
Throwable : ${pageContext.errorData.throwable}<br/>
Throwable Root cause: ${pageContext.errorData.throwable.cause}
5. isThreadSafe="true|false" default=true. "true" is recommended
true=>informing WC--- JSP is already written in thrd -safe manner ---- DONT apply thrd safety.
false=>informing WC --- apply thrd safety.
(NOT recommended) ---WC typically marks entire service(servlet scenario) or _jspService in JSP scenarion ---
synchronized. --- this removes concurrent handling of multiple client request --so not recommended.
What is reco? --- isThreadSafe=true(def.) --- identify critical code--wrap it in synchronized block.
eg ---Context scoped attrs are inherently thrd -un safe. So access them always from within synched block.
Equivalent step in Servlet
Servlet class can imple. tag i/f -- javax.servlet.SingleThreadModel(DEPRECATED) -- WC ensures only 1thread
(representing clnt request) can invoke service method. --NOT NOT recommended.
2. include directive
<%@ include file="URI of the page to be included" %>
Via include directive ---- contents are included @ Translation time.--- indicates page scope(continuation of the
same page).
Typically used -- for including static content (can be used to include dyn conts)
eg ---one.jsp
<%@ include file="two.jsp" %>
two.jsp.....
JSP actions ---- commands/mesgs meant for WC
to be interpreted @ translation time & applied @ req. processing time.(run time)
Syntax ---standard actions --implementation classes are present in jsp-api.jar.
<jsp:actionName attr list>Body of the tag/action
</jsp:actionName>
JSP Using Java beans
Why Java Beans?
1. allows prog to seperate B.L in JBs.(Req processing logic, Page navigation & resp generation will be still part
of JSP)
JBs can store conversational state of clnt(JB 's properties will reflect clnt state) + supplies Business logic methods.
2. simple sharing of JBS across multiple web pages---gives rise to re-usability.
3. Auto. translation between req. params & JB props(string--->primitive data types auto. done by WC)
What is JB?
1. pkged public Java class
2. Must have def constr.(MUST in JSP using JB scenario)
3. Properties of JBs --- private, non-static , non-transient Data members --- equivalent to request params sent by
clnt.(Prop names MUST match with req params for easy usage)
In proper words --- Java bean props reflect the conversational state of the clnt.
4. per property -- if RW
naming conventions of JB
supply getter & setter.
Rules for setter
public void setPropertyName(Type val)
Type -- prop type.
eg -- private double regAmount;
public void setRegAmount(double val)
{...}
Rules for getter
public Type getPropertyName()
Type -- prop type.
eg -- public double getRegAmount(){...}
http://localhost:8080/day6_web/transactions.jsp?acId=102&amount=500&btn=Deposit
<c:redirect url="${sessionScope.my_bank.closeAccount()}"/>
WC --- response.sendRedirect(session.getAttribute("my_bank").closeAccount());
3.3 JSTL action --- for URL rewriting
<c:url var="attr Name" value="URL to be encoded" scope="page|request|session|application"/>
eg : <c:url var="abc" value="next.jsp" />
WC invokes --- pageContext.setAttribute("abc",resp.encodeURL("next.jsp"));
<a href="${abc}">Next</a>
var -- loop var
items -- any JB 's prop --- array based,coll based (List or set) map based
How to set session tm out ?
1. programmatically --- using Java API
From HttpSession --- setMaxInactiveInterval(int secs)
2. declarativally -- either using Java annotations OR using XML config files (web.xml)
Note : when u dont specify form action , its submitted to the same page.
Expression Language implicit variables(case sensitive)
1. pageContext : PageContext object (javax.servlet.jsp.PageContext) asso. with current page.
2. pageScope - a Map that contains page-scoped attribute names and their values.
3. requestScope - a Map that contains request-scoped attribute names and their values.
4. sessionScope - a Map that contains session-scoped attribute names and their values.
5. applicationScope - a Map that contains application-scoped attribute names and their values.
6. param - a Map that contains rq. parameter names to a single String parameter value (obtained by calling
ServletRequest.getParameter(String name)).
7. paramValues - a Map that contains rq. param name to a String[] of all values for that parameter (similar
to calling ServletRequest.getParameterValues(name)
8. initParam - a Map that contains context initialization parameter names and their String value (obtained
by calling ServletContext.getInitParameter(String name)).
eg : ${initParam.db_drvr}
9. cookie : Map.Entry of cookies. (entrySet of cookies)
eg : ${cookie.cookiename.value}
key ---cookie name
value ---javax.servlet.http.Cookie
${cookie.JSESSIONID.value}
---cookie.get("JSESSIOIND").getValue()
10. To retrieve err details from Error handling page.
ERR causing URI : ${pageContext.errorData.requestURI }
ERR code : ${pageContext.errorData.statusCode}
ERR Mesg : ${pageContext.exception.message }
Throwable : ${pageContext.errorData.throwable}
Throwable Root cause: ${pageContext.errorData.throwable.cause}
eg :
<c:set var="abc" scope="session" value="Hello User...."/>
${sessionScope.abc}
OR EL syntax
${sessionScope.cust.details}
4. How to invoke B.L method of JB , w/o java code from JSP? ---EL syntax
${sessionScope.cust.authenticateCustomer()}
WC ---session.getAttribute("cust").authenticateCustomer()
<jsp:forward page="${sessinScope.cust.authenticateCustomer()}.jsp"/>
WC --- RD rd=request.getRD(session.getAttribute("cust").
authenticateCustomer().concat(".jsp"));
rd.forward(request,response);
What is Hibernate ?
0. Complete solution to the problem of managing persistence in Java.
1. ORM tool.(Object Relational Mapping) used mainly in data access layer or DAO layer.
2. Provides automatic & transperent persistence.
3. JPA(Java Persistence API) implementor
JPA vs Hibernate
JPA ---part of J2EE specification --vendor --J2EE (sun)
Implementation classes -- JAR ---hibenrate core JARs(implementor of JPA)
* Provides automatic & transparent persistence framework to store & retrieve data from database.
* Open Source Java based framework founded by Gavin King in 2001, hosted on hibernate.org
* Currently hosted on sourceforge.net
Java Persistence API (JPA) compliant
Current version Hibernate 5.x
Other popular ORM Frameworks
EclipseLink,iBATIS,Kodo etc.
WHY Hibernate?
* It mediates the applications interaction with a relational database, leaving the developer free to concentrate on
the business problem at hand.
* J2EE developer does not have to use JDBC API & manage data persistence at RDBMS level.
* No need to go to Table/Query/Column level.
* One has to bootstrap Hibernate framework , create transient(=not yet persistent) POJOs & then rely entirely on
Hibernate frmwork to manage persistence
There is huge mismatch between Object & Relational world.
Formally referred as -- Object-Relational Impedance Mismatch' (sometimes called the 'paradigm mismatch)
Important Mismatch Points
1. Granularity 2. Sub Types or inheritance n polymorphism
3. Identity 4. Associations 5. Data Navigation
Cost of Mismatch
1.SQL queries in Java code 2.Iterating through ResultSet & mapping it to POJOs or entities.
3.SQL Exception handling. 4. Transaction management 5. Caching
6. Connection pooling 7. Boiler plate code
Hibernate Frmwork --- popular ORM Tool ---JPA (Java perssitence API) provider
* Hibernate 4.x --- JPA compliant --- Java persistence API --- Its part of J2EE specifications. ---Is fully JPA
compliant
* BUT it also has additional services / annotations --- specific to Hibernate.
* Dev MUST add hibernate JARs ---while deploying appln on web server. Need not add JPA provider JARs ,
while working on appln server.
* Transparent persistence provider.(As POJOs or Entities are not bound to any Persistence API --- its written
completely independent of Persistence Provider.)
--Fully supports OOP features --- association,inheritance & polymorphism
--can persist object graphs , consisting of asso. objects
--caches data which is fetched repeatedly (via L1 & L2 cache) -- thus reduces DB traffic(L1 cache - at session
level -- built in. L2 cache - pluggable) (More on caching at end of document)
--supports lazy loading -- thus increases DB performance.
(Meaning --- Lazy fetchingThe associated object or collection is fetched lazily, when its first accessed. This
results in a new request to the database (unless the associated object is cached). Eager fetchingThe associated
object or collection is fetched together with the owning object, using an SQL outer join, and no further database
request is required.
Advantages of hibernates:
1. Hibernate supports Inheritance, Associations, Collections.
2. In hibernate if we save the derived class object, then its base class object will also be stored into the database,
it means hibernate supporting inheritance
3. Hibernate supports relationships like One-To-Many,One-To-One, Many-To-Many-to-Many, Many-To-One
4. This will also supports collections like List,Set,Map (Only new collections)
5. In jdbc all exceptions are checked exceptions, so we must write code in try, catch and throws, but in hibernate
we only have Un-checked exceptions, so no need to write try, catch, or no need to write throws. Actually in
hibernate we have the translator which converts checked to Un-checked ;)
6. Hibernate has capability to generate primary keys automatically while we are storing the records into database
7. Hibernate has its own query language, i.e hibernate query language which is database independent
So if we change the database, then also our application will works as HQL is database independent
HQL contains database independent commands
8. While we are inserting any record, if we dont have any particular table in the database, JDBC will rises an error
like View not exist, and throws exception, but in case of hibernate, if it not found any table in the database this
will create the table for us ;)
9. Hibernate supports caching mechanism by this, the number of round trips between an application and the
database will be reduced, by using this caching technique an application performance will be increased
automatically.
Hibernate supports annotations, apart from XML
10. Hibernate provided Dialect classes, so we no need to write sql queries in hibernate, instead we use the
methods provided by that API.
11. Getting pagination in hibernate is quite simple.
Persistent Object Life cycle
1.Transient State
* An object is said to be in transient state if it is not associated with the session,and has no matching record
in the database table.
* Account account=new Account();
account.setAccno(101);
2.Persistent State
* An object is said to be in persistent state if it is associated with session
object (L1 cache) and will result into a matching record in the databse table.(i.e upon commit)
* session.save(account);tx.commit();
or Account account=session.get(Account.class,102);
* When the object is in persistent state it will be in synchronization with the matching
record i.e if we make any changes to the state of persistent object it will be
reflected in the database.(after commiting tx) -- i.e automatic dirty checking will be performed.
3.Detached state
Object is not associated with session but has matching record in the database table. If we make any changes to the
state of detached object it will NOT be reflected in the database.
* session.clear(); *session.evict(Object); *session.close();
Note :By calling update method on session object it will go from detached state to persistent state.
By calling delete method on session object it will go from persistenet state to transient state.
* Explain the following methods of Session API
public void persist(Object ref) -- Persists specified transient POJO on underlying DB , upon comitting the
transaction.
void clear()
When clear() is called on session object all the objects associated with the session object become detached.
But Databse Connection is not closed. (Completely clears the session. Evicts all loaded instances and cancel all
pending saves, updates and deletions)
void close()
When close() is called on session object all the objects associated with the session object become detached and
also closes the Database Connection.
* public void evict(Object ref)
* It detaches a particular persistent object detached or disassociates from the session. (Remove this instance from
the session cache. Changes to the instance will not be synchronized with the database. )
void flush()
* When the object is in persistent state ,whatever changes we made to the object state will be reflected in the
databse only at the end of transaction.
* If we want to reflect the changes before the end of transaction (i.e before commiting the transaction )
call the flush method. (Flushing is the process of synchronizing the underlying DB state with persistable state of
session cache )
* boolean contains(Object ref)
The method indicates whethere the object is associated with session or not.
void refresh(Object ref) -- ref --persistent or detached
This method is used to get the latest data from database and make corresponding modifications to the persistent
object state. (Re-read the state of the given instance from the underlying database)
public void update(Object ref)
If object is in persistent state no need of calling the update method .As the object is in sync with the database
whatever changes made to the object will be reflect to database at the end of transaction.
* When the object is in detached state record is present in the table but object is not in sync with database,
therefore update() method can be called to update the record in the table
Which exceptions update method can raise?
1. StaleStateException -- If u are trying to update a record (using session.update(ref)), whose id doesn't exist.
i.e update can't transition from transient --->persistent
* It can only transition from detached --->persistent.
eg -- update_book.jsp -- supply updated details + id which doesn't exists on db.
2. NonUniqueObjectException -- If there is already persistence instance with same id in session.
eg -- UpdateContactAddress.java
public Object merge(Object ref)
Can Transition from transient -->persistent & detached --->persistent.
Regarding Hibernate merge
1. The state of a transient or detached instance may also be made persistent as a new persistent instance by calling
merge().
2. API of Session
Object merge(Object object)
3. Copies the state of the given object(can be passed as transient or detached) onto the persistent object with the
same identifier.
3.If there is no persistent instance currently associated with the session, it will be loaded.
4.Return the persistent instance. If the given instance is unsaved, save a copy of and return it as a newly persistent
instance. The given instance does not become associated with the session.
5. will not throw NonUniqueObjectException --Even If there is already persistence instance with same id in
session.
* public void saveOrUpdate(Object ref)
The method persists the object (insert) if matching record is not found (& id inited to default value) or fires update
query If u supply Object , with non-existing ID -- Fires StaleStateException.
lock()
when lock() method is called on the session object for a persistent object ,untill the transaction is commited in
the hibernate application , externally the matching record in the table cannot be modified.
session.lock(object,LockMode);
eg - session.lock(account,LockMode.UPGRADE);
Annotation support from pkg : javax.persistence (JPA)
1. Mark the entity or POJO class with @Entity annotation
@Entity : class level ---mandatory
2. @Table(name="table name") : class level annotation ---optional
3. @Id : can be field level OR getter method level. ---mandatory
4. optional
@GeneratedValue(strategy=GenerationType.AUTO) --> id generator supplied by persistence provider(app srvr's
or ORM frmwork i.e hibernate) & not by DB
Mandatory Rule for Identifier property type---must be Serializable
5. @Column(name="col name ") --> not mandatory if same names
@Column(columnDefinition= "double(10,2)")
private double price;
3,4,5 : applicable to Entity id property
6.@Column(name="upper-cased col name") : for rest of prop to col names mapping(optional)
eg : for additional @Column annotations (method level annotation)
NOTE : Annotations like -- @Id,@GeneratedValue,@Column,@ElementCollection,@Temporal
--can either be applied @ field level(before data member) or property level(before getter)
@Temporal --- can be applied to --java.util.Date,Calendar, GregorianCalendar
How to get Scrollable Result from Query?
* ScrollableResults scroll(ScrollMode scrollMode) throws HibernateException
* Return the query results as ScrollableResults. The scrollability of the returned results depends upon JDBC
driver support for scrollable ResultSets.
* Then can use methods of ScrollableResults ---first,next,last,scroll(n) .
7. How to create Named query from Session i/f?
What is a named query ?
Its a technique to group the HQL statements in single location(typically in POJOS) and lately refer them by some
name whenever need to use them. It helps largely in code cleanup because these HQL statements are no longer
scattered in whole code.
Fail fast: Their syntax is checked when the session factory is created, making the application fail fast in case of
an error.
Reusable: They can be accessed and used from several places which increase re-usability.
eg : In POJO class, at class level , one can declare Named Queries
8. How to invoke native sql from hibernate?
Query q=hs.createSQLQuery("select * from books").addEntity(BookPOJO.class);
l1 = q.list();
For composite primary key
Rules on prim key class
* Annotation -- @Embeddable (& NOT @Entity)
* Must be Serializable.
* Must implement hashCode & equals as per general contract.
In Owning Entity class
*Add usual annotation -- @Id.
Annotations related to relationships(associations) between entities
0. one -----> one : unidirectional relationship.
In Customer Entity class ---
@OneToOne(cascade=CascadeType.ALL)
@JoinColumn(name="addr_id")
private Address adr;
---owning side
In Address Entity --- no need of additional annotations.
1. one 1 <----> one : bidirectional relationship.
@OneToOne(cascade=CascadeType.ALL,mappedBy="cust")
private Address adr;
---owning side
@OneToOne
@JoinColumn(name="cust_id")
private Customer cust;
2. one 1 <---->* many : bi-directional
At one side : field level annotaion @OneToMany(cascade=CascadeType.ALL,mappedBy="propertyName in
many side")
NOTE -- cascade is optional attribute. can be skipped .
At many side :
@ManyToOne
@JoinColumn(name="prim key column name of one side")
Meaning - Acts as Foreign key column referred from one side
eg -- Course 1----* Students
Table structure for understanding ---
Course table --- course_id(PK),name,start_date,end_date,fees
Students table --- id(PK),name,addr,course_id(FK)
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int courseId;
@OneToMany(cascade=CascadeType.ALL,mappedBy="myCourse")
private List<Student> students;
In Student POJO
@ManyToOne
@JoinColumn(name="courseId")
private Course myCourse;
Annotations Used
1. @Embeddable : Defines a class whose instances are stored as an intrinsic part of an owning entity and share
the identity of the entity. Each of the persistent properties or fields of the embedded object is mapped to the
database table for the entity. It doesn't have own identifier.
eg : Address is eg of Embeddable
Student HAS-A Address(eg of Composition --i.e Address can't exist w/o its owning Entity i.e Student)
College HAS-A Address (eg of Composition --i.e Address can't exist w/o its owning Entity i.e College)
BUT Student will have its own copy of Address & so will College(i.e Value Types don't support shared reference)
2. @Embedded : Specifies a persistent field or property of an entity whose value is an instance of an embeddable
class. The embeddable class must be annotated as Embeddable.
eg : Address is embedded in College and User Objects.
3. @AttributesOverride : Used to override the mapping of a Basic (whether explicit or default) property or field
or Id property or field.
* In Database tables observe the column names. Student table having STREET_ADDRESS column and College
table having STREET column. These two columns should map with same Address field streetAddress.
@AttributeOverride gives solution for this.
To override multiple column names for the same field use @AtributeOverrides annotation.
3. Collection Value Types :
Hibernate allows to persist collections.
But Collection value Types can be either collection of Basic value types, Composite types and custom types.
Eg : Collection mapping means mapping group of values to the single field or property. But we cant store list of
values in single table column in database. It has to be done in a separate table.
eg : Collection of embeddables
@ElementCollection
@CollectionTable(name="CONTACT_ADDRESS", joinColumns=@JoinColumn(name="USER_ID"))
@AttributeOverride(name="streetAddress", column=@Column(name="STREET_ADDRESS"))
private List<ContactAddress> address;
eg : collection of basic type
@ElementCollection
@CollectionTable(name="Contacts", joinColumns=@JoinColumn(name="ID"))
@Column(name="CONTACT_NO")
private Collection<String> contacts;
Regarding ID generators
* Each entity must have a primary key, which you annotate on the class with the @Id annotation. Typically, the
primary key will be a single field, though it can also be a composite of multiple fields .
* The placement of the @Id annotation determines the default access strategy that Hibernate will use for the
mapping. If the annotation is applied to a field as shown below, then field access will be used.
@Id
private Integer employeeId;
If, instead, the annotation is applied to the accessor for the field then property access will be used.
@Id
public Integer getEmployeeId()
{ return employeeId; }
* Property access means that Hibernate will call the mutator/setter instead of actually setting the field directly,
what it does in case of field access. This gives flexibility to alter the value of actual value set in id field if needed.
Additionally, you can apply extra logic on setting of id field in mutator for other fields as well.
* By default, the @Id annotation will not create a primary key generation strategy, which means that you, , need
to determine what valid primary keys are, by setting them explicitly calling setter methods.
OR you can use @GeneratedValue annotation.
The strategy attribute must be a value from the javax.persistence.GeneratorType enumeration. If you do not
specify a generator type, the default is AUTO. There are four different types of primary key generators on
GeneratorType, as follows:
AUTO: Hibernate decides which generator type to use, based on the databases support for primary key
generation.
IDENTITY: The database is responsible for determining and assigning the next primary key.
SEQUENCE: Some databases support a SEQUENCE column type. It uses @SequenceGenerator.
TABLE: This type keeps a separate table with the primary key values. It uses @TableGenerator.
Regarding org.hibernate.LazyInitializationException
1. In JPA or hibernate --default fetching policy for Any--To--Many is -- LAZY
i.e if u try to fetch (using get/load/jpql) Course details(one side details) --hibernate WON't fetch student(many
side) details.(Confirm it by looking at select query)
So in Course object --in place of actual student data from db , its collection of PROXY (=un fetched data from db)
is kept.
When will hibernate throw this exception ?
If u try to access any un-fetched data from DB (represented by un-initilized proxy) from outside the session
scope(in detached manner) --- hibernate throws LazyInitExc
Triggers -- any-to-many association
session's load method.
Fix
1. POJO layer soln.
Change fetching policy of one-to-many to eager
@OneToMany(......,fetch=FetchType.EAGER)
public List<Student> getStudents(){...}
---not recommended (since it may cause a performance hit)
Use case --if the size of many is small (few)
Even if user wants ONLY course details , hib will fetch all associated student details --causing performance hit.
2. Soln in DAO layer
--Access the size of collection --from inside session scope.
Disadv --- complete data fetched using multiple queries(select n+1 problem)
3. Better alternative --- join fetch
String jpql="select c from Course c join fetch c.students where c.name=:nm"
WHY Spring ?
* To simplify Java development.
* It supports loose coupling of java objects using dependency injection & AOP(aspect oriented programming)
* Reduces boilerplate code.
* Spring eco system keeps evolving every day , to include multiple spring projects eg : Spring social,Cloud
support,microservices,spring boot etc.
* Suppports excellent integration support for ORM,JDBC(templates),MVC , RESTful web services...
What is spring?
* Its a container & a framework both.
Why Container --It manages life cycle of spring beans.
(spring bean --- java objects whose life cycle completely managed by SC(spring container)
eg : controller, service,DAO.
Why Framework --Supplies readymade implementation of standard patterns(eg :MVC,Proxy,singleton,factory,
ORM ...)
*Spring is modular n extensive framework. * Spring is an open source framework since February 2003.
* Created by Rod Johnson ,earlier published under Apache license. * Currently hosted on pivotal.
* One line answer --- Spring does not directly implement any of the J2EE specification BUT its created to
make developing complex J2EE applications easier.
*Why learn one more frmwork ? --- when u already have EJB,Struts,Hibernate etc....
Spring helps you to
1.Build applications from plain old Java objects (POJOs) (known as spring beans )
2. Apply enterprise services non-invasively.
(w/o invasion means --- POJOs DONT implement or extend from spring APIs) This capability applies to the
Java SE programming model and to full and partial Java EE.
Examples of how you, as an application developer, can use the Spring platform advantage:
Make a Java method execute in a database transaction without having to deal with transaction APIs.
Make a local Java method a remote procedure without having to deal with remote APIs.
Make a local Java method an ORM operation without having to deal with overheads of ORM set up.
Make a local Java method a web service end point , without having to deal with JAX WS or JAX RS setups.
*You can think of D.I as JNDI(Java naming & directory iterface -- Naming service) in reverse.
7.3 Aspect-oriented Spring supports aspect-oriented programming(AOP)
(AOP) allows separating application business logic from system services (such as auditing and transaction
management,logging , security,transactions).
* Application objects perform only business logic and nothing more.
* They are not responsible for (or even aware of) other system concerns, such as eg : logging , transactions, or
security
7.4 Why Spring is a Container ?
Spring is a container which manages the lifecycle and configuration of application objects.(spring beans)
In Spring, using config XMLs or annotations or java config, you can declare - how to create each of your
application objects(spring beans)
- how to configure them
- how they should be associated with each other.(collaboration/wiring/coupling=connecting dependencies
with dependent objs)
7.5 Why Spring is a framework ? Spring allows you to configure and compose complex applications from
simpler components. In Spring, application objects are composed declaratively, typically in an XML file or using
annotations
Spring also provides you with ready made implemetations of services like - transaction management, persistence
framework,web mvc etc.
Spring is unique, for several reasons:
1. It helps you in important areas that many other popular frameworks don't. eg : readymade Hibernate
templates.
2. Provides a way to manage your business objects - based on Dependeny injection(DI)
3.Spring is both comprehensive and modular.
Offers you lot many features, yet gives you choice to integrate layers one by one, test it & then add new features
via new layers.
4 Spring is an ideal framework for test driven projects.
5. It is basically a one-stop shop, addressing most of the concerns of typical enterprise applications.
6.Using Spring one can centrally describe collaborating objects. From the earliest versions of Spring, there was
an XML file that was used to describe the object graph.
Contents of XML ---- Consists of beans. Each bean element describes an object that will be created and given an
id. Each property element describes a setter method on the object and the value that should be given to it. These
setters are called for you by the Spring application container.
What is Spring ?
1. An open source framework since February 2003.
Created by Rod Johnson and described in his book Expert One-on-One: J2EE Design and Development.
Allows us to give capability of EJBs to plain JavaBeans without using an application server.
Any Java SE application can also use Spring to get simplicity, testability, and loose coupling.
2.Spring has been hosted on Pivotal
3. Spring is a lightweight framework. Most of your Java classes will have no dependency on Spring. This
means that you can easily transition your application from the Spring framework to any other frmwork.
(Framework independence)
4. All Java applications that consist of multiple classes have inter-dependencies or coupling between classes.
Spring helps us develop applications that minimize the negative effects of coupling and encourages the use of
interfaces in application development.
5. Using interfaces in our applications to specify type helps make our applications easier to maintain and enhance
later.
6. The Spring framework helps developers for separation of responsibilities.
eg scenario --
* Think of a situation Your manager tells you to do your normal development work(eg - write stock trading
appln) + write down everything you do and how long it takes you.
* A better situation would be you do your normal work, but another person observes what you re doing and
records it and measures how long it took.
* Even better would be if you were totally unaware of that other person and that other person was able to also
observe and record , not just yours but any other people s work and time.
* That s separation of responsibilities. --- This is what spring offers u thro AOP
8 Spring framework Modules
9. Advantages of ApplicationContext over BeanFactory
9.1Application contexts resolve text messages, including support for internationalization (I18N).
9.2 Application contexts provide a generic way to load file resources, such as images.
9.3Application contexts can publish events to beans that are registered as listeners.
IOC -- rather a generic term
Inversion of Control (IoC) is an object-oriented programming practice where the object coupling(dependent obj
bound with dependency) is bound at run time by an assembler object(eg spring container) and is typically not
known at compile time using static analysis.
* Unlike in traditional prog -- where dependent obj creates dependencies leading to tight coupling , container sets
the dependencies (not US --not a prog or not a dependent obj) ---so its inversion of control
* Dependency. injection=Ioc+dependency inversion
Why IoC or Dependency Injection (advantages of IoC)
* There is a decoupling of the execution of a certain task from implementation.
* Every module can focus on what it is designed for.
* Modules make no assumptions about what other systems do but rely on their contracts/specs (=i/f)
* Replacing modules has no side effect on other modules.
Inversion of Control is sometimes referred to as the "Hollywood Principle: Don't call us, we'll call you",
Dependency injection (DI) is the ability to inject dependencies. DI can help make your code architecturally pure.
It aids in using a design by interface approach as well as test driven development by providing a consistent way to
inject dependencies. For example a data access object (DAO) may need a database connection. Thus the DAO
depends on the database connection. Instead of looking up the database connection with JNDI, you could inject it.
or another eg is JMS -- conn factory or destination
One way to think about a DI container like Spring is to think of JNDI turned inside out. Instead of the objects
looking up other objects that it needs to get its job done (dependencies), with DI the container injects those
dependent objects. This is the so-called Hollywood principle, you don't call us (lookup objects), we will call you
(inject objects).
More on ApplicationContext
The instantiation of the ApplicationContext creates the container that consists of the objects defined in that XML
file.
The purpose of this XML file is to create the beans and their relationship.
This XML file is then provided to the ApplicationContext instance, which creates a container with these beans and
their object graphs along with relationships. The Spring container is simply a holder of the bean instances that
were created from the XML file.
An API (getBean) is provided to query these beans and use them accordingly from our client application.
IoC is also known as dependency injection (DI).
It is a process whereby objects define their dependencies,that is, the other objects they work with, 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.
The container then injects those dependencies when it creates the bean.
This process is fundamentally the inverse,( hence the name Inversion of Control (IoC)), of the bean itself
controlling the instantiation or location of its dependencies by using direct construction of classes, or a
mechanism such as the Service Locator pattern.
The org.springframework.beans and org.springframework.context packages are the
basis for Spring Framework's IoC container. The BeanFactory interface provides an advanced
configuration mechanism capable of managing any type of object. ApplicationContext is a
sub-interface of BeanFactory. It adds easier integration with Spring's AOP features; message resource handling
(for use in internationalization), event publication; and application-layer specific contexts such as the
WebApplicationContext for use in web applications.
What is spring ?
container --manages life cycle of spring beans (spring bean --- java objects whose life cycle completely managed
by SC(spring container)
eg : controller, service,DAO.
framework --rdymade implementation of std patterns(eg :MVC,Proxy,singleton,factory, ORM ...)
Spring is modular n extensive framework.
What is dependency injection ?
In JSP---JB---DAO -- POJO layers
Dependent Objs -- JavaBean , Hibernate based DAO, JDBC Based DAO
Dependencies --- DAO, SessionFactory , DB connection
9. The view will use the model data to render a page that will be sent as dyn resp back to the clnt browser.
object.
The ViewResolver provides a mapping between view names and actual views.
UrlBasedViewResolver Simple implementation of the ViewResolver interface thateffects the direct resolution of
logical view names to URLs, without an explicit mapping definition. This is appropriate if your logicalnames
match the names of your view resources in a straightforward manner, without the need for arbitrary mappings.
XML config Annotation
1. <bean id="abc" class="beans.TestBean"/>
class level annotations --stereotype annotations
@Component --ordinary spring bean
@Controller -- req handling spring bean
@Service ---B.L supplying bean
@Repository --DAO layer sping bean
@RestController -- RESTful service end point spring bean
2. scope="singleton|prototype"
@Scope --class level annotation
3. lazy-init="false|true"
@Lazy -- class level annotation
4. init-method
@PostConstruct --method level annotation
5. destroy-method
@PreDestroy --method level annotation
6. factory-method --no support in annotations
7. autowire=byType | constructor
@AutoWired ---It can appear before a setter / paramterized constr OR directly
Field level injection --- no setters , no paramed constrs ,add @Autowired directly to a field
eg : In VendorController
@AutoWired //required=true ---mandatory
private IVendorService service;
8. autowire=byName
eg : In VendorController bean
@AutoWired
@Qualifier("abc")
private IVendorService service;
1.2 In form (view ---jsp) -use spring form tags along with modelAttribute
Steps
1. import spring supplied form tag lib
2. Specify the name of modelAttribute under which form data will be exposed.(name of model attr mentioned in
the controller)
<s:form method="post" modelAttribute="user">
<s:input path="email"/>.....
</s:form>
1.3 Upon form submission (clnt pull I)
clnt sends a new req --- containing req params
@PostMapping("/reg")
public String processForm(User u,RedirectAttributes flashMap,HttpSession hs) {
//SC calls
User u=new User();
SC invokes MATCHING (req param names --POJO prop setters)
setters. -- conversational state is transferred to Controller.
adds pojo as model attr (in Model map)
map.addAttribute("user",u)
Thus you get a populated POJO directly in controller w/o calling <jsp:setProperty> & w/o using any java bean.
PRG pattern(Post-redirect-get pattern)
--- to avoid multiple submission issue in a web app.
Replace forward view(server pull) by redirect view (clnt pull) --a.k.a double submit guard.
How to replace default forward view by redirect view in spring MVC ?
Ans -- use redirect keyword.
eg : return "redirect:/vendor/details";
D.S invokes response.sendRedirect(response.encodeRedirectURL("/vendor/details"));
Next request from clnt --- ..../vendor/details
How to remember user details till logout?
Ans : add them in session scope.
How to access HttpSession in Spring?
Using D.I
How -- Simply add HttpSession as method argument of request handling method.
How to remember the details(attributes) till the next request (typically required in PRG --redirect view)
Ans -- Add the attributes under flash scope.
(They will be visible till the next request from the same clnt)
How to add ?
Use i/f -- o.s.w.s.mvc.support.RedirectAttributes
Method
public RedirectAttributes addFlashAttribute(String attrName,Object value)
MVC FLOW
P.L validations ---
Understanding hibernate-persistence.xml & tx management
1. Supply the location of DB property file .
<context:property-placeholder
location="classpath:/database.properties" />
2.Configure a spring bean , to create Apache supplied connection pool.
I/F --javax.sql.DataSource (represents Connection pool)
Imple class --Apache supplied --org.apache.commons.dbcp2.BasicDataSource
Inject CP properties via setter Based D.I
3. Configure SessionFactory bean , supplied by Spring.
i/f --org.hibernate.SessionFactory (hibernate supplied)
SF provider -- o.s.orm.hibernate5.LocalSessionFactoryBean
Inject SF properties via setter Based D.I
eg : packgesToScan, show_sql , hbm2ddl.auto
Inject the ref of CP bean into SF
4. Configure spring supplied tx manager bean , to automate tx management(using @Transactional)
I/F : o.s.transaction.PlatformTransactionManager
Implementation class --o.s.orm.hibernate5.HibernateTransactionManager
5. Enable annotation based tx supprt
<tx:annotationDriven/>
4. Understanding Transaction Management in Spring
How to automate Tx management in spring?
1. Add spring supplied tx manager bean in config file
<bean id="transactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory">
</bean>
2. Enable tx annotation support
<tx:annotation-driven />
3. Use @Transactional attribute typically in Service or DAO Layer.
4. How to customize tx management -- using @Transactional attributes
4.1 timeout
eg : @Transactional(timeout=100)
service/dao layer method
4.2 readOnly --
def value --false;
eg : @Transactional(readOnly=true)
4.3 @Transactional(rollbackFor = IOException.class, noRollbackFor = RuntimeException.class)
public void doSomething(...)
SOAP REST
• SOAP stands for Simple Object Access Protocol • REST stands for Representational State Transfer
• SOAP is a protocol. SOAP was designed with a • REST is an Architectural style in which a web
specification. It includes a WSDL file which has the service can only be treated as a RESTful service if it
required information on what the web service does in follows the constraints of being
addition to the location of the web service.
1. Client Server
2. Stateless
3. Cacheable
4. Layered System
5. Uniform Interface
<?xml version="1.0"?> • REST does not need much bandwidth when requests
<SOAP-ENV:Envelope are sent to the server. REST messages mostly just
xmlns:SOAP-ENV consist of JSON messages. Below is an example of
="http://www.w3.org/2001/12/soap-envelope" a JSON message passed to a web server. You can
SOAP-ENV:encodingStyle see that the size of the message is comparatively
=" http://www.w3.org/2001/12/soap-encoding"> smaller to SOAP.
<soap:Body>
<Demo.guru99WebService {"city":"Mumbai","state":"Maharastra"}
xmlns="http://tempuri.org/">
<EmployeeID>int</EmployeeID>
</Demo.guru99WebService>
</soap:Body>
</SOAP-ENV:Envelope>
• REST permits different data format such as Plain
• SOAP can only work with XML format. As seen from
text, HTML, XML, JSON, etc. But the most
SOAP messages, all data passed is in XML format.
preferred format for transferring data is JSON.
Optimistic Locking
When we talk about locking we are often referring to optimistic locking. The optimistic locking model subscribes
to the philosophy that there is a good chance that the transaction in which changes are made to an entity will be
the only one that actually changes the entity during that interval. This translates into the decision to not acquire a
lock on the entity until the change is actually made to the database, usually at the end of the transaction.
* When the data actually does get sent to the database to get updated at flush time or at the end of the transaction,
the entity lock is acquired and a check is made on the data in the database. The flushing transaction must see
whether any other transaction has committed a change to the entity in the intervening time since this transaction
read it in and changed it. If a change occurred, it means that the flushing transaction has data that does not include
those changes and should not write its own changes to the database lest it overwrite the changes from the
intervening transaction. At this stage, it must roll back the transaction and throw a special exception called
OptimisticLockException.
Transactions & Locking
1. Change tx isolation level --to REPEATABLE_READ
OR
2 Use "select for update" Query
Both of above approach applies a write lock
Better approach --Optismistic Locking
* JPA 2 supports both optimistic locking and pessimistic locking. Locking is essential to avoid update collisions
resulting from simultaneous updates to the same data by two concurrent users. Locking in JPA) is always at the
database object level, i.e. each database object is locked separately.
* Optimistic locking is applied on transaction commit. Any database object that has to be updated or deleted is
checked. An exception is thrown if it is found out that an update is being performed on an old version of a
database object, for which another update has already been committed by another transaction.
* Optimistic locking should be the first choice for most applications, since compared to pessimistic locking it is
easier to use and more efficient.
* In the rare cases in which update collision must be revealed earlier (before transaction commit) pessimistic
locking can be used. When using pessimistic locking, database objects are locked during the transaction and lock
conflicts, if they happen, are detected earlier.
* Optismistic Locking
Add @Version annotated property in hibernate POJO.(data type Integer)
* The initial version of a new entity object (when it is stored in the database for the first time) is 1. In every
transaction in which an entity object is modified its version number is automatically increased by one.
* During commit , hibernate checks every database object that has to be updated or deleted, and compares the
version number of that object in the database to the version number of the in-memory object being updated. The
transaction fails and an OptimisticLockException is thrown if the version numbers do not match, indicating that
the object has been modified by another user (using another transaction) since it was retrieved by the current
updater.
Pessimistic Locking
The main supported pessimistic lock modes are:
PESSIMISTIC_READ - which represents a shared lock.
PESSIMISTIC_WRITE - which represents an exclusive lock.
Setting a Pessimistic Lock
An entity object can be locked explicitly by the lock method: org.hibernate.Session API
void lock(Object object,LockMode lockMode)
* Obtain the specified lock level upon the given object. This may be used to perform a version check
(LockMode.READ) or to upgrade to a pessimistic lock (LockMode.PESSIMISTIC_WRITE)
eg : sf.getCurrentSession().lock(employee, LockMode.PESSIMISTIC_WRITE);
What is REST ?
REST stands for REpresentational State Transfer.
Why the name ?
* It's the representation of the resource (eg : image/student/customer/invoice/bill....) using known data exchange
formats(text/xml/json) --which gets transferred between client & server .
* REST is web standards based architecture and uses HTTP Protocol for data communication.
* It revolves around resource where every component is a resource and a resource is accessed by a common
interface using HTTP standard methods. (ROA)
* 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
presents the resources.
* Here each resource is identified by URIs
* REST uses various representations to represent a resource like text, JSON and XML. Most popular light weight
data exchange format used in web services = JSON
HTTP Methods
Following well known 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.
How to get the JSPWriter inst : connected to clnt browser : from inside the Tag class?
+ API : inside : doTag....
getJspContext() ---> JsPContext (env. of the JSP : impl. objs avlbl to JSP , whichever has invoked this tag)
On JSPContext : to get JSPWriter
+ JspWriter getOut()
& then invoke : out.println(dyn cont.)
2. Describe the tag to W.C : so that W.C can manage the life-cycle of the tag.
Creating : TLD (Tag library descriptor : .tld : xml syntax)
copy the template : ur web-appln's : web-inf\tlds\example.tld
eg :
<tag>
<name>welcome</name> : tag suffix
<tag-class>cust_tags.MytagHandler</tag-class> : F.Q class name
<body-content>empty</body-content> : no body supported by the tag + no attrs.
</tag>
SOURCE : - Annotations are to be discarded by the compiler (i.e don't appear in .class file).
eg : @Override
CLASS --Annotations are kept in the class file by the compiler but not retained by the VM at run time. This is the
default behavior.
RUNTIME -- Annotations kept in the class file by the compiler and retained by the JVM at run time, so as to read
using reflection
eg : @Deprecated,@FunctionalInterface
@Inherited --
Indicates that an annotation type is automatically inherited.
When you apply this annotation to any other annotation i.e. @MyCustomAnnotation; and
@MyCustomAnnotation is applied of any class MySuperClass then @MyCustomAnnotation will be available to
all sub classes of MySuperClass as well.
@Documented
This annotation indicates that new annotation should be included into java documents generated by java document
generator tools.
Meaning of annotations
@Override annotation assures that the subclass or implementation class method is overriding/implementing the
parent class / interface method. If it is not so, compile time error occurs.
@SuppressWarnings annotation: is used to suppress warnings issued by the compiler.
eg : @SuppressWarnings("serial")
or
@SuppressWarnings("unchecked")
@Deprecated annoation marks that this method is deprecated so compiler prints warning. It informs user that it
may be removed in the future versions. So, it is better not to use such methods.
-----------------------------------------------------------------------------------------------------------------------------------
Custom Annotations
* Java Custom Annotation
+ Java Custom annotations or 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.
+ Points to remember for java custom annotation signature (methods in i/f)
+ Method should not have any throws clauses
+ Method should return one of the following: primitive data types, String, Class, enum or array of these data
types.
+ Method should not have any parameter.
+ We should attach @ just before interface keyword to define annotation.
+ It may assign a default value to the method.
Types of Annotation
There are three types of annotations.
+ Marker Annotation + Single-Value Annotation + Multi-Value Annotation
1) Marker Annotation
An annotation that has no method, is called marker annotation. For example:
@interface MyAnnotation{}
eg : @Override , @Deprecated are marker annotations.
2) Single-Value Annotation
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
eg :
@MyAnnotation(value=10)
The value can be anything.
3) Mulit-Value Annotation
An annotation that has more than one method, is called Multi-Value annotation.
For example:
@interface MyAnnotation{
int value1();
String value2();
String value3();
}
We can provide the default value also. For example:
@interface MyAnnotation{
int value1() default 1;
String value2() default "";
String value3() default "xyz";
}
How to apply Multi-Value Annotation
@MyAnnotation(value1=10,value2="abc",value3="xyz")
Built-in Annotations used in custom annotations in java
@Target @Retention @Inherited @Documented
Example to specify annoation for a class (i.e before a class definition)
@Target(ElementType.TYPE)
@interface MyAnnotation{
int value1();
String value2();
}
Example to specify annoation for a class, methods or fields
So basically you create objects and register them on the directory services which you can later do lookup and
execute operation on.
JNDI Overview
JNDI is an API specified in Java technology that provides naming and directory functionality to applications
written in the Java programming language. It is designed especially for the Java platform using Java's object
model. Using JNDI, applications based on Java technology can store and retrieve named Java objects of any type.
In addition, JNDI provides methods for performing standard directory operations, such as associating attributes
with objects and searching for objects using their attributes.
+ JNDI is also defined independent of any specific naming or directory service implementation. It enables
applications to access different, possibly multiple, naming and directory services using a common API. Different
naming and directory service providers can be plugged in seamlessly behind this common API. This enables Java
technology-based applications to take advantage of information in a variety of existing naming and directory
services, such as LDAP, NDS, DNS, and NIS(YP), as well as enabling the applications to coexist with legacy
software and systems.
What is Maven ?
Build automation tool for overall project management.
It helps in
1. checking a build status
2. generating reports (basically javadocs)
3. setting up the automated build process and monitors the same.
Why Maven ?
It helps in source code compilation, distribution(JAR/WAR--web app archive), documentation, collaboration with
different teams .
Maven tries to describe
1. How a software is built.
2. The dependencies, plug-ins & profiles that the project is associated in a standalone or a distributed
environment.
Ant disadvantages
1. While using ant , project structure had to be defined in build.xml. Maven has a convention to place source code,
compiled code etc. So no need to provide information about the project structure in pom.xml file.
2. Maven is declarative, everything you define in the pom.xml file.
No such support in ant.
3. There is no life cycle in Ant, where as life cycle exists in Maven.
Maven advantages
4. Managing dependencies
5. Uses Convention over configuration - configuration is very minimal , in pom.xml
6. Multiple/Repeated builds can be achieved.
7. Plugin management.
8. Testing - ability to run JUnit and other integration test suites.