Archive

Archive for August, 2011

Leadership

August 22, 2011 Leave a comment

Put courage first
Be mentally tough
Decline yourself
Value your character
Project confidence

It is not work that kills men, it is worry. Work is healthy; you can hardly put more on a man than he can bear. But worry is rust upon the blade. It is not movement that destroys the machinery, but friction. ~ Henry Ward Beecher

Categories: J2EE

Design Pattern

August 21, 2011 Leave a comment

Adapter Pattern:-

Converts the interface of the class to another one that client expects.

eg: Converting a Turkey into a Duck.

we wrap Turkey into a TurkeyAdapter and send the adapter to the client.

Client has a Target Interface,

Adapter implements Target Interface and has a Adaptee.

Two types of adapter:-

1. object adapter

2. class adapter

1. Object Adapter:- is what we read so far.

2. Class Adapter:- Require multiple inheritance by sub-classing both target and adaptee.

Difference between Object and Class Adapter:-

Object Adapter, based on composition, can adapt the adaptee or any of its sub class.

Class Adapter, can override behavior

Real world adapter example:-

Adapting an Enumeration to an Iterator.

Bridge Pattern

Use Bridge Pattern to vary not only your implementations, but your abstractions.

example:- Universal remote and controller and various TV implementation.

Both TV remote and TV implementation.

Decorator Pattern
Inheritance: behavior is set statically at compile time.
All sub class inherit the same behavior.
Composition: dynamically composing objects, we can add functionality in the new code, rather than altering existing code.

Design Principal: Classes should be open for extension but closed for modification.

Definition: Decorator pattern attaches additional responsibility to an object dynamically. It provides a flexible alternative to sub classing for extending the functionality.

Component is the base class, eg Beverage
Concrete component & Decorator, both extends Component, eg. Expresso & CondimentDecorator (for type matching, not for inheriting behavior.
We acquire behavior by composing objects together.
With composition, we can mix and match behavior as we want.)
Decorator also has a Component eg. Condiment also has a Beverage.
Concerete Decorators extend Decorator, eg. Milk & Soya extend Condiment.

Similar objects doing similar operations, abstract class Beverage, abstract method cost(), requirement is to call cost method on some object in hierarchy dynamically is a candidate for such pattern

Requirement:
Write code as per abstract component, writing to concrete will brake decorator.

Cost in implementing decorator:
Many small classes
Following type is necessary
Increase code complexity that factory pattern can help to reduce.

Adapter is used to match with the client requirement for an adaptee, while facade is used to simplify the interface

The facade pattern provide a unified interface to a set of interfaces. It defines a higher level of interface that make the subsystem easy to use.

Design principle : principle of least knowledge, talk only to your immediate friends.

Flyweight: one single instance of a class can be used to provide many virtual instances, in this way you are able to flw away the memory weight of creation of multiple instance

Its Approach is to collect the state of many object and rather centralize the state at one location and form virtual objects out of one object.

It is used when class has many state and can be controlled identically.
Single logical instance of a class can not behave independently from other

Example : large tree plantation project

Proxy pattern provides a surrogate or placeholder for another object to control access to.

Another object, which may be remote, expensive to create or in the need of securing.

Both RealSubject and the Proxy implement Subject interface.
This allows any client to treat the proxy just like the real subject.

Proxy keep the reference to the real object, so it can forward the requests to the subject when necessary. it also often instantiate or handles the creation of the realsubject
Realsubject is usually the object the does most of the work.

Composite pattern: allows to compose objects into tree structure to represent part-whole hierarchies.
It let client treat individual & composition of objects uniformly.
We can apply same operations over both composite & individual object.

Eg: menu & sub menu

Client has a component, which is extended by leaf & composite. Composite contains component ( recursive )

Categories: J2EE

Servlets – Question Answer way!

August 6, 2011 Leave a comment

Q. What is Container ?

A. Servlets dint have a main() method. They are under control of another Java application called a “Container”.

Example of a Container is Tomcat.

Example of a web server is Apache.

Container provides:-

1. Communication Support: provide easy way for servlet to talk to your web server.

2. Lifecycle Management: of servlet

3. Multithreading support: a new java thread is create to handle each servlet request.

4. Declarative security: via xml configuration.

5. JSP Support: converting JSP to real java code.

Q. Explain Life-cycle of a servlet

A.1 Container Load class

2. Instantiate Servlet (Invoke its default constructor)

2.A Load ServletConfig

2.B Load ServletContext

3. Call init() -> which may contain, getting a DB Connection.

4. service(), which eventually generate a thread to process each request and subsequently call doGet() & doPost()

5. destroy()

!Note

When you have multiple parameter values for a single parameter, you need getPatameterValues() that returns an array instead of getParameter()

Q. Beside parameter, what can I get from request object?

A. request.getHeader(“User-Agent”); -> Get request header

request.getCookies();

request.getSession();

request.getMethod();

request.getInputStream(); -> get all raw request information.

Q. Important method to call on response

A. setContentType()

getWriter()

getOutputStream()

Q. Difference between forward and sendRedirect

A.1 forward (page 89)

  • Control can be forward to resources available within the server from where the call is made. This transfer of control is done by the container internally and browser / client is not involved.
  • The original request and response objects are transfered along with additional parameters if needed.

RequestDispatcher view = request.getRequestDispatcher(“result.jsp”);

view.forward(request, response);

A.2 sendRedirect (page 136)

if (workforme)

{

//hadel request

}else {

response.sendRedirect(“http://www.oreilly.com”);

}

Control can be redirect to resources to different servers or domains. This transfer of control task is delegated to the browser by the container. That is, the redirect sends a header back to the browser / client. This header contains the resource url to be redirected by the browser. Then the browser initiates a new request to the given url. Since it is a new request, the old request and response object is lost.

For example, sendRedirect can transfer control from http://javapapers.com to http://anydomain.com but forward cannot do this.

‘session’ is not lost in both forward and redirect.

To feel the difference between forward and sendRedirect visually see the address bar of your browser,
in forward, you will not see the forwarded address (since the browser is not involved)
in redirect, you can see the redirected address.

You can call sendRedirect() after response is already written. ->IlligalStateException.

Attributes are not parameters!
3 Attribute types:-
1. Application/context
2. Request
3. Session

1. Application/context
getServletContext().set/getAttribute(“”,”");
They are not thread safe. to make it thread safe, we need to lock servletContext as below:-
Synchronized (getServletContext()) {}

2. Session
requirest.getSession().get/setAttribute(“”,”");
Multiple request from same session, say multiple browser window
Lock on session
Synchronized (session){}

Implementing SingleThreadModel interface is also not a solution , it is as good as synchronizing service method.
Also result in poor performance.

3. Request
Only request attribute and local variable are thread safe
Use when some other component of the app take over all or part of the request via
RequestDispatcher.
By two of its method forward() & include() ()
Get RD from request or servletContext(/ is must, root of application, not relative to current request)

Session
If http uses state less connection so how container keep track of the user session ?
On first request , container generate a unique session Id to send with the response & client keep sending it for each subsequent request.
This happen via cookie maintained by the container.
What if client has cookies disabled on his browser ?
URL re-writing happen automatically if cookies not supported, we only need to call response.encodeUrl()
Invalidate the session if not active

Now! JSP

Page directives:-
@
scriptlet
%%
expression
=
s and e land up in service method

Declaration
!
Added to class outside of the service method, it can be variable declaration or method.

Implicit objects :-
out JspWriter
session HttpSession
request HttpServletRequest
response HttpServletResponse
config ServletConfig
application ServletContext
exception JspException
pageContext PageContext
page Object

Comments
HTML !
Jsp %%

Categories: J2EE
Follow

Get every new post delivered to your Inbox.