Download servlet-name

Document related concepts
no text concepts found
Transcript
Aspiration- Beyond Expectation- 9374928879
MVC
The main aim of the MVC architecture is to separate the business logic and application data from the
presentation data to the user.
Here are the reasons why we should use the MVC design pattern.
1.
2.
They are resuable : When the problems recurs, there is no need to invent a new solution, we
just have to follow the pattern and adapt it as necessary.
They are expressive: By using the MVC design pattern our application becomes more
expressive.
Model
The model object knows about all the data that need to be displayed.
It is model who is aware about all the operations that can be applied to transform that object.
It only represents the data of an application. The model represents enterprise data and the business rules
that govern access to and updates of this data.
Model is not aware about the presentation data and how that data will be displayed to the browser.
View
The view represents the presentation of the application.
The view object refers to the model. It uses the query methods of the model to obtain the contents and
renders it. The view is not dependent on the application logic.
It remains same if there is any modification in the business logic. In other words, we can say that it is the
responsibility of the of the view's to maintain the consistency in its presentation when the model changes.
Controller
Whenever the user sends a request for something then it always go through the controller.
The controller is responsible for intercepting the requests from view and passes it to the model for the
appropriate action. After the action has been taken on the data, the controller is responsible for directing
the appropriate view to the user.
Difference between Model 1 and Model 2 architecture:
Features of MVC1:
1. Html or jsp files are used to code the presentation. To retrieve the data JavaBean can be used.
2. In mvc1 architecture all the view, control elements are implemented using Servlets or Jsp.
3. In MVC1 there is tight coupling between page and model as data access is usually done using
Custom tag or through java bean call.
Features of MVC2:
1. The MVC2 architecture removes the page centric property of MVC1 architecture by separating
Presentation, control logic and the application state.
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
2. In MVC2 architecture there is only one controller which receives all the request for the application
and is responsible for taking appropriate action in response to each request.
Both servlets and JavaServer Pages.
In this approach, known as the Model View Controller (MVC) or Model 2 architecture, you let each
technology concentrate on what it excels at. The original request is handled by a servlet.
The servlet invokes the business-logic and data-access code and creates beans to represent the results
(that's the model).
Then, the servlet decides which JSP page is appropriate to present those particular results and forwards
the request there (the JSP page is the view). The servlet decides what business logic code applies and
which JSP page should present the results (the servlet is the controller).
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
Implementing MVC with RequestDispatcher
1. Define beans to represent the data.
2. Use a servlet to handle requests.
3. Populate the beans. The servlet invokes business logic (application-specific code) or data-access
code to obtain the results.
4. Store the bean in the request, session, or servlet context. The servlet calls setAttribute on the
request, session, or servlet context objects to store a reference to the beans that represent the
results of the request.
5. Forward the request to a JSP page. The servlet determines which JSP page is appropriate to the
situation and uses the forward method of RequestDispatcher to transfer control to that page.
6. Extract the data from the beans. The JSP page accesses beans with jsp:useBean and a scope
matching the location of step 4. The page then uses jsp:getProperty to output the bean properties.
The JSP page does not create or modify the bean; it merely extracts and displays data that the
servlet created.
Defining Beans to Represent the Data
Writing Servlets to Handle Requests
Populating the Beans
Storing the Results
Storing data that the JSP page will use only in this request. First, the servlet would create and
store data as follows:
ValueObject value = new ValueObject(...);
request.setAttribute("key", value);
Next, the servlet would forward the request to a JSP page that uses the following to retrieve the
data.
<jsp:useBean id="key" type="somePackage.ValueObject" scope="request" />
The request attributes are independent of the information coming from the client; they are just
application-specific entries in a hash table that is attached to the request object. This table simply
stores data in a place that can be accessed by both the current servlet and JSP page, but not by
any other resource or request.
Storing data that the JSP page will use in this request and in later requests from the same client.
First, the servlet would create and store data as follows:
ValueObject value = new ValueObject(...);
HttpSession session = request.getSession();
session.setAttribute("key", value);
Next, the servlet would forward to a JSP page that uses the following to retrieve the data:
<jsp:useBean id="key" type="somePackage.ValueObject" scope="session" />
Storing data that the JSP page will use in this request and in later requests from any client. First,
the servlet would create and store data as follows:
ValueObject value = new ValueObject(...);
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
getServletContext().setAttribute("key", value);
Next, the servlet would forward to a JSP page that uses the following to retrieve the data:
<jsp:useBean id="key" type="somePackage.ValueObject" scope="application" />
the servlet code is normally synchronized to prevent the data changing between the servlet and
the JSP page.
Forwarding Requests to JSP Pages
You forward requests with the forward method of RequestDispatcher. You obtain a RequestDispatcher
by calling the getRequestDispatcher method of ServletRequest, supplying a relative address.
Forwarding to Static Resources
Redirecting Instead of Forwarding
The standard MVC approach is to use the forward method of RequestDispatcher to transfer control from
the servlet to the JSP page. However, when you are using session-based data sharing, it is sometimes
preferable to use response.sendRedirect.
Here is a summary of the behavior of forward.
Control is transferred entirely on the server. No network traffic is involved.
The user does not see the address of the destination JSP page and pages can be placed in WEB-INF
to prevent the user from accessing them without going through the servlet that sets up the data.
This is beneficial if the JSP page makes sense only in the context of servlet-generated data.
Here is a summary of sendRedirect.
Control is transferred by sending the client a 302 status code and a Location response header.
Transfer requires an additional network round trip.
The user sees the address of the destination page and can bookmark it and access it
independently. This is beneficial if the JSP is designed to use default values when data is missing.
For example, this approach would be used when redisplaying an incomplete HTML form or
summarizing the contents of a shopping cart. In both cases, previously created data would be
extracted from the user's session, so the JSP page makes sense even for requests that do not
involve the servlet.
Extracting Data from Beans
The JSP page never creates the objects. The servlet, not the JSP page, should create all the data
objects. So, to guarantee that the JSP page will not create objects, you should use


<jsp:useBean ... type="package.Class" />
instead of
<jsp:useBean ... class="package.Class" />.
The JSP page should not modify the objects. So, you should use jsp:getProperty but not
jsp:setProperty.
The scope you specify should match the storage location used by the servlet. For example, the following
three forms would be used for request-, session-, and application-based sharing, respectively.
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
<jsp:useBean id="key" type="somePackage.SomeBeanClass" scope="request" />
<jsp:useBean id="key" type="somePackage.SomeBeanClass" scope="session" />
<jsp:useBean id="key" type="somePackage.SomeBeanClass" scope="application" />
This section summarizes the code that would be used for request-based, session-based, and
application-based MVC approaches.
Request-Based Data Sharing
With request-based sharing, the servlet stores the beans in the HttpServletRequest, where they are
accessible only to the destination JSP page.
Servlet
ValueObject value = new ValueObject(...);
request.setAttribute("key", value);
RequestDispatcher dispatcher =request.getRequestDispatcher("/WEB-INF/SomePage.jsp");
dispatcher.forward(request, response);
JSP Page
<jsp:useBean id="key" type="somePackage.ValueObject" scope="request" />
<jsp:getProperty name="key" property="someProperty" />
Session-Based Data Sharing
With session-based sharing, the servlet stores the beans in the HttpSession, where they are accessible to
the same client in the destination JSP page or in other pages.
Servlet
ValueObject value = new ValueObject(...);
HttpSession session = request.getSession();
session.setAttribute("key", value);
RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/SomePage.jsp");
dispatcher.forward(request, response);
JSP Page
<jsp:useBean id="key" type="somePackage.ValueObject" scope="session" />
<jsp:getProperty name="key" property="someProperty" />
Application-Based Data Sharing
With application-based sharing, the servlet stores the beans in the ServletContext, where they are
accessible to any servlet or JSP page in the Web application. To guarantee that the JSP page extracts the
same data that the servlet inserted, you should synchronize your code as below.
Servlet
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
synchronized(this) {
ValueObject value = new ValueObject(...);
getServletContext().setAttribute("key", value);
RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/SomePage.jsp");
dispatcher.forward(request, response);
}
JSP Page
<jsp:useBean id="key" type="somePackage.ValueObject" scope="application" />
<jsp:getProperty name="key" property="someProperty" />
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
Expression Language
These tag libraries provide support for common, structural tasks, such as: iteration and conditionals,
processing XML documents, internationalization and database access using the Structured Query
Language (SQL).
The Expression Language introduced in JSTL 1.0 is now incorporated in JavaServer Pages specification(JSP
2.0). This articie gives some idea about what is Expression Language and how to simplify the maintenance
for JSP applications by avoiding scripting elements.
The pattern that identifies Expression Language is ${ }.
To deactivate the evaluation of EL expressions, we specify the isELIgnored attribute of the page directive:
<%@ page isELIgnored ="true|false" %>
The valid values of this attribute are true and false. If it is true, EL expressions are ignored when they
appear in static text or tag attributes. If it is false, EL expressions are evaluated by the container.
In particular, the expression language supports the following capabilities
Concise access to stored objects. To output a "scoped variable" (object stored with setAttribute
in the PageContext, HttpServletRequest, HttpSession, or ServletContext) named saleItem, you use
${saleItem}.
Shorthand notation for bean properties. To output the companyName property (i.e., result of
the getCompanyName method) of a scoped variable named company, you use
${company.companyName}. To access the firstName property of the president property of a
scoped variable named company, you use ${company.president.firstName}.
Simple access to collection elements. To access an element of an array, List, or Map, you use
${variable[indexOrKey]}. Provided that the index or key is in a form that is legal for Java variable
names, the dot notation for beans is interchangeable with the bracket notation for collections.
Succinct access to request parameters, cookies, and other request data. To access the
standard types of request data, you can use one of several predefined implicit objects.
A small but useful set of simple operators. To manipulate objects within EL expressions, you
can use any of several arithmetic, relational, logical, or empty-testing operators.
Conditional output. To choose among output options, you do not have to resort to Java scripting
elements. Instead, you can use ${test ? option1 : option2}.
Automatic type conversion. The expression language removes the need for most typecasts and
for much of the code that parses strings as numbers.
Empty values instead of error messages. In most cases, missing values or
NullPointerExceptions result in empty strings, not thrown exceptions.
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
Operators which can be used in EL expression
Operator
Description
.
Access a bean property or Map entry.
[]
Access an array or List element.
()
Grouping of a subexpression for evaluation order.
?:
Conditional test: condition ? ifTrue : ifFalse.
+
Addition.
Subtraction.
*
Multiplication.
/or div
Division.
% or mod M Modulo (remainder).
== or eq
equality.
!= or ne
inequality.
< or lt less than.
> or gt
greater than.
<= or le
less than or equal.
>= or ge
greater than or equal.
&& or and
logical AND.
|| or or
logical OR.
! or not
Unary Boolean complement.
empty
Test for null,empty String,array or Collection.
func(args)
A function call.
Example# EL basic 1 Arithmetic operator
Output View
Coding View of El2.jsp
<html>
<head>
<title>Basic Arithmetic</title>
</head>
<body>
<h3>Basic Arithmetic</h3>
<br>
<code>
<table border="1">
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
<thead>
<td><b>EL Expression</b></td>
<td><b>Result</b></td>
</thead>
<tr>
<td>\${2 + 2}</td>
<td>${2 + 2}</td>
</tr>
<tr>
<td>\${2.2 + 2.3}</td>
<td>${2.2 + 2.3}</td>
</tr>
<tr>
<td>\${12%4}</td>
<td>${12%4}</td>
</tr>
<tr>
<td>\${12 mod 4}</td>
<td>${12 mod 4}</td>
</tr>
<tr>
<td>\${(1==2) ? 3 : 4}</td>
<td>${(1==2) ? 3 : 4}</td>
</tr>
</table>
</code>
</body>
</html>
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
Example# EL basic 2 Comparison operator
Output View
Coding View of El3.jsp
<html>
<head>
<title>Basic Comparisons</title>
</head>
<body>
<h1>Basic Comparisons</h1>
<table border="1">
<thead>
<td><b>EL Expression</b></td>
<td><b>Result</b></td>
</thead>
<tr>
<td>\${5 &lt; 7}</td>
<td>${5 < 7}</td>
</tr>
<tr>
<td>\${5 lt 7}</td>
<td>${5 lt 7}</td>
</tr>
<tr>
<td>\${4 &gt; (6/2)}</td>
<td>${4 > (6/2)}</td>
</tr>
<tr>
<td>\${4 &gt; (6/2)}</td>
<td>${4 > (6/2)}</td>
</tr>
<tr>
<td>\${6.0 &gt;= 3}</td>
<td>${6.0 >= 3}</td>
</tr>
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
<tr>
<td>\${6.0 ge 3}</td>
<td>${6.0 ge 3}</td>
</tr>
<tr>
<td>\${4 &lt;= 3}</td>
<td>${4 <= 3}</td>
</tr>
<tr>
<td>\${4 le 3}</td>
<td>${4 le 3}</td>
</tr>
<tr>
<td>\${2.0 == 2}</td>
<td>${2.0 == 2}</td>
</tr>
<tr>
<td>\${2.0 eq 2}</td>
<td>${2.0 eq 2}</td>
</tr>
<tr>
<td>\${(10*10) != 100}</td>
<td>${(10*10) != 100}</td>
</tr>
<tr>
<td>\${(10*10) ne 100}</td>
<td>${(10*10) ne 100}</td>
</tr>
</table>
</body>
</html>
EL implicit objects
Identifier
pageContext
pageScope
requestScope
sessionScope
applicationScope
parametersparam
paramValues
header
headerValues
cookie
initParam
Description
PageContext instance , servletContext , session, request ,response
Map-associates name and values of page-scoped attributes
Map-associates name and values of request-scoped attributes
Map-associates name and values of session-scoped attributes
Map-associates name and values of application-scoped attributes
Map-stores the primary values of the request parameters by name
Map-stores all values of the request parameters as String arrays
Map-stores the primary values of the request headers by name
Map-stores all values of the request headers as String arrays
Map-stores the cookies accompanying the request by name
Map-stores the context initialization params of the appln by name
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
Example# EL basic 3
Output View
Coding View of El1.jsp
<html>
<head>
<title> Use of Expression Language in jsp</title></head>
<%pageContext.setAttribute("pageColor", "#FFFFDF");%>
<%pageContext.setAttribute("boSize", "5");%>
<body>
<table bgcolor="${pageScope.pageColor}" border="${pageScope.boSize}" width="50%">
<tr>
<td>
<b>hi welcome to aspiration</b></td>
</tr>
<tr>
<td>
You appear to be using the following browser:<br>${header["user-agent"]}
</td>
</tr>
</table>
</body>
</html>
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
Example# EL basic 4 Parameter
Output View
Coding View of El4.jsp
<%@page language="java"%>
<html>
<head>
<title>[]</title>
</head>
<body>
<form action="El5.jsp">
First Name:<input type='text' name='Name'/><br>
Address :<input type='text' name='Address'/>
<input type='submit' value='Submit'/>
</form>
</body>
</html>
Coding View of El5.jsp
<%@page language="java"%>
<html>
<head>
<title>[]</title>
</head>
<body>
<form>
Name is : ${param.Name} <br>
Address is : ${param.Address}
</form>
</body>
</html>
Example# EL basic 5 Cookie
Output View
Coding View of El6.jsp
<%@page language="java"%>
<html>
<head>
<title>Cookie</title>
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
</head>
<body>
<form action="El7.jsp">
<%
Cookie c=new Cookie("name","Shyam Chawda");
response.addCookie(c);
%>
<input type='submit' value='Submit'/>
</form>
</body>
</html>
Coding View of El7.jsp
<%@page language="java"%>
<html>
<head>
</head>
<body>
<form>
Name : ${cookie["name"]} <br>
Value : ${cookie["name"].value}
</form>
</body>
</html>
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
Structure of Web Applications
Web application has a standardized format and is portable across all compliant Web or application servers.
The top-level directory of a Web application is simply a directory with a name of your choosing. Within
that directory, certain types of content go in designated locations.
Default WebApp/(Publicly available files, such as
| .jsp, .html, .jpg, .gif)
|
+WEB-INF/-+
|
+ classes/(directory containing
|
Java classes including
|
servlets used by the
|
Web Application)
|
+ lib/(directory containing
|
jar files used by the
|
Web Application)
|
+ web.xml
|
+ weblogic.xml
JSP Pages
JSP pages should be placed in the top-level Web application directory or in a subdirectory with any name
other than WEB-INF or META-INF. Servers are prohibited from serving files from WEB-INF or META-INF to
the user.
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
Once you register a prefix, JSP pages are then accessed with URLs of the form
http://host/webAppPrefix/filename.jsp (if the pages are in the top-level directory of the Web application)
or http://host/webAppPrefix/subdirectory/filename.jsp (if the pages are in a subdirectory).
It depends on the server whether a default file such as index.jsp can be accessed with a URL that specifies
only a directory (e.g., http://host/webAppPrefix/) without the developer first making an entry in the Web
app’s WEB-INF/web.xml file.
If you want index.jsp to be the default file name, we strongly recommend that you make an
explicit welcome-file-list entry in your Web app’s web.xml file.
For example, the following web.xml entry specifies that if a URL specifies a directory name but no file
name, the server should try index.jsp first and index.html second.
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
HTML Documents, Images, and Other Regular Web Content
They are placed in exactly the same locations and accessed with URLs of exactly the same form.
Individual Servlets, Beans, and Helper Classes
Servlets and other .class files are placed either in WEB-INF/classes or in a subdirectory of WEBINF/classes that matches their package name. To access one of these servlets, you need to designate the
specific URL for it by specifying the servlet-mapping element in the web.xml deployment descriptor file
that is located within the WEB-INF directory of the Web application.
There is a second way to access servlets without having to specify a custom URL. It is with URLs of the
form http://host/webAppPrefix/servlet/packageName.Servlet- Name. Using this way of accessing servlets
is fine if you want to try capabilities or make a quick test case. However, we recommend you do not use
this approach for real-world applications.
Deployment Descriptor
The deployment descriptor file, web.xml, should be placed in the WEB-INF subdirectory of the main Web
application directory.
Note that a few servers have a global web.xml file that applies to all Web applications. For example,
Tomcat uses tomcat_dir/conf/web.xml for global configuration settings.
Tag Library Descriptor Files
Tag Library Descriptor (TLD) files should be placed inside of the WEB-INF directory or any subdirectory of
WEB-INF.
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
Grouping them in a common directory (e.g., tlds) simplifies their management. JSP pages can access TLD
files that are in WEB-INF using a taglib directive as follows:
<%@ taglib uri="/WEB-INF/tlds/myTaglibFile.tld" ...%>
Because it is the server, not the client (e.g., Web browser), that accesses the TLD file, the prohibition that
content inside of WEB-INF is not Web accessible does not apply.
When deployed inside a JAR file, the .tld file should be placed inside the META-INF directory or any
subdirectory of META-INF. The switch in location from WEB-INF to META-INF is because JAR files are not
Web application archives and thus don’t contain a WEB-INF directory.
Tag Files
Tag files should be placed in the WEB-INF/tags directory or a subdirectory of WEB-INF/tags.
As with TLD files, tag files are still accessible to JSP pages even though they are located inside of the
protected WEB-INF directory. Tag files are also declared inside a JSP page through the taglib directive.
However, instead of uri, they use the tagdir attribute. For example, if we placed the myTagFile.tag file
inside of the WEB-INF/tags directory of our Web application, the taglib directive of a JSP page would look
something like this:
<%@ taglib tagdir="/WEB-INF/tags" ...%>
WAR Manifest File
When you create a WAR file, a MANIFEST.MF file is placed in the META-INF subdirectory. Normally, the jar
utility automatically creates MANIFEST.MF and places it into the META-INF directory, and you ignore it if
you unpack the WAR file. Occasionally, however, you modify MANIFEST.MF explicitly, so it is useful to
know where it is stored.
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
Web.XML
A deployment descriptor (DD) refers to a configuration file for an artifact that is deployed to some
container/engine.
The deployment descriptor, web.xml, is used to control many facets of a Web application.
Using web.xml, you can assign custom URLs for invoking servlets, specify initialization
parameters for the entire application as well as for specific servlets, control session
timeouts, declare filters, declare security roles, restrict access to Web resources based
on declared security roles, and so on.
It also enumerates enterprise beans referenced in the Web application.
The file goes into the WEB-INF directory under the document root of a web application.
The deployment descriptor is not part of the Java compilation process. Therefore,
changes in web.xml don’t force you to recompile your code.
In addition, the separation between the configuration mechanism, web.xml, and the Java code
allows for the division between the development and deployment roles within the development
process.
The Java developer is relieved of having to know about the specific operational environment while
writing code; this facilitates code reuse.
By editing web.xml, the person deploying the application has the power to affect application
behavior without ever having to deal with Java code. For example, a company might decide to
deploy the same Web application at several office locations.
Even within one company, different offices might have slightly different needs and therefore would
need to customize the application. The exact same compiled Java code could be shipped to all
locations.
The web.xml file would then be used to customize the behavior of the application based on the
particular office location.
Defining the Header and the Root Element
The deployment descriptor, like all XML files, must begin with an XML header. This header declares the
version of XML that is in effect, and gives the character encoding for the file.
The top-level (root) element for the deployment descriptor is web-app.
<web-app
xmlns=http://java.sun.com/xml/ns/j2ee
xmlns:xsi=http://www.w3.org/2001/XMLSchemainstance xsi:schemaLocation=http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/webapp_2_4.xsd version="2.4">
<!-- Your entries go here. All are optional. -->
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
</web-app>
Note that http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd is the only URL that must actually exist,
pointing to the location of the XML Schema file.
The URLs in the declaration of web.xml are namespaces. Namespaces are just unique identifiers for
a particular Schema syntax and could be any unique string.
Version 2.4
The order of web-app subelements does not matter if you are using version 2.4. This is one of
the major differences between web.xml of version 2.4 and earlier versions.
legal elements
The following list shows all
that can appear directly within the web-app
element. Remember that all these elements are optional.
• servlet and servlet-mapping.
You use the servlet element for that purpose. Once you have declared a servlet (using the servlet
element), you can designate one or more URL patterns that allow the clients to invoke the servlet.
• context-param. The context-param element declares application-wide initialization parameters.
• filter and filter-mapping. The filter element associates a name with a class that implements the
javax.servlet.Filter interface. Once you have named a filter, you associate it with one or more servlets or
JSP pages by means of the filter-mapping element.
• welcome-file-list. The welcome-file-list element tells the server what file to use when the server
receives URLs that refer to a directory name but not a file name.
• error-page. The error-page element lets you designate the pages that will be displayed when certain
HTTP status codes are returned or when certain types of exceptions are thrown.
• security-constraint. The security-constraint element lets you designate URLs that should be protected
from unauthorized users. It goes hand-in-hand with the login-config element.
• login-config. You use the login-config element to specify how the server should authenticate users who
attempt to access protected pages. It goes hand-in-hand with the security-constraint element.
• security-role. The security-role element must declare explicit role names used in the role-name
subelements of the auth-constraint element inside every security-constraint element in web.xml. It could
also list security role names that will appear in the role-name subelements of the security-role-refelement
inside the servlet element.
• session-config. If a session has not been accessed for a certain
• icon. The icon element designates the location of either one or two image files that an IDE can use to
represent the Web application.
• display-name. The display-name element provides a name that graphical user interface (GUI) tools
might use to label the Web application.
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
• description. The description element gives explanatory text about the Web application.
• mime-mapping. If your Web application has unusual files that you want to guarantee are assigned
certain MIME types, the mime-mapping element can provide this guarantee.
• jsp-config. The jsp-config element is used to provide configuration information for the JSP pages in a
Web application. It has two subelements, taglib and jsp-property-group. The taglib element assigns
aliases to Tag Library Descriptor (TLD) files.
This capability lets you change the location of the TLD files without editing the JSP pages that use those
files. The jsp-property-group element is used to configure property information for a group of files that
match a URL pattern.
• locale-encoding-mapping-list. This element sets the default locale character encodings using one or
more locale-encodingmapping elements.
• listener. The listener element designates an event listener class. Listener classes are notified when a
particular Web application life-cycle event occurs. For example, it can be notified when the ServletContext
or HttpSession is first initialized or destroyed.
• distributable. The distributable element tells the system that it is safe to distribute the Web application
across multiple servers in a cluster.
• env-entry. The env-entry element declares the Web application’s environment entry.
• ejb-ref. The ejb-ref element declares a reference to the home interface of an enterprise bean.
• ejb-local-ref. The ejb-local-ref element declares a reference to the local home interface of an
enterprise bean.
• service-ref. The service-ref element declares a reference to a Web service.
• resource-ref. The resource-ref element declares a reference to an external resource used with a
resource factory.
• resource-env-ref. The resource-env-ref element declares a reference to an administered object
associated with a resource.
• message-destination-ref. The message-destination-ref element declares a reference to a message
destination associated with a resource.
• message-destination. The message-destination element specifies a logical (e.g., portable) message
destination name.
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
Assigning Names
To provide initialization parameters, define a custom URL, or assign a logical (portable) security role to a
servlet or JSP page, you must first give the servlet or page a name.
You assign a name by means of the servlet element. The most common format includes servlet-name and
servlet-class subelements (inside the web-app element)
<servlet>
<servlet-name>Test</servlet-name>
<servlet-class>coreservlets.TestServlet</servlet-class>
</servlet>
This means that the servlet at WEB-INF/classes/coreservlets/TestServlet is now known by the
registered name Test. Giving a servlet a name has the following major implications: Initialization
parameters, custom URL patterns, and other customizations refer to the servlet by the registered name,
not by the class name.
Defining Custom URLs
To assign a custom URL, you use the servlet-mapping element along with its servlet-name and urlpattern subelements. The servlet-name element specifies the name that was assigned to the servlet
using the servlet-name subelement of the servlet element; url-pattern describes a URL relative to the Web
application root.
The value of the url-pattern element must begin with either a slash (/) or an asterisk and period
combination (*.).
<servlet>
<servlet-name>Test1</servlet-name>
<servlet-class>coreservlets.TestServlet1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Test1</servlet-name>
<url-pattern>/UrlTest1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>H1</servlet-name>
<servlet-class>HiHello</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>H1</servlet-name>
<url-pattern>/H1</url-pattern>
</servlet-mapping>
Above program is TestServlet1 invoked with http://localhost/deployDemo/UrlTest1.
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
The specification allows you to map a servlet to a particular custom URL. For example, here is a simple
web.xml excerpt that lets you use the URL http://host/webApp- Prefix/UrlTest1 to invoke TestServlet1
declared with the name Test1.
Multimapping Patterns
In the majority of cases, you want to assign one URL to each servlet
There are two ways you can accomplish this multimapping:
By giving a url-pattern of /directoryName/*, you can specify that all URLs of the form
http://host/webAppPrefix/directoryName/ blah are handled by the designated servlet.
By giving a url-pattern of *.foo, you can specify that all URLs
http://host/webAppPrefix/.../blah.foo are handled by the designated servlet.
of
the
form
Here is an excerpt from web.xml showing a mapping that lets you use URLs like
http://host/webAppPrefix/UrlTest4, http://host/webAppPrefix/UrlTest4/ (note the slash at the end), h
ttp://host/webAppPrefix/UrlTest4/foo/bar to invoke TestServlet4 declared with the name Test4.
<servlet>
<servlet-name>Test4</servlet-name>
<servlet-class>coreservlets.TestServlet4</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Test4</servlet-name>
<url-pattern>/UrlTest4/*</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>H2</servlet-name>
<servlet-class>HiHello</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>H2</servlet-name>
<url-pattern>/servlet/*</url-pattern>
</servlet-mapping>
Likewise, you can use * if you want all URLs ending with a certain extension to invoke a particular servlet.
For
example,
here
is
an
excerpt
from
web.xml
that
lets
you
use
URLs
like
http://host/webAppPrefix/foo/bar/baz.urlTest5,
http://host/webAppPrefix/foo.urlTest5
to
invoke
TestServlet5 declared with the name
<servlet>
<servlet-name>Test5</servlet-name>
<servlet-class>coreservlets.TestServlet5</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Test5</servlet-name>
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
<url-pattern>*.urlTest5</url-pattern>
</servlet-mapping>
Matching Overlapping Patterns
When mapping a servlet to a URL, the specification does not allow the same value of url-pattern to appear
twice within the same web.xml file.
Thus, there can never be an overlap between two patterns that map exact matches. However, if one or
more servlet mappings use “*”, an overlap could occur.
Compliant servers are required to use the following rules to resolve these overlaps.
• Exact matches are handled first. Thus, if /foo/bar and /foo/* were both url-pattern entries, the first
would take precedence for a request URL of http://host/webAppPrefix/foo/bar. Similarly, /foo/bar.html
would win over *.html for an incoming URL of http://host/webAppPrefix/foo/bar.html.
• Directory mappings are preferred over extension mappings.
Thus, if /foo/* and *.html were both url-pattern entries, the first would take precedence for a request URL
of http://host/webAppPrefix/foo/bar.html.
• For overlapping directory mappings, the longest path is preferred.
Thus, if /foo/bar/* and /foo/* were both url-pattern entries, the first would take precedence for a request
URL of http://host/webAppPrefix/foo/bar/baz.html.
JSP naming conventions
Generally, JSP pages do not need to be declared inside web.xml.
They can be invoked like any other static resource (e.g., somePage.html), provided you place them
outside of WEB-INF.
Declaring a name for a JSP page allows you to provide a name to use with customization settings (e.g.,
initialization parameters and security settings) and so that you can change the URL that invokes the JSP
page
<!-- Register the name "PageName" for TestPage.jsp -->
<servlet>
<servlet-name>PageName</servlet-name>
<jsp-file>/WEB-INF/jspPages/TestPage.jsp</jsp-file>
</servlet>
<!-- Use the URL http://host/webAppPrefix/UrlTest7/foo -->
<servlet-mapping>
<servlet-name>PageName</servlet-name>
<url-pattern>/UrlTest7/*</url-pattern>
</servlet-mapping>
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
Disabling the invoker serlvet
Disabling the invoker servlet, because most servers have a standard servlet that is registered with the
default servlet URLs and simply invokes the real servlet.
One reason for setting up a custom URL for a servlet or JSP page is so that you can register
initialization parameters to be read from the init (servlets) or jspInit (JSP pages) methods.
There are two main approaches for disabling the default URL:
• Remapping the /servlet/ pattern in each Web application.
• Globally turning off the invoker servlet.
Remapping the /servlet/ URL Pattern
It is quite straightforward to disable processing of URLs that begin with http://host/webAppPrefix/servlet/
in a particular Web application.
Simply use <url-pattern>/servlet/*</url-pattern> as the pattern within the servlet-mapping element.
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
Eight basic steps are required to set up your system to use this type of form-based security.
Set up usernames, passwords, and roles. In this step, you designate a list of users and associate each
with a password and one or more abstract roles (e.g., normal user or administrator). This is a completely
server-specific process.
Tell the server that you are using form-based authentication. Designate the locations of the
login and login-failure page.
This process uses the web.xml login-config element with an auth-method subelement of FORM and a
form-login-config subelement that gives the locations of the two pages.
Create a login page.
This page must have a form with an ACTION of j_security_check, a METHOD of POST, a text field named
j_username, and a password field named j_password.
Create a page to report failed login attempts.
This page can simply say something like “username and password not found” and perhaps give a link back
to the login page.
Specify which URLs should be password protected.
For this step, you use the security-constraint element of web.xml. This element, in turn, uses webresource-collection and auth-constraint subelements.
The first of these (web-resourcecollection) designates the URL patterns to which access should be
restricted, and the second (auth-constraint) specifies the abstract roles that should have access to the
resources at the given URLs.
List all possible abstract roles (types of users) that will be granted access to any resource.
Each abstract role is declared using the security-role element. The security-role element contains the
required role-name element, which contains the name of the abstract role.
Specify which URLs should be available only with SSL.
If your server supports SSL, you can stipulate that certain resources are available only through encrypted
HTTPS (SSL) connections. You use the user-data-constraint subelement of security-constraint for this
purpose.
Turn off the invoker servlet.
Security settings are based on URLs, so you protect servlets by listing their URLs within the webresourcecollection element. The servlet URLs, in turn, are normally defined with the url-pattern element of
servlet-mapping. However, many servers also have a default servlet URL of the form
http://host/webAppPrefix/servlet/ServletName. If you have this capability enabled, there are now two
URLs that can invoke each servlet: the URL registered in servlet-mapping and the default (invoker servlet)
URL. Remembering to protect both addresses is too hard. Instead, disable the invoker servlet, either
globally for your server, or by mapping the /servlet/* pattern within your Web application.
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
Servlet 3.0 specifies the following methods that enable you to access security information about the
component’s caller:
getRemoteUser, which determines the user name with which the client authenticated. The
getRemoteUser method returns the name of the remote user (the caller) associated by the container with
the request. If no user has been authenticated, this method returns null.
isUserInRole, which determines whether a remote user is in a specific security role. If no user has been
authenticated, this method returns false. This method expects a String user role-name parameter.
The security-role-ref element should be declared in the deployment descriptor with a role-name
subelement containing the role name to be passed to the method. Using security role references is
discussed in Declaring and Linking Role References.
getUserPrincipal, which determines the principal name of the current user and returns a
java.security.Principal object. If no user has been authenticated, this method returns null. Calling the
getName method on the Principal returned by getUserPrincipal returns the name of the remote user.
reventing unauthorized users from accessing sensitive data. This process involves access restriction
(identifying which resources need protection and who should have access to them) and authentication
(identifying users to determine if they are one of the authorized ones). Simple authentication involves the
user entering a username and password in an HTML form or a dialog box; stronger authentication involves
the use of X.509 certificates sent by the client to the server. The first aspect of Web security applies to
virtually all secure applications. Even intranets at locations with physical access controls usually require
some sort of user authentication.
Preventing attackers from stealing network data while it is in transit. This process involves the use of SSL
to encrypt the traffic between the browser and the server. This capability is generally reserved for
particularly sensitive applications or for particularly sensitive pages within a larger application. After all,
unless the attackers are on your local subnet, it is exceedingly difficult for them to gain access to your
network traffic.
There are two general strategies for implementing these security aspects: declarative security and
programmatic security.
Within the Web application framework, there are two general approaches to this type of security:
1. Declarative security. With declarative security, the topic of this chapter, none of the individual servlets
or JSP pages need any security-aware code. Instead, both of the major security aspects are handled by
the server.
To prevent unauthorized access, you use the Web application deployment descriptor (web.xml) to
declare that certain URLs need protection, and which categories of users should have access to them.
You also designate the authentication method that the server should use to identify users. At request
time, the server automatically prompts users for usernames and passwords when they try to access
restricted resources, automatically checks the results against a predefined set of usernames and
passwords, and automatically keeps track of which users have previously been authenticated. This
process is completely transparent to the servlets and JSP pages.
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
To safeguard network data, you use the deployment descriptor to stipulate that certain URLs should only
be accessible with SSL. If users try to use a regular HTTP connection to access one of these URLs, the
server automatically redirects them to the HTTPS (SSL) equivalent.
With declarative security, the topic of the previous chapter, none of the individual servlets or JSP pages
need any security-aware code. Instead, both of the major security aspects are handled by the server. To
prevent unauthorized access, you use the Web application deployment descriptor (web.xml) to declare
that certain URLs need protection, and which categories of users should have access to them. You also
designate the authentication method that the server should use to identify users. At request time, the
server automatically prompts users for usernames and passwords when they try to access restricted
resources, automatically checks the results against a predefined set of usernames and passwords, and
automatically keeps track of which users have previously been authenticated. This process is completely
transparent to the servlets and JSP pages. To safeguard network data, you use the deployment descriptor
to stipulate that certain URLs should only be accessible with SSL. If users try to use a regular HTTP
connection to access one of these URLs, the server automatically redirects them to the HTTPS (SSL)
equivalent.
Declarative security is all well and good. In fact, it is by far the most common approach to Web application
security. But what if you want your servlets to be completely independent of any server-specific settings
such as password files? Or, what if you want to let users in various roles access a particular resource but
customize the data depending on the role that they are in? Or, what if you want to authenticate users
other than by requiring an exact match from a fixed set of usernames and passwords? That's where
programmatic security comes in.
With programmatic security, the topic of this chapter, protected servlets and JSP pages at least partially
manage their own security. To prevent unauthorized access, each servlet or JSP page must either
authenticate the user or verify that the user has been authenticated previously. Even after the servlet or
JSP page grants access to a user, it can still customize the results for different individual users or
categories of users. To safeguard network data, each servlet or JSP page has to check the network
protocol used to access it. If users try to use a regular HTTP connection to access one of these URLs, the
servlet or JSP page must manually redirect them to the HTTPS (SSL) equivalent.
1. Programmatic security. With programmatic security, the topic of the next chapter, protected servlets and
JSP pages at least partially manage their own security.
To prevent unauthorized access, each servlet or JSP page must either authenticate the user or verify that
the user has been authenticated previously.
To safeguard network data, each servlet or JSP page has to check the network protocol used to access it.
If users try to use a regular HTTP connection to access one of these URLs, the servlet or JSP page must
manually redirect them to the HTTPS (SSL) equivalent.
Declarative security is very convenient: you set up usernames, passwords, access mechanisms (HTML
forms vs. BASIC authentication) and transport-layer requirements (SSL vs. normal HTTP), all without
putting any security-related code in any of the individual servlets or JSP pages. However, declarative
security provides only two levels of access for each resource: allowed and denied. Declarative security
provides no options to permit resources to customize their output depending on the username or role of
the client that accesses them.
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
It would be nice to provide this customization without giving up the convenience of container-managed
security for the usernames, passwords, and roles as would be required if a servlet or JSP page completely
managed its own security (as in Section 4.3). To support this type of hybrid security, the servlet
specification provides three methods in HttpServletRequest:
isUserInRole. This method determines if the currently authenticated user belongs to a specified role. For
example, given the usernames, passwords, and roles of Listing 4.1, if the client has successfully logged in
as user valjean, the following two expressions would return true:
request.isUserInRole("lowStatus")
request.isUserInRole("nobleSpirited")
Tests for all other roles would return false. If no user is currently authenticated (e.g., if authorization
failed or if isUserInRole is called from an unrestricted page and the user has not yet accessed a
restricted page), isUserInRole returns false. In addition to the standard security roles given in the
password file, you can use the security-role-ref element to define aliases for the standard roles. See
the next subsection for details.
getRemoteUser. This method returns the name of the current user. For example, if the client has
successfully logged in as user valjean, request.getRemoteUser() would return "valjean". If no user is
currently authenticated (e.g., if authorization failed or if isUserInRole is called from an unrestricted page
and the user has not yet accessed a restricted page), getRemoteUser returns null.
getUserPrincipal.
This
method
returns
the
current
username
wrapped
inside
a
java.security.Principal object. The Principal object contains little information beyond the username
(available with the getName method). So, the main reason for using getUserPrincipal in lieu of
getRemoteUser is to be compatible with preexisting security code (the Principal class is not specific to
the servlet and JSP API and has been part of the Java platform since version 1.1). If no user is currently
authenticated, getUserPrincipal returns null.
It is important to note that this type of programmatic security does not negate the benefits of containermanaged security. With this approach, you can still set up usernames, passwords, and roles by using your
server's mechanisms. You still use the login-config element to tell the server whether you are using
form-based or BASIC authentication. If you choose form-based authentication, you still use an HTML form
with an ACTION of j_security_check, a text field named j_username, and a password field named
j_password. Unauthenticated users are still automatically sent to the page containing this form, and the
server still automatically keeps track of which users have been authenticated. You still use the securityconstraint element to designate the URLs to which the access restrictions apply. You still use the userdata-constraint element to specify that certain URLs require SSL. For details on all of these topics, see
However, you also add code to some of your resources to customize their behavior based on who is
accessing them.
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
Often, declarative security is server based. Using the server's configuration, you provide protection to a
resource or set of resources. You use the container's authentication and authorization schemes to protect
that resource from unauthorized access.
The declarative approach to security casts a wide net. Declarative security is implemented as a separate
layer from the web components that it works with. You set up a security system, such as a set of file
permissions or users, groups, and roles, and then you plug your application's authentication mechanism
into that layer.
With declarative security, either a user gains access to the resource or they do not. Usually the content
cannot be customized based on roles. In an HTML-based application, the result is that users are denied
access to certain pages. However, in a Flex environment, the typical result of declarative security is that
the user is denied access to the entire application, since the application is seen as a single resource to the
container.
Declarative security lets programmers who write web applications ignore the environment in which they
write. Declarative security is typically set up and maintained by the deployer and not the developer of the
application. Also, updates to the web application do not generally require a refactoring of the security
model.
Programmatic security gives the developer of the application more control over access to the application
and its resources. Programmatic security can be much more detailed than declarative security. For
example, a developer using programmatic security can allow or deny a user access to a particular
component inside the application.
Although programmatic security is typically configured by the developer of the application, it usually
interacts with the same systems as declarative security, so the relationship between developer and
deployer of the application must be cooperative when implementing programmatic security.
Declarative security is recommended over programmatic security for most applications because the design
promotes code reuse, making it more maintainable. Furthermore, declarative security puts the
responsibility of security into the hands of the people who specialize in its implementation; application
programmers can concentrate on writing applications and people who deploy the applications in a specific
environment can concentrate on enforcing security policies and take advantage of that context.
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
omcat implements security as specified in the Java servlet specification. This document primarily addresses
Tomcat 4.x security, which is compliant with the 2.3 servlet specification. Some information is also provided
regarding the forthcoming Tomcat 5.x release, which implements the servlet 2.4 specification. Also, there is
some overlap between security requirements defined in the servlet and J2EE specifications. In general, the J2EE
specification includes all servlet specification requirements and makes some optional requirements mandatory
for a web container to be "J2EE compliant". Tomcat implements most optional servlet specification features
but, as an open source project, has not been able to pass the J2EE compliance tests due to J2EE licensing policy
(recent changes by Sun may allow this in the near future).
Tomcat Security Scope
As stated in the servlet specification, Tomcat security is primarily concerned with:




Authentication - The means by which communicating entities prove their identities to one another.
Access control - The means by which requests for resources are limited to users or programs.
Integrity - The means used to prove that information has not been modified while in transit.
Confidentiality - The means used to ensure that information is understandable only by authorized users.
As defined in the servlet specification, Tomcat security is user role-based and web container (somewhat web
application) centric. Hence, Tomcat security scope, by definition in the servlet specification, does not address
issues of security integration with other web and application servers.
Declarative and Programmatic Security
The servlet specification classifies Tomcat security into two broad categories:


Declarative security is the expression of application security external to the application and is preferred when
sufficient as it allows runtime configuration of application security without recoding the application.
Programmatic security is used to implement fine-grained access control, enabling application components to
become security aware.
It may be easier to think in terms of security you configure in the web application environment (declarative) and
security you define within the web application code (programmatic). Each web application configures
declarative security in its unique deployment descriptor, web.xml. This is a required XML-formatted
configuration file (also called the deployment descriptor) found in each web application's WEB-INF directory.
Programmatic security involves using HttpServletRequest API method calls to make business logic decisions
within the web application context. For example, you may want to make combo box values dynamic based on a
user's identity. The servlet API calls you use are:



getRemoteUser - Returns the user name the client used for authentication.
isUserInRole - Determines if a remote user is in a specified security role.
getUserPrincipal - Returns a java.security.Principal object, which contains the principals name and roles.
Tomcat uses role-based authorization to manage access. With this model, access permissions are granted to an
abstract entity called a security role, and access is allowed only to users or groups of users who have that role.
For example, the Tomcat distribution includes two administrative web applications that only grant access to
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
users with the "manager" role. The deployment descriptor specifies the type of access granted to each role, but
does not specify the role to user or group mappings. That's done in the user repository, which is typically a
relational database or LDAP server in production environments, but is another XML-formatted file named
tomcat-users.xml by default.
<!-- Define a security constraint on this application -->
<security-constraint>
<web-resource-collection>
<web-resource-name>Entire Application</web-resource-name>
<url-pattern>/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<!-- This role is not in the default user directory -->
<role-name>manager</role-name>
</auth-constraint>
</security-constraint>
<!-- Define the login configuration for this application -->
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>Tomcat Manager Application</realm-name>
</login-config>
<!-- Security roles referenced by this web application -->
<security-role>
<description>
The role that is required to log in to the Manager Application
</description>
<role-name>manager</role-name>
</security-role>
Figure 1 - Security snippet from Tomcat Manager's web.xml deployment descriptor
Figure 1.0 shows a security snippet from the Tomcat Manager web application's web.xml file. The security
contraint element defines the URL pattern to match for the constraint to apply (in this example the entire web
application) and an authentication constraint, which will force the user to authenticate. Access is granted only if
an authenticated user has the "manager" role. The login config element defines the type of authentication (more
on this next), in this case HTTP basic. And, the roles referenced by the web application.
Authentication
By default, you do not need to authenticate to access Tomcat resources. Authentication is needed only when
specified in the deployment descriptor with the auth-constrain element. You use a web client (typically a web
browser) to authenticate with Tomcat using one of the following mechanisms:




HTTP Basic Authentication
HTTP Digest Authentication
Form Based Authentication
HTTPS Client Authentication
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
HTTP Basic Authentication
When your browser prompts you for a username and password in a dialog box, you are using HTTP basic
authentication to logon to a web server. This is also know as browser-based authentication because the web
server requests the browser to authenticate you through the HTTP 1.0 protocol. In the dialog box, you also see
the name of a realm to which you will be authenticated. The realm does not necessarily reflect a security policy
domain, which is also referred to as a realm. Think of an HTTP basic authentication realm as a "database" of
usernames and passwords that identify valid users of a web application (or set of web applications), plus a list of
the roles associated with each valid user.
Once you enter your username and password, they are base64 encoded and sent by the browser to Tomcat (for
both secure and non-secure resources). Tomcat authenticates you, and then reauthenticates each subsequent
request against the specified realm. You cannot logout as your username and password remain in browser
memory until you exit. Hence, you must exit the browser to "logout".
Because the username and password are not encrypted, and the target server's identity is not authenticated by
the browser, basic authentication alone is not secure. You can improve security by using a secure transport
mechanism such as HTTPS, or security at the network level such as a VPN. However, if you switch to HTTP
(after authenticating with basic authentication and HTTPS), your browser continues to send your username and
password with each subsequent request in cleartext until you exit.
HTTP Digest Authentication
HTTP digest authentication is also performed by the browser upon request by the web server and based on a
username, password, and realm. However, in this case your password is digested with the secure MD5
algorithm before it is sent by the browser.
You can specify in Tomcat's <realm> element a digest attribute, which must be one of the digest algorithms
supported by the java.security.MessageDigest class (SHA, MD2, or MD5). When you select this option, the
contents of the password that is stored in the realm must be the digest version of the password. The client must
also digest the password using the same algorithm before it is sent. When the realm authenticate() method is
called, the password you input is compared with the value returned by the realm and, if equal, you are
authenticated.
Because your password is digested, HTTP digest authentication is more secure than basic. However, it does
suffer from the same security issues as basic authentication. As it is not supported by popular browsers, HTTP
digest authentication is not required by the servlet specification, but it is implemented by Tomcat. As with basic
authentication, your credentials are stored in the browser's memory until it is exited.
Form Based Authentication
This is the most popular web authentication mechanism in use. It provides the application developer with the
greatest control over the look and feel of the “login screen”, enables closing of user sessions without exiting the
browser, and is more secure than basic authentication.
The web application deployment descriptor contains elements to specify a "login form" and an "error page".
The HTML login form must contain fields for entering a username and a password, which must be named
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
"j_username" and "j_password", respectively. When you attempt to access a protected resource, Tomcat checks
if you are authenticated. If not, the following steps occur:
1.
2.
3.
4.
5.
6.
Tomcat saves the entire HTTP request, then redirects the browser to the configured login form.
You enter your username and password in the login form's "j_username" and "j_password" fields.
The browser posts the form back to the server using the "j_security_check" action.
The container attempts to authenticate the user using the configured security realm.
If authentication fails, the error page is returned with the status code of the response set to 401.
If authentication succeeds, the principal is checked to determine if you have a role authorized to access the
resource.
7. If you are authorized, Tomcat processes the original HTTP request. If authentication fails, or you are not
authorized to access the requested resource, the configured error page is returned.
Because your username and password are not encrypted and the target server is not authenticated, form-based
authentication using HTTP is not secure. If you are using form-based authentication, you should use a secure
transport mechanism such as HTTPS, or security at the network level such as a VPN. However, form-based
authentication is more secure than basic authentication when switching back and forth between HTTPS and
HTTP as your username and password are not sent with each request.
Another advantage of form-based over basic authentication is that the application can programmatically close
your authenticated session, enabling you to logout without restarting your browser. In this respect, calling the
HttpSession.invalidate method seems like it should work, but it does not because HTTP sessions are totally
independent of authentication (e.g., you can have an HTTP session without authenticating and authenticate
without having an HTTP session).
HTTPS Client Authentication
Authentication using HTTPS (HTTP over SSL) enables browsers and web servers to communicate over an
encrypted connection. This is a two-way process, meaning that both the server and the browser encrypt all
traffic before sending out data. Tomcat uses HTTPS for confidentiality (by encrypting the data) and integrity
(which is insured if the message can be decrypted).
Another important aspect of the SSL protocol is authentication. This means that during your initial attempt to
communicate with a web server over a secure connection, that server will present your web browser with a set
of credentials, in the form of a certificate chain, as proof the site is who and what it claims to be. Though
Tomcat supports HTTPS connections and server authentication, it is generally recommended that you off-load
SSL connections to a web server like Apache or IIS and use Tomcat as a plugin to process the servlet and JSP
requests.
The server may also request a client certificate from your browser, asking for proof that you are who you claim
to be. This practice is used more for business-to-business transactions than with individual internet users
because of the overhead required to manage certificates. Most SSL-enabled web servers do not request client
authentication but if you need it, Tomcat does support it.
Web Application Single Sign-on
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
As the underlying principals to which roles are mapped are environment specific rather than web application
specific, it is desirable to:
1. Make login mechanisms and policies a property of the web application environment.
2. Use the same authentication information to represent a principal to all applications in the same container, and
3. Require re-authentication of users only when a security policy domain boundary has been crossed.
Therefore, a J2EE compliant servlet container is required to track authentication information at the container
level (rather than at the web application level). Tomcat enables users authenticated for one web application to
access other web applications managed by the same container. However, login configurations must still be
specified for each web application, which, depending upon the number of web applications can be difficult to
manage (Tomcat also allows each web application to define its own realm). Additionally, Tomcat single sign-on
does not address multiple Tomcat servers, other web servers such as Apache, or an application server like
JBoss.
Specifying Security Constraints
Deployment descriptor <security-constraint> elements define the permissions and rules for the protected
Tomcat resources and include the following XML elements:



web-resource-collection - A set of URL patterns and HTTP methods that describe a set of resources to be
protected. All requests that contain a URL pattern matched in a web resource collection are subject to the
constraint.
auth-constraint - A set of security roles (one or more) to which a user must belong to be granted access to
resources matched by the web resource collection.
user-data-constraint - Describes integrity and confidentiality requirements for the transport layer of the client
server.
Hence, the web resource collection defines the resources, the authorization constraint defines the roles to which
a user can belong to access the resources, and the data constraints defines if HTTPS should be required.
Enhancing Tomcat Security with Cams
When you arrive at the boundary of Tomcat security, you'll discover that it is generally limited by the scope of
the servlet specification and J2EE security. Consequently, Tomcat will not meet the security needs of most
heterogenous, multi-server environments. The good news is that you have the Tomcat source and can write
security code and implement security in servlets to customize Tomcat. The bad news is that you probably don't
have the time, budget, expertise, or even desire to write security code. In addition, embedding low-level security
code within applications is considered to be bad practice.
The Cafésoft Access Management System is designed to pickup where Tomcat security stops. Cams flexibly
meets the needs of the enterprise by providing a complete web access managment system which spans servers
and tiers in a web farm. Cams provides the same security features Tomcat does and more.
From a high-level, you should consider using Cams with Tomcat when you have any of the following needs:
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879




You have a web server farm with more than one stand-alone Tomcat server
You are using Apache and Tomcat servers and desire integrated security
You need centralized security configuration, logging, and events
You need a flexible, easy-to-extend security system
Cams offers many unique features that might more closely adhear to your security needs. The following tables
show a feature by feature comparison of Tomcat security with and without Cams.
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
Two basic approaches to implementing security are programmatic security, in which you embed explicit
security calls directly into your code, and declarative security, in which you specify security policies using
deployment descriptors and configuration files.
When making use of programmatic security, you embed security enforcement within the application with
programmatic checks on policies, to determine what a user is allowed to do or see in the application, and then
react to this information appropriately. Programmatic security can be useful, even required in some situations,
especially in application contexts in which the expressive power of declarative security is insufficient. But
programmatic security should be used with care. If the design and implementation are not clever and the
developers are not careful, such checks become scattered and strewn throughout the application code. This
situation can become extremely difficult to maintain because of duplicated code and nonuniform
implementation styles. For example, a change in a particular piece of business logic might require changing
several pieces of code. This is expensive, because there is more code to update and test, and also error-prone,
because it's difficult to ensure that you've covered all the bases when the code is implemented and distributed in
an ad hoc fashion. So with programmatic security, the onus is on you to architect your security code in such a
way that it's contained and well encapsulated.
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
Filters
Filters are java components that you can use to intercept and process requests before they are sent to the
servlet or to process responses after the servlet has completed, but before the response goes back to the
client.
It works basis on the DD.
In the DD, the deployer maps which filters will be called for which request URL patterns.
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
Advantages
Encapsulate common behavior.
– Have 30 different servlets or JSP pages that need to compress their content to decrease download time?
Make 1 compression filter and apply it to all 30 resources.
Separate high-level access decisions from presentation code.
– Want to block access from certain sites without modifying the individual pages to which these access
restrictions apply? Create an access restriction filter and apply it to as many pages as you like.
Apply wholesale changes to many different resources.
– Have a bunch of existing resources that should remain unchanged except that the company name
should be changed? Make a string replacement filter and apply it wherever appropriate.
Servers load filters into memory when the Web app first comes up. So, if
that filter is not found, your entire Web app is disabled.
Creating a filter involves five basic steps:
Create a class that implements the Filter interface.
Your class will need three methods: doFilter, init, and destroy. The doFilter method contains the main
filtering code , the init method performs setup operations, and the destroy method does cleanup.
Put the filtering behavior in the doFilter method.
The first argument to the doFilter method is a ServletRequest object.
This object gives your filter full access to the incoming information, including form data, cookies, and
HTTP request headers. The second argument is a ServletResponse; it is mostly ignored in simple filters.
The final argument is a FilterChain; it is used to invoke the servlet, JSP page, or the next filter in the chain
as described in the next step.
Call the doFilter method of the FilterChain object.
The doFilter method of the Filter interface takes a FilterChain object as one of its arguments. When you
call the doFilter method of that object, the next associated filter is invoked. If no other filter is associated
with the servlet or JSP page, then the servlet or page itself is invoked.
Register the filter with the appropriate servlets and JSP pages.
Use the filter and filter-mapping elements in the deployment descriptor (web.xml).
Disable the invoker servlet.
Prevent users from bypassing filter settings by using default servlet URLs.
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
Example# Filter 1
Output View
Coding View of F11.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class F11 extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException,IOException{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<h1>Welcome, calling servlet successful</h1>");
}
}
Coding View of ResponseFilterExample.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ResponseFilterExample implements Filter{
private FilterConfig config = null;
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterchain)throws IOException, ServletException{
filterchain.doFilter(request, response);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<b>Filter Received Your Message Successfully:</b>" +
config.getInitParameter("response"));
}
public void destroy() { }
public void init(FilterConfig config) {
this.config = config;
}
}
Coding View of Web.XML
<servlet>
<servlet-name>F11</servlet-name>
<servlet-class>F11</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>F11</servlet-name>
<url-pattern>/F11</url-pattern>
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
</servlet-mapping>
<filter>
<filter-name>ResponseFilterExample</filter-name>
<filter-class>ResponseFilterExample</filter-class>
<init-param>
<param-name>response</param-name>
<param-value>Hello Response Filter Example!</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>ResponseFilterExample</filter-name>
<url-pattern>/F11</url-pattern>
</filter-mapping>
Example# Filter2
Output View
Coding View of IPFilterExample.java
import
import
import
import
import
java.io.*;
java.util.*;
javax.servlet.*;
java.io.IOException;
java.util.StringTokenizer;
import
import
import
import
import
import
import
javax.servlet.Filter;
javax.servlet.FilterChain;
javax.servlet.FilterConfig;
javax.servlet.ServletException;
javax.servlet.ServletRequest;
javax.servlet.ServletResponse;
javax.servlet.http.HttpServletResponse;
public class IPFilterExample implements Filter{
public IPFilterExample() {}
public final static String IP = "193.168.10.146";
private FilterConfig filterConfig;
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterchain) throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><head><title>IP Filter Example</title></head>");
String userip = request.getRemoteAddr();
String Ht="";
HttpServletResponse httpResponse = null;
if (response instanceof HttpServletResponse){
httpResponse = (HttpServletResponse) response;
}
if (IP.equals(userip)) {
out.println("you are not allowed");
} else {
filterchain.doFilter(request, response);
Ht="Passed successfully from IP Filter";
out.println(Ht);
}
}
public void destroy() {}
public void init(FilterConfig config) throws ServletException{
this.filterConfig = config;
}
}
Coding View of CallIpFilter.jsp
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class CallIpFilter extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException,IOException{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<html>");
pw.println("<head><title>IP Filter Example</title></title>");
pw.println("<body>");
pw.println("<h1>Welcome, calling servlet successful</h1>");
pw.println("</body></html>");
}
}
Coding View of web.xml
<filter>
<filter-name>IPFilterExample</filter-name>
<filter-class>IPFilterExample</filter-class>
</filter>
<filter-mapping>
<filter-name>IPFilterExample</filter-name>
<url-pattern>/CallIpFilter</url-pattern>
</filter-mapping>
<servlet>
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
<servlet-name>CallIpFilter</servlet-name>
<servlet-class>CallIpFilter</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CallIpFilter</servlet-name>
<url-pattern>/CallIpFilter</url-pattern>
</servlet-mapping>
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
Listeners
Servlet context listeners. These listeners are notified when the servlet context (i.e., the Web
application) is initialized and destroyed.
Servlet context attribute listeners. These listeners are notified when attributes are added to, removed
from, or replaced in the servlet context.
Session listeners. These listeners are notified when session objects are created, invalidated, or timed
out.
Session attribute listeners. These listeners are notified when attributes are added to, removed from, or
replaced in any session.
Session migration listeners. These listeners are notified when the session objects are serialized and
deserialized by the container. Usually, the serialization and deserialization of session objects occurs when
the container migrates the session objects from one machine to another.
Session object binding listeners. These listeners are notified when the implementing object is added or
removed from the session object.
Request listeners. These listeners are notified when request objects are initialized and destroyed.
Using these listeners involves six basic steps. We'll give a general outline here, then provide listenerspecific details in the following sections.
1. Implement the appropriate interface. Use ServletContextListener, ServletContextAttributeListener,
HttpSessionListener,
HttpSessionAttributeListener,
HttpSessionActivationListener,
HttpSessionBindingListener,
ServletRequestListener,
or
ServletRequestAttributeListener.
The
interfaces without the Http prefix in their name reside in the javax.servlet package and the interfaces
with the Http prefix reside in the javax.servlet.http package.
2. Implement the methods needed to respond to the events of interest. Provide empty bodies for the
other methods in the interface. For example, the ServletContextListener interface defines two
methods: contextInitialized (the Web application was just loaded and the servlet context was
initialized) and contextDestroyed (the Web application is being shut down and the servlet context is
about to be destroyed). If you wanted to define an application-wide servlet context entry, you could
provide a real implementation for contextInitialized and an empty body for contextDestroyed.
3. Obtain access to the important Web application objects. There are nine important objects that you are
likely to use in your event-handling methods: the servlet context, the name of the servlet context
attribute that changed, the value of the servlet context attribute that changed, the session object, the
name of the session attribute that changed, the value of the session attribute that changed, the
request object, the name of the request attribute that changed, and the value of the request attribute
that changed.
4. Use these objects. This process is application specific, but there are some common themes. For
example, with the servlet context, you are most likely to read initialization parameters
(getInitParameter), store data for later access (setAttribute), and read previously stored data
(getAttribute).
5. Declare the listener. You do this with the listener and listener-class elements of the general Web
application deployment descriptor (web.xml) or of a TLD file.
6. Provide any needed initialization parameters. Servlet context listeners commonly read context
initialization parameters to use as the basis of data that is made available to all servlets and JSP
pages. You use the context-param web.xml element to provide the names and values of these
initialization parameters.
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
Note, however, that the ServletRequestListener and the ServletRequestAttributeListener are new additions
to version 2.4 of the servlet specification. If your Web application needs to support servers compliant only
with version 2.3, you cannot use the aforementioned listeners.
Core Warning
ServletRequestListener and ServletRequestAttribute-Listener fail in servers that are
compliant only with version 2.3 of the servlet specification.
6.1. Monitoring Creation and Destruction of the Servlet Context
The ServletContextListener class responds to the initialization and destruction of the servlet context.
These events correspond to the creation and shutdown of the Web application itself. The
ServletContextListener is most commonly used to set up application-wide resources like database
connection pools and to read the initial values of application-wide data that will be used by multiple
servlets and JSP pages. Using the listener involves the following six steps.
1. Implement the ServletContextListener interface. This interface is in the javax.servlet package.
2. Implement contextInitialized and contextDestroyed. The first of these (contextInitialized) is triggered
when the Web application is first loaded and the servlet context is created. The two most common
tasks performed by this method are creating application-wide data (often by reading context
initialization parameters) and storing that data in an easily accessible location (often in attributes of
the servlet context). The second method (contextDestroyed) is triggered when the Web application is
being shut down and the servlet context is about to be destroyed. The most common task performed
by this method is the releasing of resources. For example, contextDestroyed can be used to close
database connections associated with a now-obsolete connection pool. However, because the servlet
context will be destroyed (and garbage collected if the server itself continues to execute), there is no
need to use contextDestroyed to remove normal objects from servlet context attributes.
3. Obtain a reference to the servlet context. The contextInitialized and contextDestroyed methods each
take a ServletContextEvent as an argument. The ServletContextEvent class has a getServletContext
method that returns the servlet context.
4. Use the servlet context. You read initialization parameters with getInitParameter, store data with
setAttribute, and make log file entries with log.
5. Declare the listener. Use the listener and listener-class elements to simply list the fully qualified name
of the listener class, as shown here:
<listener>
<listener-class>somePackage.SomeListener</listener-class>
</listener>
For now, assume that this declaration goes in the web.xml file. However, keep in mind that if you
package listeners with tag libraries, you can use the identical declaration within the TLD file of the tag
library. This technique is discussed in Section 6.5 (Packaging Listeners with Tag Libraries).
6. Provide any needed initialization parameters. Once you have a reference to the servlet context (see
Step 3), you can use the getInitParameter method to read context initialization parameters as the
basis of data that will be made available to all servlets and JSP pages. You use the context-param
web.xml element to provide the names and values of these initialization parameters, as follows:
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
<context-param>
<param-name>name</param-name>
<param-value>value</param-value>
</context-param>
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
What is Request Dispatcher?
Request dispatcher is used to transfer the value attributes to servlets and jsps.
RequestDispatcher is used to connect to another webresource with in the same context.
RequestDispatcher is an interface,In a web application having multiple webcomponents to handle a
single request at time we go for RequestDispatcher.
When you want send your request to another servlet/jsp from your servlet, we can use
RequestDispatcher.
There are two ways to get reference of RequestDispatcher.
1. If you get requestdispatcher reference from ServletContext, you have to specify the absolute url as
argument in getRequestDispatcher method like below.
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher("/my_other_app/servlet/SomeServlet");
dispatcher.forward(request, response);
2. If you get requestdispatcher reference from ServletRequeset, you have to specify the relative url as
argument in getRequestDispatcher method like below.
RequestDispatcher dispatcher = request.getRequestDispatcher("SomeServlet");
dispatcher.forward(request, response);
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
JSTL
The difference between javabean and java custom tags was that, though both made use of java
classes, tags can be used by non-programmers also without knowledge of Java programming, just as
they would use html tags
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
What is new in Servlet 3.0?
Web framework pluggability
Servlet API is the building block of the Java web applications. Almost all the java web application
frameworks build on top of the Servlet API. Examples are Spring MVC, Struts, Struts 2, Stripes, and Rife
etc. In order to hook this frameworks into your web application, you either declare a filter or a servlet into
your web application and map URL patterns to that servlet/filter. There was no way that you can just put
the jar file into web application lib directory and ready to go.
Annotations
With servlet 3.0, web.xml deployment descriptor is totally optional. Servlets, Filters, Listeners, Init
parameters can be defined using annotations. Deployment descriptor can be used to override the
configuration. For example, you can define a servlet using @WebServlet annotation and put into WEBINF/classes directory. The servlet does not need to be defined into web.xml, at run time container will
process classes in WEB-INF/classes and lib directory and identify it based on the annotation.
@WebServlet
This annotation is used to define a Servlet component in a web application and defines the metadata
about the servlet being declared. Read this tutorial on how to define servlet using @webServlet annotation
Classes annotated with @WebServlet annotation must extend javax.servlet.http.HttpServlet class.
Example
@WebServlet(asyncSupported = true, name = "asyncServlet", urlPatterns = { "/async" })
public class AsyncServletExample extends HttpServlet {
@WebFilter
This
annotation
is
used
to
define
a
filter
in
web
application.
The classes annotated with @WebFilter annotation must implement javax.servlet.Filter interface.
Example
@WebFilter(filterName="samplefilter", urlPatterns={"/foo/*", "/bar"})
public class SampleFilter implements Filter {
@WebInitParam
This annotation is used to specify any init parameters that must be passed to the Servlet or the Filter.
Example
@WebInitParam(name="param1", value="foo")
@WebListner
This annotation is used to define a listener. Any type of listener like ServletContexListner,
ServletRequestListner or HttpSessionListner classes can be defined using this annotation.
Example
@WebListener()
public class SampleContextListner extends ServletContextListner {
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
@MultipartConfig
Servlet 3.0 specification comes with the built in file upload support. This annotation, when specified on a
Servlet, indicates that the request it expects is of type mime/multipart. The HttpServletRequest object of
the corresponding servlet makes available the mime attachments via the getParts and getPart methods to
iterate over the various mime attachments.
The @MultipartConfig annotation can be used to specify the location where the files can be stored,
maximum size of the file being uploaded, maximum request size and the size threshold after which the file
will be written to the disk.
There is any equivalent <multipart-config> element in web.xml that can be used for the same purpose.
File upload
Up to now Servlet API did not provide any built in support for handling file upload. we used various open
source libraries like Commons file upload and COS multipart parser. However supporting file upload is so
common requirement for any web application that Servlet 3.0 Specification supports it out of the box. Web
container itself can parse the multipart request and make mime attachments available through
HttpServletRequest object.
Two new methods have been introduced to HttpServletRequest interface
public Collection<Part> getParts()
public Part getPart(String name).
Each part provides access to the headers, content type related with it and also the content via the
getInputStream method.
The HTML form must specify multipart/form-data as encoding type and Servlet should be either annotated
with @MultiPartConfig or configured with element in deployment descriptor.
Modularization of web.xml
The annotations make the web.xml deployment descriptor optional, However web.xml can be used to
override the configuration values defined by the annotations. Currently before Servlet 3.0 specification
web.xml is a big fat file with all the configuration for entire application. However Servlet 3.0 introduces
notion of deployment descriptor fragments. The web.xml can be divided into parts called fragments and
bundled in jar file. The fragments must be located into META-INF directory of the jar file.
A web fragment is a logical partitioning of the web application in such a way that the frameworks being
used within the web application can define all the artifacts without asking developers to edit or add
information in the web.xml. It can include almost all the same elements that the web.xml descriptor uses.
However the top level element for the descriptor MUST be web-fragment and the corresponding descriptor
file MUST be called web-fragment.xml
Asynchronous Servlets and comet support.
Servlet 3.0 makes developing Comet applications very easier. If you don’t know what is comet, read this
Wikipedia article http://en.wikipedia.org/wiki/Comet_%28programming%29 Some time comet is referred
as reverse Ajax also.
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
Servlet 3.0 added new methods into HttpServletRequest class to support the asynchronous request
processing and response generation.
public AsyncContext startAsync(ServletRequest req, ServletResponse res)
This method puts the request into asynchronous mode and initializes it’s AsyncContext with the given
request and response objects.
It was just the basic introduction of the new features of servlet 3.0 specification. A lot more interesting
stuff is yet to come. Next,in this series, I will write tutorials on each of the new features mentioned above.
Ease of Development
Ease of development is one of the key success mantras of any technology. The Servlet 3.0 API focuses on
ease of development by making use of JSR 175 annotations to enable declarative-style programming. This
means that you can swiftly develop a servlet or a filter class by simply annotating the class with
appropriate annotations like @Servlet or @ServletFilter. Annotations not only make the coding of servlet,
filter, and listener classes easier, but also make deployment descriptors optional for a web application,
even though the application archive may have servlet, filter, or context listener classes. The web container
is responsible for processing the annotations located in classes in the WEB-INF/classes directory, in a .jar
file located in the WEB-INF/lib directory, or in classes found elsewhere in the application's classpath.
Annotations Vs. Deployment Descriptor
It is interesting to note that the deployment descriptor takes precedence over annotations. In other
words, the deployment descriptor overrides configuration information specified through the annotation
mechanism. Version 3.0 of the web deployment descriptor contains a new attribute called metadatacomplete on the web-app element. This attribute defines whether the web descriptor is complete, or
whether the class files of the web application should be examined for annotations that specify deployment
information. If the attribute is set to true, the deployment tool must ignore any servlet annotations
present in the class files and use only the configuration details mentioned in the descriptor. Otherwise, if
the value is not specified or set to false, the container must scan all class files of the application for
annotations. This provides a way to enable or disable scanning of the annotation and its processing during
the startup of the application.
All annotations introduced in Servlet 3.0 can be found under the packages javax.servlet.http.annotation
and javax.servlet.http.annotation.jaxrs. The following section explains the complete set of annotations in
Servlet 3.0 :
@Servlet:
javax.servlet.http.annotation.Servlet is a class-level annotation that affirms the annotated class as a
servlet and holds metadata about the declared servlet. The urlMappings attribute is a mandatory attribute
of @Servlet that specifies the URL pattern that invokes this servlet. When a request arrives, the container
matches the URL in the request with the servlet's urlMappings and if the URL pattern matches, the
corresponding servlet will be invoked to serve the request. All other attributes of this annotation are
optional, with reasonable defaults. There must be a method annotated with any one of the HttpMethod
annotations like GET, PUT, POST, HEAD, or DELETE in the servlet class. These methods should take the
HttpServletRequest and HttpServletResponse as method parameters. Version 3.0 servlets can be
implemented as Plain Old Java Objects (POJOs) as opposed to previous versions; i.e., servlets no longer
have to extend any of the basic servlet implementation classes like HTTPServlet or GenericServlet.
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
For comparison, a code snippet for writing a Java servlet using the old Servlet 2.5 API is shown below. In
Servlet 2.5, the web container will initialize the servlet only if you configure the details of the servlet in
the deployment descriptor.
public class MyServlet extends HttpServlet {
public void doGet (HttpServletRequest req,
HttpServletResponse res) {
....
}
}
Deployment descriptor (web.xml)
<web-app>
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>samples.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/MyApp</url-pattern>
</servlet-mapping>
...
</web-app>
Here is the much simplified version written to the Servlet 3.0 API. As MyServlet is annotated as a servlet
using the @Servlet annotation, it gets initialized during the startup of the web container. Note that the
deployment descriptor is optional in this case.
@Servlet(urlMappings={"/MyApp"})
public class MyServlet {
@GET
public void handleGet(HttpServletRequest req,
HttpServletResponse res) {
....
}
}
@ServletFilter and @FilterMapping:
You
can
easily
create
a
servlet
filter
by
annotating
the
filter
class
with
the
javax.servlet.http.annotation.ServletFilter annotation. This annotation encloses metadata about the filter
being declared. It is also mandatory to have the @FilterMapping annotation on the filter class. The
@FilterMapping annotation defines the URL pattern for the filter. All other attributes of @ServletFilter are
optional, with reasonable defaults. The v3.0 filter classes will now look as POJO classes and there will be
no Filter interface or no-argument public constructor required for these classes. Given below is the code
snippet of a filter class using the Servlet v2.5 API:
public class MyFilter implements Filter {
public void doFilter(ServletRequest req,
ServletResponse res,
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
FilterChain chain)
throws IOException, ServletException {
......
}
}
Deployment descriptor (web.xml)
<web-app>
<filter>
<filter-name>My Filter</filter-name>
<filter-class>samples.MyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>My Filter</filter-name>
<url-pattern>/foo</url-pattern>
</filter-mapping>
...
</web-app>
A sample filter class written using Servlet 3.0 is shown below. The container marks MyFilter as a filter
class, as it is annotated with ServletFilter. MyFilter intercepts all incoming requests whose URL matches
the pattern /foo. Servlet 3.0 makes the deployment descriptor optional for filter configurations.
@ServletFilter
@FilterMapping("/foo")
public class MyFilter {
public void doFilter(HttpServletRequest req,
HttpServletResponse res) {
.....
}
}
@InitParam:
This annotation can be used to define any initialization parameters that must be passed to the servlet or
filter classes. It is an attribute of the @Servlet and @ServletFilter annotation. The following code sample
explains how to pass an initialization parameter named lang, having the value english, to a servlet class.
@Servlet(urlMappings={"/MyApp"}, initParams ={@InitParam(name="lang", value="english")})
public class MyServlet {
@GET
public void handleGet(HttpServletRequest req,
HttpServletResponse res) {
....
}
}
@ServletContextListener:
The javax.servlet.http.annotation.ServletContextListener annotation declares the class as a servlet context
listener. The context listener receives notifications when the web container creates or destroys the
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
ServletContext. The context listener will be a POJO class, and does not have to implement the
ServletContextListener interface. A listener class written using the Servlet 2.5 API is shown below. The
container will recognize the listener class if and only if you configure its details in deployment descriptor.
public class MyListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent sce) {
}
.....
}
Deployment Descriptor (web.xml)
<web-app>
<listener>
<listener-class>samples.MyListener</listener-class>
</listener>
....
</web-app>
A much simplified listener class using the Servlet 3.0 API is shown below.
@ServletContextListener
public class MyListener {
public void contextInitialized (ServletContextEvent sce) {
}
.....
}
Deployment Descriptor (web.xml)
Pluggability and Extensibility
Nowadays, web frameworks such as Struts, JSF, and Spring are becoming widely accepted and
established techniques for building web applications. Integrating these frameworks into a web application
is not so easy, as it involves assimilating different pieces together and then editing a single descriptor file
that describes how all of these pieces fit together. Most of these frameworks mandate that you configure
the details of the framework like servlet classes (typically a Controller Servlet), filter classes, or listener
classes in your application's deployment descriptor file. The main reason for this configuration requisite is
that today's web applications support only a single monolithic deployment descriptor wherein we define all
deployment information. When the size of the application increases, the dependency on external
frameworks may also increase, resulting in complex deployment descriptor files. As you probably know,
maintenance of complex descriptors is always a hassle.
In order to resolve these issues, one of Servlet 3.0's most significant concepts is the idea of web
fragments or modular web.xml. The web fragment is a logical partitioning of a web application into
elements like servlet, servlet-mapping, servlet-filter, filter-mapping, servlet-listener, and their child
elements. The framework developers can leverage this feature to define their own web fragments that
reside within the framework, and developers can plug in more and more frameworks by just including the
library files in the application's classpath, without modifying the existing deployment descriptor. In short,
this feature is aimed at having zero configuration when working with frameworks or libraries.
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
The deployment descriptor has been changed to include a new element called <web-fragment>, which
holds the details of a web fragment. If the fragment is packaged as a .jar file and has metadata
information in the form of a deployment descriptor, then the web.xml file must be included under the
META-INF directory of the .jar file. At deployment time, the container scans the application's classpath and
discovers all web fragments and processes them. The metadata-complete flag discussed earlier controls
the scanning of web fragments during the startup of the application. A sample web fragment is shown
below:
<web-fragment>
<servlet>
<servlet-name>myservlet</servlet-name>
<servlet-class>samples.MyServlet</servlet-class>
</servlet>
<listener>
<listener-class>samples.MyListener</listener-class>
</listener>
</web-fragment>
To provide enhanced pluggability, Servlet 3.0 provides much-needed support for the programmatic
addition of servlets and filter classes with the help of new APIs added to ServletContext. These new APIs
allows you to declare servlets, filter classes, and their URL mappings programmatically. These classes get
initialized during application startup time or runtime. Most importantly, you can call these APIs only from
the contextInitialized method of ServletContext. Refer to the Servlet 3.0 API docs for more details of these
APIs. A code sample for programmatically adding a servlet and a filter class is shown below:
@ServletContextListener
public class MyListener {
public void contextInitialized (ServletContextEvent sce) {
ServletContext sc = sce.getServletContext();
//Declare servlet and servlet mapping
sc.addServlet("myServlet", "Sample servlet", "samples.MyServlet", null, -1);
sc.addServletMapping("myServlet", new String[] {"/urlpattern/*"});
//Declare filter and filter mapping
sc.addFilter("myFilter", "Sample Filter", " samples.MyFilter", null);
sc.addFilterMapping("myFilter", new String[] {"/urlpattern/*"}, "myServlet",
DispatcherType.REQUEST, false);
}
}
Asynchronous Support
All of us have probably had deal with slow-serving servlets, particularly servlets that have to wait for a
response from a web service, a JDBC connection, a JMS message, and so on. In the current scenario, the
servlet has to wait for all long-running processes to complete before generating the response, resulting in
inefficient blocking operations that consume a thread or other limited resources of the container. Another
adverse effect is that in case of a JDBC connection, for example, the database may have many blocking
threads waiting for access. This kind of a scenario will ultimately lead to thread starvation and poor quality
of service for the entire web container.
In order to overcome the above-mentioned shortcomings, Servlet 3.0 adds support for suspending and
resuming request processing, which enables the servlet to service a request in an asynchronous, non-
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
blocking fashion (this is the Comet style of programming). When a request is suspended, the thread
handling the request will return to the container without generating any response and gets ready to
perform other tasks. The resume method on the request resumes the request processing. Whenever the
requested resource becomes available, the thread handling that event resumes the suspended request
and proceeds to generate the response. Listed below are some of the capabilities of asynchronous
servlets:
 The ability to receive data from a client without blocking even if the data is slow arriving (nonblocking input).
 The ability to send data to a client without blocking, even if the client or network is slow (nonblocking output).
 The ability to handle delayed requests. Delayed request handling is useful if a remote/slow
resource must be obtained before servicing the request or if access to a specific resource needs to
be throttled to prevent too many simultaneous accesses.
 The ability to handle delayed response close; i.e., the response will be held open to allow additional
data to be sent when asynchronous events occur.
 The ability to notify blocking or non-blocking events.
A set of new APIs are added to ServletRequest and ServletResponse for suspending, resuming, and
querying for the status of the request and enabling disabling and querying the status of the response. The
notification events for the resume, suspend, and complete methods of request are available for developers
through the requestSuspended(), requestResumed() and requestCompleted() methods, respectively. Refer
to the Servlet 3.0 API for detailed information about these methods. The sequence of events involved in
fetching data from a remote web service using asynchronous servlets is illustrated in Figure 1.
Figure 1. Request handling using an asynchronous servlet
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
Security
This topic is not included in the early draft of the 3.0 specification, as it is still undergoing discussions
within the expert group. However, the proposal recommends providing the ability to log in and log out
programmatically. New APIs will be added to HTTPServletRequest to enable this. The login method of
HTTPServletRequest will allow the application or framework to force a container-mediated authentication.
The logout method of HTTPServletRequest and HTTPSession allows an application to reset the
authentication state of the request.
Other Miscellaneous Changes
Listed below are some of the enhancements made to the existing APIs for easy data retrieval and better
developer experience.
HttpOnly Cookies: The Servlet 3.0 specification allows cookies to be marked as HttpOnly cookies.
HttpOnly cookies are not exposed to client-side scripting code, thereby preventing certain kinds of crosssite scripting attacks. Most modern browsers support this feature. Listed below are the methods added to
the Cookie class to support HTTPOnly cookies:
void setHttpOnly(boolean isHttpOnly)
boolean isHttpOnly()
API changes: The following new convenience methods are added to ServletRequest to easily get
ServletResponse and ServletContext instances associated with a request object.
ServletResponse getServletResponse()
ServletContext getServletContext()
The Roadmap
The early draft review of the 3.0 specification was completed in June 2008. As Servlet 3.0 is targeted for
the Java EE 6 platform and higher, the proposed final release of the specification is also aligned with the
release of Java EE 6. However, the early bits of the specification will be made available through
GlassFish, which is the reference implementation for Java EE. The reference implementation of Servlet
3.0 is expected to be integrated into version 3 of GlassFish.
There are changes happening around the review draft of JSR, and new proposals are coming into the
picture to address suggestions and feedback from the community. The key changes in the new proposal
are listed below:
 @Servlet is renamed to @WebServlet and @ServletContextListener to @WebServletContextListener
.
 The new proposal suggests that @WebServlet must extend the HTTPServlet class. Therefore,
servlet classes might not be POJO classes, as described earlier.
 Similarly, the @ServletFilter class and @WebServletContextListener classes need to implement the
Filter and ServletContextListener interfaces, respectively.
 Providing an option for enabling and disabling a Servlet.
See the updated proposal provided in the Resources section of this article for more details. Also note that
these new features are subject to change, depending upon the final approval of this proposal.
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
Struts
Apache Struts is a free open-source framework for creating Java web applications.
Web applications differ from conventional websites in that web applications can create a dynamic
response. Many websites deliver only static pages. A web application can interact with databases and
business logic engines to customize a response.
Web applications based on JavaServer Pages sometimes commingle database code, page
design code, and control flow code. In practice, we find that unless these concerns are
separated, larger applications become difficult to maintain.
One way to separate concerns in a software application is to use a Model-View-Controller (MVC)
architecture. The Model represents the business or database code, the View represents the page design
code, and the Controller represents the navigational code. The Struts framework is designed to help
developers create web applications that utilize a MVC architecture.
The framework provides three key components:
A "request" handler provided by the application developer that is mapped to a standard URI.
A "response" handler that transfers control to another resource which completes the response.
A tag library that helps developers create interactive form-based applications with server pages.
What is Model-View-Controller (MVC) Architecture?
Model-View-Controller architecture is all about dividing application components into three different
categories Model, View and the Controller.
Components of the MVC architecture has unique responsibility and each component is independent of the
other component. Changes in one component will have no or less impact on other component.
Responsibilities of the components are: - Model: Model is responsible for providing the data from the database and saving the data into the data
store. All the business logic are implemented in the Model. Data entered by the user through View are
check in the model before saving into the database. Data access, Data validation and the data saving logic
are part of Model.
- View: View represents the user view of the application and is responsible for taking the input from the
user, dispatching the request to the controller and then receiving response from the controller and
displaying the result to the user. HTML, JSPs, Custom Tag Libraries and Resources files are the part of
view component.
- Controller: Controller is intermediary between Model and View. Controller is responsible for receiving
the request from client. Once request is received from client it executes the appropriate business logic
from the Model and then produce the output to the user using the View component. ActionServlet, Action,
ActionForm and struts-config.xml are the part of Controller.
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
--
MVC Architecture
The main aim of the MVC architecture is to separate the business logic and application data from the
presentation data to the user.
Here are the reasons why we should use the MVC design pattern.
1. They are resuable : When the problems recurs, there is no need to invent a new solution, we just
have to follow the pattern and adapt it as necessary.
2. They are expressive: By using the MVC design pattern our application becomes more expressive.
1). Model: The model object knows about all the data that need to be displayed. It is model who is aware
about all the operations that can be applied to transform that object. It only represents the data of an
application. The model represents enterprise data and the business rules that govern access to and
updates of this data. Model is not aware about the presentation data and how that data will be displayed
to the browser.
2). View : The view represents the presentation of the application. The view object refers to the model. It
uses the query methods of the model to obtain the contents and renders it. The view is not dependent on
the application logic. It remains same if there is any modification in the business logic. In other words, we
can say that it is the responsibility of the of the view's to maintain the consistency in its presentation
when the model changes.
3). Controller: Whenever the user sends a request for something then it always go through the
controller. The controller is responsible for intercepting the requests from view and passes it to the model
for the appropriate action. After the action has been taken on the data, the controller is responsible for
directing the appropriate view to the user. In GUIs, the views and the controllers often work very closely
together.
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
Overview of the Struts Framework
The Struts framework is composed of approximately 300 classes and interfaces which are
organized in about 12 top level packages.
Along with the utility and helper classes framework also provides the classes and interfaces for working
with controller and presentation by the help of the custom tag libraries.
It is entirely on to us which model we want to choose. The view of the Struts architecture is given below:
The Struts Controller Components
Whenever a user request for something, then the request is handled by the Struts Action
Servlet.
When the ActionServlet receives the request, it intercepts the URL and based on the Struts
Configuration files, it gives the handling of the request to the Action class. Action class is a
part of the controller and is responsible for communicating with the model layer.
The Struts View Components
The view components are responsible for presenting information to the users and accepting
the input from them. They are responsible for displaying the information provided by the
model components.
Mostly we use the Java Server Pages (JSP) for the view presentation. To extend the
capability of the view we can use the Custom tags, java script etc.
The Struts model component
The model components provides a model of the business logic behind a Struts program.
It provides interfaces to databases or back- ends systems. Model components are generally
a java class. There is not any such defined format for a Model component, so it is possible
for us to reuse Javacode which are written for other projects. We should choose the model
according to our client requirement.
How Struts Works
The basic purpose of the Java Servlets in struts is to handle requests made by the client or by web
browsers. In struts JavaServerPages (JSP) are used to design the dynamic web pages. In struts, servlets
helps to route request which has been made by the web browsers to the appropriate ServerPage. The use
of servlet as a router helps to make the web applications easier to design, create, and maintain. Struts is
purely based on the Model- View- Contoller (MVC) design pattern. It is one of the best and most well
developed design patterns in use. By using the MVC architecture we break the processing in three sections
named Model, the View, and the Controller. Below we are describing the working of struts.
1. As we all are well aware of the fact that each application we develop has a deployment descriptor
i.e. WEB-INF/web.xml. This is the file which the container reads. This file has all the
configuration information which we have defined for our web application. The configuration
information includes the index file, the default welcome page, the mapping of our servlets including
path and the extension name, any init parameters, information related to the context elements.
In the file WEB-INF/web.xml of struts application we need to configure the Struts ActionServlet
which handles all the request made by the web browsers to a given mapping. ActionServlet is the
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
central component of the Struts controller. This servlet extends the HttpServlet. This servlet
basically performs two important things. First is : When the container gets start, it reads the
Struts Configuration files and loads it into memory in the init() method. You will know more about
the Struts Configuration files below. Second point is: It intercepts the HTTP request in the
doGet() and doPost() method and handles it appropriately.
2. In struts application we have another xml file which is a Struts configuration file named as
struts.config.xml. The name of this file can be changed. The name of the struts configuration file
can be configured in the web.xml file. This file is placed under the WEB-INF directory of the web
application. It is an XML document that describes all or part of Struts application. This file has all
the information about many types of Struts resources and configures their interaction. This file is
used to associate paths with the controller components of your application., known as Action
classes like <action path ="/login" type = "LoginAction">. This tag tells the Struts
ActionServlet that whenever the incoming request is http://myhost/myapp/login.do, then it
must invoke the controller component LoginAction. Above, you can see that we have written .do
in the URL. This mapping is done to tell the web application that whenever a request is received
with
the
.do
extension
then
it
should
be
appended
to
the
URL.
3. For each action we also have to configure Struts with the names of the resulting pages that will be
shown as a result of that action. In our application there can be more than one view which depends
on the result of an action. One can be for a success and the other for the failure. If the result
action is "success" then the action tells the ActionServlet that the action has been successfully
accomplished or vice- versa. The struts knows how to forward the specific page to the concerned
destination. The model which we want to use is entirely to you, the model is called from within the
controller components.
4. Action can also get associate with a JavaBean in our Struts configuration file. Java bean is nothing
but a class having getter and setter methods that can be used to communicate between the view
and the controller layer. These java beans are validated by invoking the validate() method on the
ActionForm by the help of the Struts system. The client sends the request by the normal form
submission by using Get or Post method, and the Struts system updates that data in the Bean
before calling the controller components.
5. The view we use in the struts can be either Jsp page, Velocity templates, XSLT pages etc. In struts
there are set of JSP tags which has been bundled with the struts distribution, but it is not
mandatory to use only Jsp tags, even plain HTML files can be used within our Struts application but
the disadvantage of using the html is that it can't take the full advantage of all the dynamic
features provided in the struts framework.
The framework includes a set of custom tag libraries that facilitate in creating the user interfaces
that can interact gracefully with ActionForm beans. The struts Jsp taglibs has a number of generic
and struts specific tags tags which helps you to use dynamic data in your view. These tags helps us
to interact with your controller without writing much java code inside your jsp. These tags are used
create forms, internally forward to other pages by interacting with the bean and helps us to invoke
other actions of the web application.
There are many tags provided to you in the struts frameworks which helps you in sending error
messages, internationalization etc.
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
Note: The points we have described above will be in effect if and only if when the ActionServlet is handling
the request. When the request is submitted to the container which call the ActionServlet, make sure that
the extension of the file which we want to access should have the extension .do.
Struts working:
Process flow:
web.xml : Whenever the container gets start up the first work it does is to check the web.xml file and
determine what struts action Servlets exist. The container is responsible for mapping all the file request to
the correct action Servlet.
A Request : This is the second step performed by the container after checking the web.xml file. In this
the user submits a form within a browser and the request is intercepted by the controller.
The Controller : This is the heart of the container. Most Struts application will have only one controller
that is ActionServlet which is responsible for directing several Actions. The controller determines what
action is required and sends the information to be processed by an action Bean. The key advantage of
having a controller is its ability to control the flow of logic through the highly controlled, centralized
points.
www.shyamsir.com ,9374928879 , [email protected]
Aspiration- Beyond Expectation- 9374928879
struts.config.xml : Struts has a configuration file to store mappings of actions. By using this file there is
no need to hard code the module which will be called within a component. The one more responsibility of
the controller is to check the struts.config.xml file to determine which module to be called upon an action
request. Struts only reads the struts.config.xml file upon start up.
Model : The model is basically a business logic part which takes the response from the user and stores
the result for the duration of the process. This is a great place to perform the preprocessing of the data
received from request. It is possible to reuse the same model for many page requests. Struts provides the
ActionForm and the Action classes which can be extended to create the model objects.
View : The view in struts framework is mainly a jsp page which is responsible for producing the output to
the user.
Struts tag libraries : These are struts components helps us to integrate the struts framework within the
project's logic. These struts tag libraries are used within the JSP page. This means that the controller and
the model part can't make use of the tag library but instead use the struts class library for strut process
control.
Property file : It is used to store the messages that an object or page can use. Properties files can be
used to store the titles and other string data. We can create many property files to handle different
languages.
Business objects : It is the place where the rules of the actual project exists. These are the modules
which just regulate the day- to- day site activities.
The Response : This is the output of the View JSP object.
www.shyamsir.com ,9374928879 , [email protected]