Servlets and Java Server Pages and SCWCD Notes
by Sandeep Desai (http://www.thedesai.net/sandeep)
This document can be used as a reference for Servlets and
JSP. It also can be used for the Sun Certified Web Components Developers
Certification 1.4 exam
Book Reference:
Head First Servlets and Java Server Pages by Kathy Sierra,
Bert Bates and Bryan Basham
Mock exams
Jdiscuss, J2EECertificate, Whizlabs
Download Tomcat Servlet and JSP
container 5.0 or greater
Browser (IE, Mozilla)
Send requests to
web server
mime type (type of
documents that browser understand e.g html, text, mpeg etc)
URL (Uniform Resource Locator)
HTTP (Hypertext Tranfer Protocol, stateless protocol)
GET-> Send
parameters as part of URL (e.g http://www.thdesai.net/get?s=a)
get less secure
POST -> Send
parameters as part of HTTP post
CGI (Common Gateway Interface)
Tomcat
Servlet container
- Lifecycle
management
- multi-threading
support
- configurable
security (not hard coded in servlet code
- JSP
support
- communication
with web server
Distributing servlet
- default
servlet context present on only one JVM
- separate
instance of non default servlet context available for each JVM
- <distributable>
in DD
Thread safe
- local
variables
- request
attributes
Not Thread safe
- instance
variables
- class
variables
- session
attributes
- context
attributes
Web application has
- Servlet
and JSP files
- XML
based deployment descriptor (DD)
- should
not override container implementation classes
myservlet Web Application
Web Application directory structure
webapps
MyApp
*.jsp, *.html (directly accessible)
client applet jar files
WEB-INF
web.xml (Deployment Descriptor)
tags
classes
lib
x.jar
META-INF
tags
tlds
*.jsp and *.html under the app directory or
subdirectory are directly accessible by a browser (Invalid request produce 404 not found error)
*.jsp and *.html can also be under WEB-INF or
subdirectory under WEB-INF. These are not directly accessible by URL
*.tld under WEB-INF directory or subdirectory
*.tld in a jar file under META-INF directory or subdirectory
.tag or .tagx under tags directory or
WEB-INF\lib\*.jar\META-INF\tags directory or subdirectory
servlet classes under WEB-INF\classes or
WEB-INF\lib\*.jar
tag handler class under WEB-INF\classes or
WEB-INF\lib\*.jar
*.jar under WEB-INF\lib
WAR (Web Archive) file structure
- structure
as shown above
- Web
App directory structure and
META-INF directory with MANIFEST.MF file
- Deploy
a war file by placing it in the webapps directory
- The
name of the war file becomes the Web App Name
- library
dependencies can be declared in MANIFEST.MF file
- Container
looks at classes in the WEB-INF/classes first and then in
WEB-INF/lib/*.jar
- Access
images etc from jar files using getResource() and getResourceAsStream()
XML compliant JSP document, used by tool vendors
Enclose document with jsp:root,
taglib in jsp:root itself
jsp:root optional in JSP 1.2
version attribute mandatory
<jsp:root version
="1.2" xmlns:test="foo.tld">
|
|
Normal JSP syntax
|
JSP document syntax
|
|
Directives
(except taglibs)
|
<%@
page import="java.io.*" %>
|
<jsp:directive.page
import="java.io.*"/>
|
|
Declaration
|
<%!
int x=0; %>
|
<jsp:declaration>
int x=0; </jsp:declaration>
|
|
scriptlet
|
<%
++x; %>
|
<jsp:scriptlet>
++x; </jsp:scriptlet>
|
|
Text
|
Hello
World
|
<jsp:text>Hello
World<jsp:text>
|
|
Scripting expression
|
<%=
x %>
|
<jsp:expression>
x </jsp:expression>
|
Security
|
|
Responsiblity
|
|
Authentication (userid/password)
|
Admin
|
|
Authorization (roles e.g guest, admin)
|
Deployer
|
|
Confidentiality (e.g using public keys)
|
Deployer
|
|
Data Integrity
(encryption using https)
|
Deployer
|
Realm is a place where authentication information is stored
Tomcat stores users list in
conf/tomcat-users.xml file. The storage mechanism and data structure is vendor
specific
<?xml
version='1.0' encoding='utf-8'?>
<tomcat-users>
<role rolename="tomcat"/>
<role rolename="manager"/>
<role rolename="admin"/>
<user username="tomcat"
password="tomcat" roles="tomcat"/>
<user username="admin"
password="admin" roles="admin,manager"/>
</tomcat-users>
In DD
<security-role>
<role-name>admin</role-name>
</security-role>
<login-config>
<auth-method>BASIC</auth-method>
</login-config>
Design Principles
·
Code to interface
·
separation of concern.
·
Cohesion, degree to which class is designed for one
task or purpose
·
Hide complexity
·
Loose coupling, keep classes less interdependent
·
Proxy
·
Make app more declarative i.e. easier to modify at
deploy time
Patterns
See
Patterns document for more details
Composite
·
Used for combining UI elements in the form of a tree
Business Delegate (hide remote proxy business object)
- Acts
as proxy implementing remote service's interface
- Initiates
communications with remote service
- Handles
communications details and exceptions
- Receives
request from controller
- Translates
the request and forwards it to the business service (stub)
- Translates
the response and returns it to the controller component
- Makes
controller more cohesive
- Principles
- OO
principles
- hiding
complexity
- coding
to interfaces
- loose
coupling
- separation
of concerns
- Minimizes
impact on the web tier when changes occur in the business tier
- Reduces
coupling between tiers
- Adds
a layer to the application, which increases complexity
- Method
calls should be coarse grained to reduce network traffic
Service Locator (used for registry (JNDI) lookup of
components)
- Obtains
InitialContext objects
- Performs
registry lookups
- Handle
communications details and exceptions
- Can
improve performance by caching previously obtained references
- Works
with variety of registries such as: JNDI, RMI, UDDI and COS naming
- Principles
- OO
Principles
- hiding
complexity
- separation
of concerns
- Minimizes
the impact on the web tier when remote components change locations or
containers
- Reduces
coupling between tiers
Transfer Object (minimize network traffic by providing local representation
of remote object)
- e.g
Minimze a lot of getName() getAddress() remote calls, instead create
Person transfer object
- Provides
a local representation of a remote entity (i.e object maintains some
state)
- minimize
network traffic
- follow
Javabean conventions so that it can be easily accessed by other objects
- Implemented
as a serializable object so that it can move across the network
- Typically
easily accessible by view components
- Principles
- reducing
network traffic
- Minimize
performance impact on the web tier when remote components data is
accessed with fine-grained calls
- Reduces
coupling between tiers
- Data
can be stale
- Making
updatable Transfer objects concurrency-safe is typically complex
Intercepting Filter (modify requests before going to
servlet or response before it sent back to browser)
·
Intercept and/or
modify requests before they reach servlet
·
Intercept and/or
modify request before they are returned to browser
·
Filters are deployed
declaratively in DD
·
Filters can be chained
·
Filter lifecycle is
managed by the container
·
Filter must implement init()
destroy() and doFilter() callback
·
Principles
o OO Principles
·
cohesion,
·
loose coupling
o Declarative control allows filter to be added or
remove easily
o Declarative control allows filter chaining sequence
to changed easily
Data Access Object
·
specify data source at
deploy time
·
data client
independant of data source API
Model, View, Controller (MVC)
- Views
can change independently from controllers and models
- Model
components hide internal details from view and controller
- Model
can be migrated to remote business components
- Views
- Renders
model
- requests
updates from model
- sends
user gestures to controller
- allows
controller to select view
- Controller
- translate
view interaction to model action
- Principles
- OO
Principles
- separation
of concerns
- loose
couplings
- Increases
cohesion in individual components
- Increases
overall complexity of application
- Minimizes
impact of change in other tiers to the application
Front Controller (gather redundant request processing into
single component)
- centralizes
a web app's initial request handling tasks in a single component
- Using
the front controller with other patterns can provide loose coupling by
making presentation tier dispatching declarative
- Front
Controller subset of Struts. Better to use struts
- Principles
- OO
Principles
- hiding
complexity
- separation
of concerns
- loose
coupling
- Increases
cohesion in application controller components
- Decreases
the overall complexity of the application
- Increases
the maintainability of the infrastructure code
Struts Framework implementation of Front Controller
- Declarative
maps between request URLs, validation objects, model-invoking objects and
views
- Automated
Request Dispatching: Action .execute() method returns a symbolic
ActionForward which tells the ActionServlet which view to dispatch to. Another
layer of abstraction (loose coupling)
- DataSources:
provides DataSource management
- Custom
Tags:
- Internationalization
support
- Declarative
Validation
- Global
exception handling: exception specific to application code in Action
object
- Plug-ins:
e.g. Validator plugin to enhance struts application has its own init() and
destroy()