Você está na página 1de 35

Class

{
1. Data

// variables/fields/properties

2. Methods which act on that data// functions/operations


}

Variable

field declared to be of a primitive data type

int x
dou

Object

field declared to be of a class type

Strin

Instance

'only' when you use 'new' operator to call the constructor to


create a new instance of that class.

g=

Declaration

defining a variable to be of a specific datatype/class type

int x

Initialization

assigning a value to the variable/field/property

x=
g=
g=
in h

Instantiation

calling new operator to create a new instance of that class

g=

Method signature :
1. method name
2. method params (no.of.params, and datatypes)
3. access modifier/specifiers
4. return type
5. exceptions it throws
parameter - variables that receive values. Public void foo(int x, float y)
argument - values that are passed (pass by value not by reference) to a
method. foo(6, 4.4)
Access Specifiers :

Public : all and any classes


Default : all classes of same package
Private : only to that class
Protected : all classes of same package + sub classes of other packages
Access Modifiers:
Static
:
access without instantiating the class, only static methods
can access static fields, static methods can call only other static methods.
Final :
can be applied to - field [ once assigned a value, cannot
reassign ], -method [ cannot be overridden ], -class [ cannot be extended ]
Volatile :
not cached, always read from main memory
Transient : not persisted, not serialized
Abstract : not clear, vague, incomplete, to be implemented
Serialization :
process of writing an object to a network as a byte stream
(bunch of bytes)
final
finally is a block in exception handling,
finalize() method that is called just before garbage collection

Volatile

Tran

used as an indicator to Java compiler and Thread to not


cache value of this variable and always read it from main
memory, used in Concurrent programming in Java

used along with instance var


serialization process, its valu

cannot be used with method or class and it can only be


used with variable

Along with static variables, tr


serialized during Serialization

An object has three characteristics:


-----------------------------------------------state: represents data (value) of an object.
behavior: represents the behavior (functionality) of an object such as
deposit, withdraw etc.
identity: Object identity is typically implemented via a unique ID. The value
of the ID is not visible to the external user.

Object class methods


hashcode, tostring

clone, finalize, wait, notify, notifyAll, equals,

equals() and hashcode() methods


---------------------------------------------

JVM assigns unique hashcode value to each object when they are
created in memory
It is not necessary that two different object must have different
hashcode values. it might be possible that they share common hash
bucket.
If two objects are same then they must return same value in
hashcode() and equals() method whenever invoked.

OOPS Object Oriented Programming


-

Data Abstraction
Encapsulation
Inheritance
Polymorphism

Overloading

Overridin

Same method name, different method


signature

Same method name, same method


body/impl will vary

Within the same class

Between class and its sub class

Return types may vary

Return types are same

Declared exceptions may vary

Declared exceptions will also be sam

Class

Abstract class

Implements(provide method body) all of


methods

Implements some, none or all of


its methods

Can have instances

Cannot have instances

Can have sub classes (extends)

Must have sub class

Public static void main(String args[]) : to be globally accessible and for


JVM to be able to call it, be able to call without instantiating class, no return
type as JVM cannot do anything receiving the return, reserved word, to
collect command line arguments.
c:/>javac Test.java
java Test <1> <11> <222>
Possible :
-----------------------class extends class
class implements interface
interface extends interface
class implements interface,interface,interface.....
Not Possible :
----------------------class implements class
interface implements interface
interface extends class
Singleton Class :
-

Should have a private constructor and at least one constructor


Should have a private static object of the class
Should have public static method to return that private static instance

Cloning, Deep and Shallow


------------------------------------------

Shallow copies duplicate as little as possible, is a copy of the collection


structure, not the elements, two collections now share the individual
elements.
Deep copies duplicate everything. A deep copy of a collection is two
collections with all of the elements in the original collection duplicated.

Multithreading in java is a process of executing multiple threads


simultaneously. But we use multithreading than multiprocessing because
threads share a common memory area. They don't allocate separate
memory area so saves memory, and context-switching between the
threads takes less time than process.

The life cycle of the thread in java is controlled by JVM. The java thread
states are as follows:
New
Runnable
Running
Non-Runnable (Blocked)
Terminated

Thread scheduler in java is the part of the JVM that decides which thread
should run.
Under preemptive scheduling, the highest priority task executes until it
enters the waiting or dead states or a higher priority task comes into
existence.
Under time slicing, a task executes for a predefined slice of time and then
reenters the pool of ready tasks.

Each thread have a priority. Priorities are represented by a number between


1 and 10.

3 constants defiend in Thread class:


public static int MIN_PRIORITY
public static int NORM_PRIORITY
public static int MAX_PRIORITY
Default priority of a thread is 5 (NORM_PRIORITY). The value of
MIN_PRIORITY is 1 and the value of MAX_PRIORITY is 10.

Daemon thread in java is a service provider thread that provides


services to the user thread. Its life depend on the mercy of user threads i.e.
when all the user threads dies, JVM terminates this thread automatically.
There are many java daemon threads running automatically e.g. gc, finalizer
etc.

No. After starting a thread, it can never be started again. If you does so, an
IllegalThreadStateException is thrown.

Each thread starts in a separate call stack. Invoking the run() method from
main thread, the run() method goes onto the current call stack rather than at
the beginning of a new call stack.

The join() method waits for a thread to die. In other words, it causes the
currently running threads to stop executing until the thread it joins
with completes its task.
t1.join();
t2.start();
t3.start();
As you can see in the above example,when t1 completes its task then t2
and t3 starts executing.
t1.join(1500);

In the above example,when t1 is completes its task for 1500 miliseconds(3


times) then t2 and t3 starts executing.

getName(), setName(String) and getId() method:


t1.setName("Sonoo Jaiswal");
t1.getName()
t1.getId()

The currentThread() method returns a reference to the currently executing


thread object.
System.out.println(Thread.currentThread().getName());

Java Thread pool represents a group of worker threads that are waiting
for the job and reuse many times.

In case of thread pool, a group of fixed size threads are created. A thread
from the thread pool is pulled out and assigned a job by the service provider.
After completion of the job, thread is contained in the thread pool again.
Advantage of Java Thread Pool is,
Better performance It saves time because there is no need to create new
thread. Real time usage is,
It is used in Servlet and JSP where container creates a thread pool to process
the request.

Synchronization in java is the capability to control the access of multiple


threads to any shared resource.
The synchronization is mainly used to :

To prevent thread interference.


To prevent consistency problem.

There are two types of thread synchronization mutual exclusive and interthread communication.

Mutual Exclusive - helps keep threads from interfering with one another while
sharing data. This can be done by three ways in java:

-Synchronized method.
If you declare any method as synchronized, it is known as synchronized
method.
-Synchronized block.
Suppose you have 50 lines of code in your method, but you want to
synchronize only 5 lines, you can use synchronized block.
-static synchronization.
If you make any static method as synchronized, the lock will be on the class
not on object.

Cooperation (Inter-thread communication in java)


Is a mechanism in which a thread is paused running in its critical section and
another thread is allowed to enter (or lock) in the same critical section to be
executed.
It is implemented by following methods of Object class:

wait()

Causes current thread to release the lock and wait until either another
thread invokes the notify() method or the notifyAll() method for this object,
or a specified amount of time has elapsed.
The current thread must own this object's monitor, so it must be called from
the synchronized method only otherwise it will throw exception.
notify()
Wakes up a single thread that is waiting on this object's monitor. If any
threads are waiting on this object, one of them is chosen to be awakened.
The choice is arbitrary and occurs at the discretion of the implementation.
notifyAll()
Wakes up all threads that are waiting on this object's monitor.

Synchronization is built around an internal entity known as the lock or


monitor. Every object has an lock associated with it.
By convention, a thread that needs consistent access to an object's fields has
to acquire the object's lock before accessing them, and then release the lock
when it's done with them.

t1 -> Obj1 <- t2

t3 -> Obj2 <- t4

Suppose there are two objects of a shared class(e.g. Table) named object1
and object2.
In case of synchronized method and synchronized block there cannot be
interference between t1 and t2 or t3 and t4 because t1 and t2 both refers to
a common object that have a single lock.
But there can be interference between t1 and t3 or t2 and t4 because t1
acquires another lock and t3 acquires another lock.I want no interference
between t1 and t3 or t2 and t4.
Static synchronization solves this problem.

Deadlock in java is a part of multithreading. Deadlock can occur in a


situation when a thread is waiting for an object lock,
that is acquired by another thread and second thread is waiting for an object
lock that is acquired by first thread.
Since, both threads are waiting for each other to release the lock, the
condition is called deadlock.

t1 -> obj1 t2 -> obj2

t1 waiting on t2, t2 waiting on t1

Wait()

Slee

wait() method releases the lock.

sleep() method doesn't releas

is the method of Object class

is the method of Thread class

is the non-static method

is the static method

should be notified by notify() or notifyAll() methods

after the specified amount of

wait(), notify() and notifyAll() are methods of 'Object'.


isInterrupted(), interrupt() are methods of Thread.
sleep() and yield() are static methods of Thread class.

start() method registers thread into the Thread Scheduler.

wait(), sleep() and join() will make thread leave Running state.

String

StringBuffer

Storage Area

Stack

Heap

Mutation

Immutable

Mutable

Thread Safe ?

Yes

Yes

Performance

Fast

Slow

Comparable

Comparator

1) Comparable provides single sorting sequence.

Comparator provides multiple elem

2) Comparable affects the original class

Comparator doesn't affect the or

i.e. actual class is modified.

3) Comparable provides compareTo() method to sort

i.e. actual class is not modified.

Comparator provides compare() m

elements.

4) Comparable is found in java.lang package.

Comparator is found in java.util pa

5) Collections.sort(List) method.

Collections.sort(List,Comparato

Variables can store only one value. int x = 10;

Arrays store multiple values but have specific size restriction.

Collections mutable

Collection (I)
List (I) : first in first out, maintain the order of values, allows duplicates
Vector(C)
ArrayList (C)
LinkedList (C)

Set (I) : not ordered collection , unique collection of values,


HashSet (unsorted)
TreeSet (sorted)

Map (I) : Key-Value pairs ('a',100), ordered


HashMap
TreeMap
Hashtable

Vector

Array list

Synchronized

Unsynchronized

Allows duplicates

Allows null

Hashtable

Hashmap

Synchronized

Unsynchronized

No duplicates

Allows null

Array list

Linked list

Slow access

Fast access

Random access

No random access

Ordered

Duplicates

LIST

Yes

Yes

SET

No

No

LIST ordered
LINKED faster access, and ordered access
SET and MAP unique values, no duplicates
MAP key-value pairs, and no duplicates
HASH not sorted
TREE sorted

Checked exceptions are checked and warned by JVM at compile time.


Unchecked exceptions are not checked and warned by JVM at compile
time.
Exception handling is process of managing the runtime exceptions.
try the block where you expect code to go wrong and throw an
exception.
catch the block(s) which has code to react to a caught exception. Every
try should have atleast one catch or finally. Can have many catch
blocks.
finally optional block, this code gets fired irrespective of whether an
exception occurs or not.
Static text non intuitive
Hyper text intuitive/interactive
Protocol - set of rules. HTTP, FTP, SMTP
HTTP - static content + hyper text
Web - HTTP + Servlets, JSPs
Application - Web + EJB also
Servlet extends GenericServlet
-

init()
service()
destroy()

Servlet extends HttpServlet


-

init()
service()
destroy()
doGet()
doPost()

Servlet Life Cycle


If an instance of the servlet does not exist, the web container
a. Loads the servlet class (.class).
b. Creates an instance of the servlet class.

c. Initializes the servlet instance by calling the init method.


d. Invokes the service method, passing request and response objects.

ServletConfig

ServletContext

Specific to one servlet

Applies to all servlets

Used to pass initialization parameters to the


servlet

Used to define context parameters c


servlets

<init-param> tags are used

<context-param> tags are used

To make servlets to thread safe :


-------------------------------------------

By implementing SingleThreadModel.
Synchornize the part of sensitive code.
Your servlet service() method should not access any member variables,
unless these member variables are thread safe themselves.

JSP Life Cycle


When a request is comes to a JSP page, the web container first checks
whether the JSP pages servlet is older than the JSP page. If the servlet is
older, the web container translates the JSP page into a servlet class and
compiles the class.
After the page has been translated and compiled, the JSP pages servlet (for
the most part) follows the servlet life cycle

Directives

<%@
%>

Declarations

<%!
%>

Expressions

<%=
%>

Scriptlets

<%
%>

Directives :
<%@ page import = %>
<%@ include file = %>
<%@ taglib uri = %>
<%@ page errorPage = %>
Servlet RequestDispatcher (I) :
forward() same request is passed to other jsp and control does not go to
UI
Include()
response.sendRedirect(other.jsp) control goes to UI and then gets rerouted to other jsp with new request

forward() method

sendRedirect() method

The forward() method works at server side.

The sendRedirect() metho


side.

It sends the same request and response objects to


another servlet.

It always sends a new req

There are four techniques used in Session tracking:


1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession
Cookie ck=new Cookie("user","sonoo jaiswal");//creating cookie object
response.addCookie(ck);//adding cookie in the response
Cookie ck[]=request.getCookies();

<input type="hidden" name="uname" value="Vimal Jaiswal">

url?name1=value1&name2=value2&??

String n=request.getParameter("userName");
HttpSession session=request.getSession();
session.setAttribute("uname",n);
String n=(String)session.getAttribute("uname");

JSP action tags :


<jsp:include page = />

response of the second jsp is included in the res


first jsp

<jsp:forward page = />

request is routed to several other jsps before res


sent back

<jsp:param name = value =


/>

Parameters you pass along, while forwarding

ACID :
Transactio
n

Set of statements executed on a database or file


system

Atomicity

Set of statements executed as a single unit of work

Consisten
cy

Txn exists in a consistent state before and after the


execution

Isolation

One txn executes independent of the other txn

Durability

Once COMMIT is fired txn survives even network


failures

Dirty Read

Reading uncommitted data. First txn could roll back before com
second txn

Non-Repeatable
Read

In a same transaction same query yields different results. This


another transaction updates the data returned by other tra

Phantom Read

First txn still not done adding data, and may add more data af
a read

Normalization - It is the process of organizing data in order to achieve 2


things :
1. Eliminate redundant data
2. Ensure data dependency makes sense by store related data in the
same table

Data Definition Language (DDL)

create, alter, rename, drop, truncate

Data Manipulation Language (DML)

select, insert, update, delete (CRUD)

Data Control Language (DCL)

grant, revoke

Transaction Control Language (TCL)

commit, rollback, savepoint

Delete

Truncate

Delete some or all


records

Delete all records

WHERE clause can be


used

WHERE clause cannot be


used

Need explicit COMMIT

Auto COMMIT

Drop
Remove table

Can be rolled back

Cannot be rolled back

Does not trim the table

Trims the table

Stored Procedure

Function

May or may not return a value

Must return a value

Called by EXEC command

Called from SQL statements

Can call function

Cannot call procedure

Code fragment
a row or tab

Join

Returns rows when there is atleast one match in both tables

Left

All rows of left table with or without matching rows in the right table

Left Outer

Rows of left without matching rows in right table

Right

All rows of right table with or without matching rows in the left table

Right
Outer

Rows of right without matching rows in left table

Inner

All rows common between left and right tables

Outer

All rows from both left and right tables except the common/matching
ones

Clustered Index

Non-clustered Inde

Order of the indexes matches order of data


storage

Order of the indexes does not mat


data storage

Telephone directory

Index at the back of the book

Sorting of the indexes sorts the data

Sorting of the indexes does not so

Optimistic locking
Assuming data duplication will never occur, bother
about locks and eliminate duplicates as they
occur

Pessimistic loc

Assuming data duplication alw


address duplication before

Performance tuning can be done in the following ways :


-

Too much normalization is bad, denormalize where required


Too much of indexing is bad, optimize index usage
Reduce no.of.cols that make up the composite key
Proper partitioning of table spaces, have separate space for BLOBs and
CLOBs
Use stored procedures

View

Materialized V

Runs the query each time it is accessed

Runs the query only once an


periodically

Gets latest data but performance depends on wellformed query

Fast but may not refresh on


latest data

Only when there is a IS-A relation, use Inheritance. If you want just code
reuse, use Composition.
Use Interfaces if you want polymorphism.

Aggregation

Contained object is not dependent on container object, when conta


destroyed contained remains undestroyed. E.g. School-student

Composition

Contained object is dependent on container object, when containe


contained is also destroyed. E.g. House-rooms

Data Modeling :
-

Identify entities
Identify entity attributes
Apply naming conventions as per logical model standards
Identify relationships cardinality
Apply design patterns
Assign keys
Normalize : eliminate data redundancy
Denormalize : improve performance

CREATIONAL Design Patterns :


Factory

Abstraction or interface, to let sub class or the implementing class, t


is to be instantiated, or which method is to be called

Prototype

Cloning of an object to reduce the cost of creation. E.g. method over

Singleton

Only one instance of the object exists at anytime

STRUCTURAL Design Patterns :


Adapter

Convert existing interface to new interface in order to achieve reus


classes. E.g. wrapper classes

Composite

Build complex objects out of elemental objects. E.g. file directory st

Decorator

Add additional functions to existing interface dynamically. E.g. JScro

Faade

Make complex system look simple by providing a generic interface

Proxy

Simple object to represent complex object, providing a placeholder


to access it. E.g. stub-skeleton

BEHAVIORAL Design Patterns :

Chain of
Responsibility

more than one object participate in handling the request wit


each other. E.g. servlet chaining

Observer

One object changes state and all dependent objects are upd
wait-notify

J2EE Design Patterns :


Front Controller

Single component to receive all input requests

Service Locator

Centralizing the distributed object lookup

Business
Delegate

Decoupling the presentation and service tiers

DAO

Uniform interface to access multiple databases

TO

Serialized object to act as data carrier for related attributes

STRUTS :Open source framework built on MVC architecture for


developing web applications using Java EE.
Model

Java beans, EJB

View

HTML, JSP

Controller

ActionServlet

ActionForm

Java beans representing form inputs containing request param


referencing the action bean.
validate() used to validate the input parameters, called befo
handed over to the Action class, it returns ActionErrors obje
ActionErrors validate(ActionMapping, HttpServletRequest)

ActionMapping

Contains all maps between, views to other views, and views to

Deployment
descriptor

Struts-config.xml , contains :
- form beans

Action class

action classes
action mappings
global forwards
controller configuration(action servlet)

Adapter between request contents and logic that need to be e


execute()- business logic resides here
execute(ActionMapping, ActionForm, Request, Response)

Struts Life Cyle : when a req comes from a jsp or html,


-

Retrieve or create form bean


Store form bean in appropriate scope
Reset properties/attributes
Populate properties
Validate properties
Pass form bean to action class

SPRING:
Core

BeanFactory, IOC engine

Context

Config file to define enterprise services


(beans.xml)

AOP
DAO (JDBC)
ORM (Hibernate, JDO, IBatis)
Web(MVC: Struts,JSF, Servlets, JSP)
Web MVC

BeanFactory

Collection of beans, holds bean definitions, auto-instanti

ApplicationContext

BeanFactory + resolves text messages, internationalizat


event listeners
ClassPathXmlApplicationContext : It Loads contex
file located in the classpath, treating context definitio
The application context is loaded from the application
code .
ApplicationContext context = new ClassPathXmlAppli
FileSystemXmlApplicationContext : It loads conte
file in the filesystem. The application context is loade
using the code .
ApplicationContext context = new
FileSystemXmlApplicationContext("bean.xml");
XmlWebApplicationContext : It loads context defin
contained within a web application.

Bean Scopes :
Singleton(d
)

Single definition maps to single object instance

Prototype

Single definition maps to multiple object instances

Request

Single definition maps to life cycle of a HttpRequest

Session

Single definition maps to life cycle of a HttpSession

IOC

You do not create an object but define how it is to be created, so


instantiated at runtime

Dependency
Injection

Do not connect services and components but define the depend


services, so that those services are wired-in at runtime
-

Constructor
Setter
Interface

Spring Life Cycle :


-

Container finds bean definition from config file and instantiate the bean
Using IOC dependency injection , populates all properties as specified
in config file
Call init()
Call service methods

Advantages of Spring :
-

POJO programming
Layered architecture
Open source (free)
IOC, DI and AOP

JDBC (DB table)


Template
DAOSupport
Hibernate (ORM-objs)
Template
DAOSupport
Spring-Hibernate Integration :

2 ways to connect Spring and Hibernate :


-

IOC with Hibernate template (there is a Spring JDBC template also, for
doing DB txns via JDBC)
Extend HibernateDAOSupport and AOP
o Configure HibernateSessionFactory
o Extend the DAO implementation of the HibernateDAOSupport
class
o Wire in the transaction support using AOP

AOP

Modularize cross cutting concerns such as logging, transaction


management, etc.

Aspect

Cross cutting concern

Joint Point

A certain point in the execution of a program

Advice

Action taken by Aspect at a Joint Point. Can be done in 2 ways :


1. Annotations based - it is defined by a point cut expression.
2. Schema based everything defined using <aop: tags in the config
file
Before advice advice executes before joint point
After returning advice executes after joint point exits normally
without exception
After throwing advice executes after joint point throws exception
After advice (finally) advice executes after joint point, whether exits
normally or with exception
Around advice advice executes both before and after joint point

Interceptors

Hibernate:
-

.hbm files

preHandle() fired before request is processed


postHandle() fired after request is processed
afterCompletion() fired after view is rendered

.cfg file

Advantages of Hibernate :
-

Boiler plate code is abstracted out into xml files


Mapping between tables and objects using xml
Database independent

Disadvantages of Hibernate :
-

Have to learn new API


Debug and performance issues
Slower than JDBC
Gets complicated when there is many-many relationships

Session

SessionFactory

1st level cache

2nd level cache

Data is shared across txns within the


same session

Data is shared across sessions

Session.load()

Session.get()

If you are certain object exists in cache,


avoid DB hit

If you are not sure if object exists in cache, hit the


DB to fetch data

If object not found in cache, it throws an


exception

If object not found in cache, it returns null, so check


for null

Transient object is instantiated but not associated with session


Persistent object is associated with session
Detached object exists but detached from session (session is closed)

update()

merge()

Use update() when you are sure that object


already exists and is associated to a session

Use merge() when you are not sure that object


exists and is associated to a session

WEB SERVICES
Reusable component , that can be exposed as a service, and made
available over the network , for remote access.

Interoperability
XML
SOAP

ability to integrate when we have diverse systems, platforms, la


applications

language gives capability to send data in generic format that


network over communication protocol like SOAP

Simple Object Access Protocol allows communication between a


remote machines. It in turn uses transport protocols like HTTP, S
Envelope
-

Header(o)
Body
o Request
o Response
o Fault(o)

SOAP Faults
Version Mismatch

Invalid namespace in envelope

Must understand

SOAP processor is unable to process header

Client

Client incorrectly formed the SOAP message

Server

Server cannot process SOAP message

Principles of SOA

Standard service contract between provider and consumer

Loose coupling to reduce dependency and maintain only awareness of each


other

Abstraction to hide logic from outside world

Autonomous so that services alone have total control over the logic

Reusable

Statelessness

Granularity

Discoverability

Composability

10 Interoperability

Webservice protocol stack

Service transport layer Responsible for transporting messages between applications usin
XML messaging layer

Responsible for encoding messages into common XML format so


consumer can understand

Service discovery
layer

Responsible for centralized distributed object lookup providing pu


UDDI

Service description
layer

Responsible for describing the public interface for the service usi

Bottom Up(Java first)

Top Down(WSDL first)


WSDL annotations(JAXWS)

Requires less knowledge of WSDL, XML, XSD

Requires more knowledge o

Interoperability issues may occur with consumers/providers


written in other languages

Better interoperability

If end point interface changes, WSDL changes , and client


to be rewritten

Less sensitive to change

WSDL elements :
Types

Data types, pojos, XSD elements. All XSD types can be declared in separ
then linked into WSDL

Message

Message types based on XSD types for REQUEST, RESPONSE and FAULT

Port Type

Links operations and message types.


-request
-response
-fault

Binding

Protocol and data format for particular port type

Service

Binds java service to port, this is where you define soap address(end poi

JAXWS specification is used, it is pre-included in JEE5. Once you have


application server plugin, if you create a web project, the required jars are
auto included by application server.

You use Endpoint.publish(http://...,new MyService()). If you paste endpoint


url in browser it will give the WSDL, so use WSDL to generate client.

Class will have @WebService and method will have @WebMethod

@WebMethod

action value of soap action


exclude true/false
operationName - <wsdl:operation

@WebService

name - <wsdl:portType name=


portName - <wsdl:port name=
serviceName - <wsdl:service name=
targetNamespace namespace for <wsdl:portType
endpointInterface complete name of service endpoint
wsdlLocation location of pre-defined WSDL

If class has @WebService then all public methods are automatically


webmethods, no need to explicitly put @WebMethod for each method.

@Oneway

means method has only input but no output

@WebParam

(name maps to <part name=


(header = true means it is a header field

@WebFault

maps to <wsdl:fault

@WebResult

return value of a webmethod

@postConstruc

This method is executed after dependency injection is applied on the

class

@preDestroy

This method is executed just before instance is being removed by


container

@Resource

Maps webservicecontext resource to a field or method

JAX RPC

JAX WS

Cannot support asynchronous and message oriented


web services

Supports asynchronous and mess


web services

Uses java type binding and only 90% XML

100% XML with JAXB

No annotations and Deployment Descriptor is must

Uses annotations and Deploymen


optional

Advantages of webservices:
-

JAXWS has API to access the header info


Stateless so only one instance available for all callers, so thread safe

Disadvantages of webservices:
-

Need to know XML


All data types to be XML types
Marshalling and unmarshalling overhead
Distributed transaction management is not possible. E.g. there are 3
method calls and method2 call is to a webservice. If method 3 fails,
then there is no way to tell the webmethod to rollback.

SOAP engines Apache Axis, JBoss WS


JBoss 5.0 is the best app server for webservices.

REST

SOAP

Exposes resources which represent data

Exposes operations which represent

Uses HTTP (GET/POST/DELETE)

Uses HTTP POST only

Point-to-point tunneling

Distributed messaging

Supports multiple data formats

Supports only XML

Supports stateless communication only

Supports stateless , stateful and asyn


messaging

Lightweight does not require XML parsing


Not secure, does not use contract(WSDL)

Você também pode gostar