You are on page 1of 6

8:07

Creational - 1) prototype - when creating an object is time consuming and costly


affair and we have similar object with us then we go for prototype pattern.(copying
the existing similar object and modify it)

2) Builder - It builds a complex object using simple objects and using a step by
step approach . end result would be a complex object but in order to create that
complex object using simple objects .
Recall stringBuilder class - mutable class
eg 1)
StringBuilder sb = new StringBuilder();
sb.append("hello");
sop(sb); // hello

sb.append("welcome"); // hello welcome

eg 2) where string builder is used in java :-


int num1=10; int num2=20;
sop("Tow numbers are "+num1+"\t"+num2);
Internal Working -
behind this statment stringBuilder is used
what compiler does - Behind the scene , compiler used string builder and it creates
complex object by using simple objects by appending
StringBuidler sb = new StringBuilder()// empty object is created
sb.append("Two numbers are");
sb.append(num1);
sb.append(num2);

StringBuilder is given to sop(sb.tostring());

eg. 3) cake and BuilderPatternExample


inside cake class we have some members and inside that we have static nested class
and has same members and inside that we have some methods . It has one special
method method which is build has return type cake and inside this it returns new
cake(this) and private constructor of outside class will be called from here.
second class - just using builderPattern we have created cake object using simple
methods and final at last using build method invokation we have complex object.

how do you create mutable class?

class MyNum
{
int k;
MyNum add(int k)
{
this.k=k;
return this; // mutable class - returning same object for modification
return new MyNum(k) // immutable class - new object is created
everytime
}
}

8:45 - After init_method info

Redirect Forward - what if one web component [servlet or jsp] is not sufficient ?
partially processing of request
This can be achieved by redirect or forward

Real life scenario - scenario 1) Buy a particular thing - one shopkeeper redirects
to another shopkeeper to get object or thing - we know shopkeeper holding object
second scenario - shopkeeper will not have that thing but will manage and bring
that - we will dont know exactly who is serving you.

a) redirect -
client request goes to redirecting serv that servlet recommends client to go for
another servlet and that serves it
b) forward -
client request goes to forwarding serv that servlet forwards that same request to
forwarded serv which processes the request

Create new project - create servlet - open RedirectedServ and


RedirectingServ(inside sir's folder) create two respective servlet but first is
Redirecting serv and then RedirectedServ both with doget() method

which servlet should be run first - redirecting servlet - inside output in web
browser we have RedirectedServ in address bar and its content
what is the Sequence of this application?
-> a) We Requested RedirectingServ
b) RedirectingServ recommended us to go to another RedirectedServ(shopkeeper )
c) based on this recommendation , we issued a fresh request to RedirectedServ,
d) RedirectedServ gave us response.

What we did?
-> we requested RedirectingServ and we got the response from RedirectedServ.

compare above two questions - b) and c) in first question are hidden behind
response.sendRedirect("RedirectedServ");

API - Redirect - HttpServletResponse and it has sendRequest("another servlet


name");

open redirect flow - ppt - redirect can go beyond container to another resource eg.
(www.google.com)
client knows clearly who responded his request

Forward - ForwardingServ and ForwardedServ (inside sir's folder) first


ForwardingServ servlet and then ForwardedServ servlet - run Forwarding
on output browser - our address bar we have ForwardingServ and we are under
impression that we are served by it but check the content of output

Forwarding API - RequestDispatcher is an interface


getRequestDispatcher() is inside HttpServletRequest
RequestDispatcher rd=request.getRequestDispatcher("another servlet name");

and inside RequestDispatcher implementation we have forward(request,response)

RequestDispatcher is used for both below scenario


scenario - 1) forwarding and forwarded - servlet should be forwarded - rd.forward()
2) include the response of ForwardedServ and then gave us output - servlet
should be included - rd.include()

Note- After forward we will not write any code because it will be forwarded and
forward will be used mostly in conditional situations(conditional statments )
forward flow - forward cannot go outside container to any other resources - It is
faster. it uses same request does not create another response.
but for outside project? - we have way to do it -

create two project inside eclipse - first project name 'one' inside that
ForwardingServ1 -
ServletContext context1=context.getContext("/myapp1"); // for this create new
project with the same name
RequestDispatcher rd=context1.getRequestDispatcher("/FirstServ"); // create servlet
with same name as this

run the ForwardingServ1 inside one project - while running server - configured both
servlets and then run it

in order to forward from one context to anonther context - we need additional


attribute to be written <Context CrossContext="true"> inside tomcat context.html
inside tomcat folder then again delete tomcat server from eclipse and add new
updated tomcat server (with additional libraries in both context if errors) and
then run again.

output - in Address bar - http://localhost:8080/One/ForwardingServ1---- we have one


firstServ from that we have forwarded to FirstServ of myapp1
Inside the forwarded servlet of myapp1 - output in webbrowser

Difference between two programs:-


1)within the same project -
RequestDispatcher rd=request.getRequestDispatcher("ForwardedServ");
rd.forward(request,response);

and

2)across the project


ServletContext context=getServletContext();
ServletContext context1=context.getContext("/myapp1");
RequestDispatcher rd=context1.getRequestDispatcher("/FirstServ");

rd.forward(request,response);

what we have done - crossContent=true inside tomcat folder , coding difference


ServletContext context1 = context.getContext("/myapp1"); -- get me the reference
of project ("mysapp1");
RequestDisparcher rd = context1.getRequestDispatcher("/myapp1"); -- from that
reference call requestDispatcher / is compulsory when getRequestdispatcher of
context
rd.forward(request,response); // helps

include response - second scenario - i can paritally process the request but i know
partial response of other servlet so i will include
everything regarding logic is decided in main servlet - developer of first servlet
.

create a dynamic web project - create two IncluderServ and IncludedServ and then
run IncluderServ
inluderserv - code only using RequestDispatcher will not clear what to do include
or forward
using RequestDispatcher include method - includes the response of other servlet
inside current servlet - response in the sense object
difference imp - forward() - execution completes for first sevlet
include() - execution remains intact and doesn't get terminated and all the
statamenst after that will be printed.

making Http_stateful - Http is a stateless protocol - doesn't keep track of


information.
when client requests a web resource(jsp/servlet) and client requests again - for
container client will be different altogether.
in practical scenario -

real life example -


two servlets

client billserv

shopserv

Scenario - why http needs to be stateful?


client in case of shopserv will select products from list and place add to cart
and client is suppose to visit billserv
when client use one servlet and finish its work and container forgots client and
for another servlet will take client as new client.This is not feasible in most
cases.
container should remember the client. what we need - http has be stateful.

There are four ways to make http stateful -


1) hidden Fields -
2) custom cookies - Cookie is a class in java
3) HttpSession - It is an API
4) URlRewriting

1)) Hidden Fields - first way of making http stateful


create new dynamic project - copy paste log file from making http stateful inside
web folder of eclipse and create two servlets of hidden serv1 and hidden serv2
discussion -

log.html H1 hidden servlet 1


if want then pass to H2
Hidden
name : AB str1-ABC ----a1 = ABC

age: 39 str2-39 -----a2 = 39

submit done

when will click on submit - control goes to hiddenServ1 dopost and collected in
str1 and str2. We have Hidden component inside Html tag form action and inside that
we have specified hidden type input tag and create form with two hidden componenets
containing value and when click on done control goes to hiddenServlet 2 and print
these values.
form values are passed to servlet 1 and after that it is send to servlet 2
hidden fields - drawbacks - a) They can be seen with "view source" b) you have to
generate html dynamically inside the servlet

Note - how to change version of project then properties - facets

2) custom cookies -
create new project - and add CustomCookieServ servlet and paste from sir's file
discussion - file cookie concept
Cookie is a class Http package, cookies are used to store info , they can store
only textual information and cannot store java objects, cookies can be rejected by
client browser. cookies are always added inside response and retrieved from
request.

request.getcookies - returns null control goes to else we are creating object of


cookie class cookie(name,value)
Cookie c = new Cookie('ab','5');
response.addCookie(c);

Bydefault cookie life until browser is open


c.setMaxAge(120); // this will still hold cookies after browser closed values will
be stored
getcookies() return always array of cookies even if it is single cookie

cookies drawback - cookies can be rejected by browser , cannot store java objects,
seen by users

customcookie - flow

3) HttpSession - about HttpSession file in sir's file - HttpSession interface is


used to create a session in java

HttpSession session = request.getSession(); //

or

HttpSession session = request.getSession(true );


above statment will create a sessin if not exists or retrieve existing session - if
session present - it will return otherwise create one

how to add values in session - session.setAttribute(string,object)


how to retrieve valus from session session.getAttribute(string)

HttpSession session = request.getSession(false) // this statement will give present


session only otherwise null

SessionServlet1 and SessionServlet2 open these

SessionServ1 - Session will be created first and attribute will be set as key and
value so in another servlet we are able to retrieve session values
session life is limited to browser and session is for whole project

Internal working :-
SessionServ1
HttpSession session = request.getSession(); // or get Session(true);
session.setAttribute("book","Value");

sessionServ2
HttpSession sessioon =request.getSession(false);
pw.println(session.getAttribute("book"));

client -> shopServ // getSession() or getSession(true)


-> Billserv // getSession(false)

about http session again :-


HttpSession session = request.getSession(); // or get Session(true);
session.setAttribute("book","Value");
how internally it works :-
container will
a) create session object - serve side
b) store attribute/s
c) generate unique session id
d) create cookie -container will do all this
e) store session id inside cookie
f) add cookie inside response

cookies are internally used behind session

what happens when session is retrieved ?


HttpSession sessioon =request.getSession(false);
conatiner will
a) retrieve cookie from request
b) retrieve session id from cookie
c) try to match session id with the session object avaliable on server.
if it matches return session object , else return null

http session should work irrespective of cookie is accepted or rejected

therefore 4) URLRewriting - session id with url inside cookie

open folder URLRewriting - create a new project and create first servlet

encode() - it allows you to use html rewriting technique it is present in response

You might also like