java web programming - · pdf filejava web programming requestdispatcher ... chapter 2 - web...
TRANSCRIPT
Java Web Programming
Student Workbook
Page ii Rev 4.1.2 © 2011 ITCourseware, LLC
Java Web Programming
Java Web Programming
Mike Naseef, Jamie Romero, and Rick Sussenbach
Published by ITCourseware, LLC., 7245 South Havana Street, Suite 100, Centennial, CO 80112
Editors: Danielle Hopkins and Jan Waleri
Editorial Assistant: Ginny Jaranowski
Special thanks to: Many instructors whose ideas and careful review have contributed to the qualityof this workbook and the many students who have offered comments, suggestions, criticisms, andinsights.
Copyright © 2011 by ITCourseware, LLC. All rights reserved. No part of this book may be reproducedor utilized in any form or by any means, electronic or mechanical, including photo-copying, recording, or byan information storage retrieval system, without permission in writing from the publisher. Inquiries should beaddressed to ITCourseware, LLC., 7245 South Havana Street, Suite 100, Centennial, Colorado, 80112.(303) 302-5280.
All brand names, product names, trademarks, and registered trademarks are the property of their respectiveowners.
© 2011 ITCourseware, LLC Rev 4.1.2 Page iii
Java Web Programming
Contents
Chapter 1 - Course Introduction ............................................................................................................. 7
Course Objectives ............................................................................................................................ 8Course Overview ........................................................................................................................... 10Using the Workbook ...................................................................................................................... 11Suggested References ..................................................................................................................... 12
Chapter 2 - Web Applications and MVC .............................................................................................. 15
Web Applications ........................................................................................................................... 16JSPs and Servlets ........................................................................................................................... 18Model-View-Controller .................................................................................................................. 20Model 2 Architecture ...................................................................................................................... 22The WAR File ................................................................................................................................ 24web.xml ......................................................................................................................................... 26Building the WAR ........................................................................................................................... 28Deploying the WAR ........................................................................................................................ 30Labs ............................................................................................................................................... 32
Chapter 3 - JavaServer Pages ............................................................................................................... 35
Introduction to JSP ......................................................................................................................... 36JSP Syntax ..................................................................................................................................... 38JSP Scripting Elements .................................................................................................................... 40Request and Response Implicit Objects ........................................................................................... 42page Directive ................................................................................................................................ 44Error Handling ................................................................................................................................ 46The include directive ....................................................................................................................... 48include and forward Actions ............................................................................................................ 50Labs ............................................................................................................................................... 52
Chapter 4 - Java Servlets ..................................................................................................................... 55
HTTP Requests .............................................................................................................................. 56HttpServlet ..................................................................................................................................... 58Servlet Lifecycle ............................................................................................................................. 60@WebServlet Annotation ............................................................................................................... 62
Page iv Rev 4.1.2 © 2011 ITCourseware, LLC
Java Web Programming
RequestDispatcher .......................................................................................................................... 64HttpSession .................................................................................................................................... 66ServletContext ................................................................................................................................ 68Servlet Filters ................................................................................................................................. 70JSP vs. Servlet ................................................................................................................................ 72Labs ............................................................................................................................................... 74
Chapter 5 - JavaBeans ........................................................................................................................ 77
What is a JavaBean? ....................................................................................................................... 78Rules .............................................................................................................................................. 80Properties ....................................................................................................................................... 82Using JavaBeans in JSPs ................................................................................................................. 84Properties and Forms ..................................................................................................................... 86Data Access Objects ...................................................................................................................... 88Resource Reference ........................................................................................................................ 90Bean Scopes in Servlets .................................................................................................................. 92Bean Scopes in JSPs ...................................................................................................................... 94Labs ............................................................................................................................................... 96
Chapter 6 - JSP Expression Language .................................................................................................. 99
JSP Expression Language ............................................................................................................. 100Literals ......................................................................................................................................... 102Variables ...................................................................................................................................... 104The . and [ ] Operators ................................................................................................................. 106Other Operators ........................................................................................................................... 108Implicit Objects ............................................................................................................................ 110Labs ............................................................................................................................................. 112
Chapter 7 - Introduction to JSTL ........................................................................................................ 115
What is JSTL? .............................................................................................................................. 116Core Tags — Conditionals ............................................................................................................ 118Core Tags — Iteration and Import ................................................................................................ 120Variables, Output, and Exceptions ................................................................................................. 122XML Manipulation Tags ............................................................................................................... 124Internationalization Tags ................................................................................................................ 126SQL Tags ..................................................................................................................................... 128Labs ............................................................................................................................................. 130
© 2011 ITCourseware, LLC Rev 4.1.2 Page v
Java Web Programming
Chapter 8 - Security ........................................................................................................................... 133
Concepts ...................................................................................................................................... 134Constraints ................................................................................................................................... 136Roles ............................................................................................................................................ 138login-config ................................................................................................................................... 140BASIC Authentication .................................................................................................................. 142FORM Authentication ................................................................................................................... 144Login and Error Pages .................................................................................................................. 146Labs ............................................................................................................................................. 148
Appendix A - Tag Libraries ................................................................................................................. 151
Custom Tags ................................................................................................................................ 152Using Custom Tags ....................................................................................................................... 154Defining Tags ................................................................................................................................ 156Tags with Attributes ...................................................................................................................... 158Fragments and Variables ............................................................................................................... 160Packaging Tag Files ...................................................................................................................... 162Labs ............................................................................................................................................. 164
Appendix B - Ant ............................................................................................................................... 167
What Is Ant? ................................................................................................................................ 168build.xml ....................................................................................................................................... 170Tasks ........................................................................................................................................... 172Properties and Property Files ........................................................................................................ 174Managing Files and Directories ..................................................................................................... 176Filesets ......................................................................................................................................... 178Java Tasks .................................................................................................................................... 180Creating Java Archives .................................................................................................................. 182Specifying Paths ........................................................................................................................... 184Miscellaneous Tasks ..................................................................................................................... 186
Solutions ............................................................................................................................................ 189
Index .................................................................................................................................................. 251
Page vi Rev 4.1.2 © 2011 ITCourseware, LLC
Java Web Programming
Course Introduction
© 2011 ITCourseware, LLC Rev 4.1.2 Page 7
Chapter 1
Chapter 1 - Course Introduction
Java Web Programming
Page 8 Rev 4.1.2 © 2011 ITCourseware, LLC
Write web applications that combine Java Servlets, JavaServer Pages, andJavaBeans using the Model-View-Controller architecture.
Use JavaBeans to encapsulate business and data access logic.
Generate HTML or XML output with JavaServer Pages.
Process HTTP requests with Java Servlets.
Configure your web applications with the web.xml deployment descriptor.
Create scriptless JSPs by using JSTL tags combined with JSP ExpressionLanguage for functionality, such as conditionals, iteration, internationalization,and XML processing.
Course Objectives
Course Introduction
© 2011 ITCourseware, LLC Rev 4.1.2 Page 9
Chapter 1
Java Web Programming
Page 10 Rev 4.1.2 © 2011 ITCourseware, LLC
Audience: Java programmers who need to develop web applications usingJSPs and Servlets.
Prerequisites: Java programming experience and basic HTML knowledgeare required.
Classroom Environment:
A workstation per student.
Course Overview
Course Introduction
© 2011 ITCourseware, LLC Rev 4.1.2 Page 11
Chapter 1
Using the Workbook
Chapter 2 Servlet Basics
© 2002 ITCourseware, LLC Rev 2.0.0 Page 17
Add an init() method to your Today servlet that initializes a bornOn date, then print the bornOn date
along with the current date:
Today.java
...
public class Today extends GenericServlet {
private Date bornOn;
public void service(ServletRequest request,
ServletResponse response) throws ServletException, IOException
{
...
// Write the document
out.println("This servlet was born on " + bornOn.toString());
out.println("It is now " + today.toString());
}
public void init() {
bornOn = new Date();
}
}
Hands On:
The init() method is
called when the servlet is
loaded into the container.
This workbook design is based on a page-pair, consisting of a Topic page and a Support page. When youlay the workbook open flat, the Topic page is on the left and the Support page is on the right. The Topicpage contains the points to be discussed in class. The Support page has code examples, diagrams, screenshots and additional information. Hands On sections provide opportunities for practical application of keyconcepts. Try It and Investigate sections help direct individual discovery.
In addition, there is an index for quick look-up. Printed lab solutions are in the back of the book as well ason-line if you need a little help.
Java Servlets
Page 16 Rev 2.0.0 © 2002 ITCourseware, LLC
� The servlet container controls the life cycle of the servlet.
� When the first request is received, the container loads the servlet class
and calls the init() method.
� For every request, the container uses a separate thread to call
the service() method.
� When the servlet is unloaded, the container calls the destroy()
method.
� As with Java’s finalize() method, don’t count on this being
called.
� Override one of the init() methods for one-time initializations, instead of
using a constructor.
� The simplest form takes no parameters.
public void init() {...}
� If you need to know container-specific configuration information, use
the other version.
public void init(ServletConfig config) {...
� Whenever you use the ServletConfig approach, always call the
superclass method, which performs additional initializations.
super.init(config);
The Servlet Life Cycle
The Topic page providesthe main topics for
classroom discussion.
The Support page hasadditional information,
examples and suggestions.
Code examples are in afixed font and shaded. Theon-line file name is listedabove the shaded area.
Screen shots showexamples of what youshould see in class.
Topics are organized intofirst ( ), second ( ) and
third ( ) level points.
Pages are numberedsequentially throughout
the book, making lookupeasy.
Callout boxes point outimportant parts of the
example code.
Java Web Programming
Page 12 Rev 4.1.2 © 2011 ITCourseware, LLC
Basham, Bryan, Kathy Sierra, and Bert Bates. 2004. Head First Servlets and JSP: Passing the SunCertified Web Component Developer Exam (SCWCD). O'Reilly & Associates, Sebastopol,CA. ISBN 0596005407.
Bergsten, Hans. 2003. JavaServer Pages, 3rd Edition. O'Reilly & Associates, Sebastopol, CA.ISBN 0596005636.
Hall, Marty and Larry Brown. 2003. Core Servlets and JavaServer Pages, Vol. 1: Core Technologies,2nd Edition. Prentice Hall, Englewood Cliffs, NJ. ISBN 0130092290.
Hall, Marty, Larry Brown and Yaakov Chaikin. 2006. Core Servlets and JavaServer Pages, Volume II(2nd Edition). Prentice Hall, Englewood Cliffs, NJ. ISBN 0131482602.
Heffelfinger, David, 2010. Java EE 6 with GlassFish 3 Application Server. Packt Publishing,Birmingham, UK. ISBN 1849510369
Jendrock, Eric, et.al. 2010. The Java EE 6 Tutorial: Basic Concepts (4th Edition). Prentice Hall,Upper Saddle River, NJ. ISBN 0137081855
Steelman, Andrea, Joel Murach. Bergsten, Hans. 2008. Murach's Java Servlets and JSP, 2nd Edition.Mike Murach & Associates. ISBN 1890774448.
Java Servlet Technology: http://www.oracle.com/technetwork/java/index-jsp-135475.htmlJSP Technology: http://www.oracle.com/technetwork/java/jsp-138432.htmlJSTL Technology: http://www.oracle.com/technetwork/java/jstl-137486.htmlJava EE 6 Tutorial: http://download.oracle.com/javaee/6/tutorial/doc/
Suggested References
Course Introduction
© 2011 ITCourseware, LLC Rev 4.1.2 Page 13
Chapter 1
Java Web Programming
Page 14 Rev 4.1.2 © 2011 ITCourseware, LLC
Chapter 2 Web Applications and MVC
© 2011 ITCourseware, LLC Rev 4.1.2 Page 15
Chapter 2 - Web Applications and MVC
Objectives
Describe Java web technologies.
Explain how the Model-View-Componentarchitecture applies to a web application.
Describe the structure of WAR files.
Build and deploy a web application.
Java Web Programming
Page 16 Rev 4.1.2 © 2011 ITCourseware, LLC
Web applications are applications that the end user can access using a standardweb browser.
The Java Platform Enterprise Edition (Java EE) defines a web application as acollection of web components and supporting files.
Web components include Java servlets and JSP files.
Supporting files include static HTML documents, image files, andsupporting classes.
Your web application runs in the environment of a web container, which ismanaged by an application server.
Web containers can contain several web applications.
Your applications can work together or operate independently.
Each web application is addressed with a context path.
The context path is determined when the application is deployed.
A web container can contain a "default" application, which has an emptycontext path.
To access a component or file in the web application from a browser, youmust include the context path in the request URL.
Web Applications
Chapter 2 Web Applications and MVC
© 2011 ITCourseware, LLC Rev 4.1.2 Page 17
BrowserHTTP
Application Server
Web Container
Web Application
Servlet
JSP
Java Web Programming
Page 18 Rev 4.1.2 © 2011 ITCourseware, LLC
JSPs and Servlets
The standard protocol for communication between browsers and servers isdesigned for static documents.
Typically, a web server returns the contents of a static file in response to abrowser request.
Use servlets and JavaServer Pages (JSP) to handle requests from a browserdynamically.
A servlet is a web component which receives an object encapsulating thebrowser request and constructs a response to the browser.
The response typically contains an HTML document.
JSP pages start as text documents containing HTML or XML with specialtags for executing Java code.
JSP pages are compiled into servlets automatically.
HTML designers do not need to learn Java.
Java developers do not need to learn HTML.
You get some important benefits by using Java's web component architecture:
Your application will be portable across web containers.
You can get better performance and security from servlets than fromstandard CGI.
You can make full use of the vast set of Java APIs.
You can use facilities provided by the web container to maintain state.
Chapter 2 Web Applications and MVC
© 2011 ITCourseware, LLC Rev 4.1.2 Page 19
Java Web Programming
Page 20 Rev 4.1.2 © 2011 ITCourseware, LLC
Model-View-Controller
The Model-View-Controller (MVC) architecture was originally described bySmalltalk for implementing GUI applications.
The primary goal of MVC is to separate user interface code (the view) fromdomain code (the model).
The controller is introduced as a separate body of code that manages thetranslation of events in the view to procedures in the model.
The view only accesses the model to retrieve values for display.
The model should not have any knowledge of the view or the controller.
The benefits of MVC are similar to encapsulation.
Changes in the model can be made without impacting the view.
The view can be modified, or new views can be implemented withoutimpacting the model.
Developers can focus on their skills — database programmers do notneed to understand user interface issues.
MVC adapts well to the needs of web applications.
The view is further separated from the model both architecturally andphysically.
The controller typically takes a broader role, managing the view as well asthe model.
Chapter 2 Web Applications and MVC
© 2011 ITCourseware, LLC Rev 4.1.2 Page 21
View
Controller
Model
Java Web Programming
Page 22 Rev 4.1.2 © 2011 ITCourseware, LLC
Model 2 Architecture
The typical adaptation of MVC to Java web applications is called the Model 2Architecture.
Use JavaBeans to define the model.
The controller should encapsulate business object data in JavaBeans tomake the data accessible to the JSP views.
The controller can provide helper JavaBeans to convert data from thebusiness object to formats appropriate to the view.
For example, a JavaBean could convert a date to an appropriatestring value.
Use a servlet as the controller.
It will extract data needed to handle the request from the browser.
The servlet will also call methods on business objects to process therequest.
Finally, it will forward the request to the JSP page, including any beansneeded to generate the view.
The servlet might choose between JSP pages based on the resultsof the request.
Use JSP pages to generate the view — typically an HTML or XML document.
The view will retrieve information to display from the beans included bythe servlet.
Chapter 2 Web Applications and MVC
© 2011 ITCourseware, LLC Rev 4.1.2 Page 23
ArticleNotFound.jsp ListArticles.jspShowArticle.jsp
In the early days of JSP, the popular architecture was what is now referred to as "Model 1." In thisarchitecture, a browser request is handled directly by a JSP file, which, in turn, creates JavaBeans toaccess the business objects.
In both Model 1 and Model 2 architectures, JavaBeans are the preferred mechanism for accessingbusiness objects. The JSP specification has strong support for working with JavaBeans objects, whichmakes it easier to separate the display logic of the JSP file from the business logic of the application.
The filenames shown in the diagram refer to files in the BlogNews example application.
blognews.ArticleServlet
blognews.Article
Web Container
2
3
View
Model
Controller
1
Browser
JSP
Servlet
JavaBean
Java Web Programming
Page 24 Rev 4.1.2 © 2011 ITCourseware, LLC
You must organize your web application using a specific directory structure.
The application root directory acts as the document root for yourapplication.
You put your JSP, HTML, and other supporting files here.
You can use subdirectories to organize your application.
Store your application files in a subdirectory named WEB-INF.
Place the optional web.xml configuration file here.
This subdirectory is not accessible via the web server.
Put your servlet classes and supporting classes in the WEB-INF/classesdirectory.
Put any JAR files specific to your application in the WEB-INF/libdirectory.
This is the preferred method for storing your JavaBeans.
If a JAR file will be used by other applications, it may make moresense to put it in a system-wide or server-wide directory.
You can package your application for distribution in a Web ARchive (WAR) file.
A WAR file is a JAR file that contains all of the files in your application.
Since WAR files must conform to the Java EE specifications, they areportable between different web containers.
The WAR File
Chapter 2 Web Applications and MVC
© 2011 ITCourseware, LLC Rev 4.1.2 Page 25
Contents of BlogNews.war:
ArticleNotFound.jsp
BadPostArticle.jsp
GenericErrorHandler.jsp
index.html
ListArticles.jsp
NewArticle.html
ShowArticle.jsp
ViewArticle.html
META-INF
MANIFEST.MF
WEB-INF
web.xml
classes
blognews
Article.class
ArticleFactory.class
ArticleNotFoundException.class
ArticleDateComparator.class
ArticleServlet.class
META-INF andMANIFEST.MF are
artifacts created by thejar utility. They have no
effect on the war.
Most container vendorsalso suggest a vendor-specific XML file in the
WEB-INF directory.
Java Web Programming
Page 26 Rev 4.1.2 © 2011 ITCourseware, LLC
web.xml
Provide an optional deployment descriptor to supply additional configurationinformation for your web application.
Create it as WEB-INF/web.xml in your web application directory.
List files the container should look for when the user request specifies a contextwith the <welcome-file-list> element.
Use the <error-page> element to delegate error handling to your own servlets,JSP pages, or HTML files.
This allows you to customize the appearance of your error pagesdynamically.
HTTP errors are mapped by the 3-digit status code.
<error-page><error-code>404</error-code><location>/errors/PageNotFound.jsp</location>
</error-page>
Exceptions are mapped by the full class name of the exception handled.
<error-page><exception-type>java.io.IOException</exception-type><location>/errors/IOException.jsp</location>
</error-page>
The web container looks for a page matching the class of theexception thrown or one of its superclasses.
When the web container invokes your error handler, it provides requestattributes with the error code or exception, and the original request URI.
Use these attributes to customize your error response.
Chapter 2 Web Applications and MVC
© 2011 ITCourseware, LLC Rev 4.1.2 Page 27
The location is specifiedrelative to the webapplication root.
You can use a<description> element
to provide documentation.
Examples/WebContent/WEB-INF/web.xml<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <description> This is the BlogNews application. Setup is straightforward. No changes should be necessary at deployment unless you wish to change the default error page or the welcome file. Articles will be stored in the WEB-INF/articles directory which is created automatically the first time the servlet is accessed. </description>
<welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list>
<error-page> <error-code>404</error-code> <location>/GenericErrorHandler.jsp</location> </error-page></web-app>
Note:Prior to the Servlet 3.0 specification, web.xml was required. Servlet 3.0 defined several annotations thatyou can add to your code to take the place of many, but not all, of the web.xml entries.
Java Web Programming
Page 28 Rev 4.1.2 © 2011 ITCourseware, LLC
Building the WAR
You build your application using these steps:
1. Create a directory in which to build your web application.
mkdir webapp
2. Compile your classes putting the resulting class files in WEB-INF/classes.
javac -d webapp/WEB-INF/classes *.java
If you create any JAR files, put them in WEB-INF/lib.
3. Copy your JSP files, HTML files, and other supporting files into theapplication directory.
4. Optionally, create your deployment descriptor in WEB-INF/web.xml.
To build the WAR file, use the jar command to archive the application directory.
jar cf MyApplication.war webapp
Chapter 2 Web Applications and MVC
© 2011 ITCourseware, LLC Rev 4.1.2 Page 29
To simplify the building and deployment process, we will use the Apache Software Foundation's Ant tool.
To use Ant, you create an XML configuration file called build.xml and define targets that define the stepsfor building and deploying your application. The targets also set dependencies, so that you can compile,build, and deploy with a single command.
For this class, we have provided build.xml files for you with targets for compiling the Java files,building the WAR file, and deploying the WAR file.
To complete all of the steps on the preceding page, you simply need to run the ant command with theappropriate build target. Your instructor will give you the details of how to run Ant and which target to use.
Java Web Programming
Page 30 Rev 4.1.2 © 2011 ITCourseware, LLC
Deploying the WAR
You deploy a web application with these fundamental steps.
1. Pass the WAR file to your web container.
You might simply copy the file to a specific location or use a tool tolocate the file.
2. Specify the context path for the application.
The context path often defaults to the name of the WAR file.
3. Configure any container-managed resources as specified in thedeployment descriptor.
These might include database connections, JNDI services, andsecurity roles.
The mechanisms for performing these is determined by your web container.
Some container providers have GUI or web-based tools for deployingapplications.
You may need to create the appropriate configuration files manually andinclude them in your WAR file.
Chapter 2 Web Applications and MVC
© 2011 ITCourseware, LLC Rev 4.1.2 Page 31
Try It:The BlogNews application is a simple example of a web application using the Model 2 architecture.The application allows you to create and display a list of articles.
The servlet creates a new directory within the WEB-INF directory of the deployed application. The articlesare stored in this new directory as serialized objects. The upside of this implementation is that you do notneed to configure a storage directory or database. The downside is that this directory is usually destroyedwhen the application is redeployed.
The classes in the blognews package represent the controller, the model, and the business logic. TheArticle class is our model JavaBean. The ArticleFactory and supporting classArticleNotFoundException provide the business logic for working with articles. The ArticleServlet isthe controller
Start Tomcat, then build and deploy the application by running the ant command in the chapter's Examplesdirectory. To view the application, navigate with your browser to http://localhost:8080/BlogNews.
Java Web Programming
Page 32 Rev 4.1.2 © 2011 ITCourseware, LLC
Modify the deployment descriptor so that the 405 error (generated when a user tries to usea GET when a POST is required) is handled by the GenericErrorHandler. You cangenerate this error by entering the URL for the View command manually in your browser'saddress bar (http://localhost:8080/BlogNews/Article/View).(Solution: Solutions-Lab1/WebContent/WEB-INF/web.xml)
Modify the servlet so that it throws a runtime exception (try dividing by zero ordereference a null pointer). Deploy the application and observe the error displayed. Now,modify the deployment descriptor so that GenericErrorHandler.jsp is displayed instead.(Solutions: Solutions-Lab2/src/blognews/ArticleServlet.java, Solutions-Lab2/WebContent/WEB-INF/web.xml)
(Optional) Create a new view which lists only the titles of the articles. Add an action to theservlet to display the view, and add a link to index.html in order to access this action .(Solutions: Solutions-Lab3/src/blognews/ArticleServlet.java, Solutions-Lab3/WebContent/ListTitles.jsp, Solutions-Lab3/WebContent/index.html)
(Optional) Create a new view that allows the user to edit the body of an article. You will needto create a form to enter the title of the article to edit and a new action in ArticleServlet todisplay the new view using the article entered in the form. The new view can use the existingPost action in the servlet to save the changes. Add a link to index.html to display the newform.(Solutions: Solutions-Lab4/WebContent/EditArticle.jsp, Solutions-Lab4/WebContent/EditArticle.html, Solutions-Lab4/src/blognews/ArticleServlet.java, Solutions-Lab4/WebContent/index.html)
Labs
Chapter 2 Web Applications and MVC
© 2011 ITCourseware, LLC Rev 4.1.2 Page 33
Java Web Programming
Page 132 Rev 4.1.2 © 2011 ITCourseware, LLC
Chapter 8 Security
© 2011 ITCourseware, LLC Rev 4.1.2 Page 133
Chapter 8 - Security
Objectives
Add authentication and authorization to aweb application.
Use HTTP Basic and Form-based loginmethods.
Create security roles and constraints inweb.xml.
Java Web Programming
Page 134 Rev 4.1.2 © 2011 ITCourseware, LLC
Often, you want to restrict access to your web application to certain users.
Authentication allows you to identify who is trying to run the application.
At a bank, you will be asked to present a picture ID to prove youridentity.
Once you know who the user is, you need to authorize that user; that is,decide if they are allowed access.
Even if you prove your identity, the bank will not let you accessanother person's account.
Another person can tell the bank you should have access to theiraccount.
Web applications need to authenticate a user, and then determine if the user isauthorized to perform a request.
A user often provides a password to authenticate their identity.
The web application can then check requested actions against thoseallowed for the user.
Concepts
Chapter 8 Security
© 2011 ITCourseware, LLC Rev 4.1.2 Page 135
Hands On:A news blog application is provided in the chapter directory. Currently, it has no security restrictions.We will add security features to this application throughout this chapter.
Build and deploy the application using Ant. Navigate with your browser to http://localhost:8080/SecureBlogNews to view the application.
Note:All subsequent HTTP requests will include the username/password (if needed). They are cached forthe given realm.
Browser Application Server
HTTP Request
401 Authentication Required
Access aRestricted
URL
Username/password
OK
Prompt forusername and
password Original HTTP Request + usernameand password
Web Page
Java Web Programming
Page 136 Rev 4.1.2 © 2011 ITCourseware, LLC
Constraints
Add <security-constraint> entries to web.xml to restrict access to portions ofa web application.
Each security constraint entry describes what access is allowed on a set ofresources.
Security constraints must have a <web-resource-collection> sub-element,describing the set of resources covered by the security constraint.
The collection must have a <web-resource-name> sub-elementdescribing the collection.
The collection can have any number of <url-pattern> sub-elementsdescribing URLs to include in the collection.
URL patterns can include wildcard characters.
Security constraints should have an <auth-constraint> sub-element.
Leaving out the <auth-constraint> results in access by everyone.
An empty <auth-constraint> results in access by no one.
Chapter 8 Security
© 2011 ITCourseware, LLC Rev 4.1.2 Page 137
Hands On:Add the following entry to the end of Examples/WebContent/WEB-INF/web.xml:
... </error-page>
<security-constraint> <web-resource-collection> <web-resource-name>The entire app</web-resource-name> <url-pattern>/*</url-pattern> </web-resource-collection> <auth-constraint/> </security-constraint></web-app>
Use Ant to redeploy the application and try it out. Note that all pages of the application are nowrestricted.
Java Web Programming
Page 138 Rev 4.1.2 © 2011 ITCourseware, LLC
Roles
Roles specify who is allowed access to secured resources.
Roles provide finer granularity than "everyone" and "no one."
The <security-role> element specifies which roles are available for use by theweb application.
The <role-name> sub-element defines a role.
Use as many <security-role> elements as needed.
The <auth-constraint> element specifies which roles are allowed access to theresource.
No one has access if no roles are provided.
Specify a role using the <role-name> sub-element.
Provide as many <role-name> sub-elements as needed.
The special role "*" matches all the roles defined by the <security-role>elements in web.xml for this application.
Assignment of users to roles is application-server specific.
Chapter 8 Security
© 2011 ITCourseware, LLC Rev 4.1.2 Page 139
Hands On:The application server contains a user entry with username student and password password, which ismapped to the blog-user role. Change <auth-constraint> in web.xml and add the <security-role> entryto the end of web.xml:
... </error-page>
<security-constraint> <web-resource-collection> <web-resource-name>The entire app</web-resource-name> <url-pattern>/*</url-pattern> </web-resource-collection> <auth-constraint> <role-name>blog-user</role-name> </auth-constraint> </security-constraint>
<security-role> <role-name>blog-user</role-name> </security-role></web-app>
You have specified who can use the application, but do not yet have a way to determine the user's identity.
Java Web Programming
Page 140 Rev 4.1.2 © 2011 ITCourseware, LLC
login-config
Add a <login-config> element to tell the application what type of authenticationto use.
BASIC and FORM authentication use a username and password type ofauthentication.
Other authentication methods exist, but require more setup and are less-commonly used.
The <login-config> element also provides any extra information neededby the authentication method.
Once a user is authenticated, the container looks up which roles are associatedwith that user.
Requests against secured resources result in the container asking forauthentication.
The container allows or denies the request based on whether the user hasa role that can use the resource.
Use the getRemoteUser() method of the request inside a servlet to returnthe user's name.
public void doGet(HttpServletRequest req,HttpServletResponse res){String user=req.getRemoteUser();...
}
Chapter 8 Security
© 2011 ITCourseware, LLC Rev 4.1.2 Page 141
Hands On:Add the following entry to the end of web.xml, but do not redeploy the application.
... <security-role> <role-name>blog-user</role-name> </security-role>
<login-config> </login-config></web-app>
Java Web Programming
Page 142 Rev 4.1.2 © 2011 ITCourseware, LLC
BASIC Authentication
The default form of authentication is BASIC.
Explicitly set BASIC authentication by setting the <auth-method> sub-element of <login-config> to BASIC.
You can provide an optional realm name with the <realm-name> sub-element.
The realm is usually not important except as part of the clientprompt.
The application server tells the client which realm the resource is in, and asksthe client to get the corresponding username and password.
The client displays a dialog box presenting the request.
The client encodes the username and password, passing them back to theapplication server.
The client encodes the username and password using the Base-64 scheme.
Base-64 is easy to decode, so treat it as if the username and password aresent as plain text.
Use HTTPS instead of HTTP if this is an issue.
Chapter 8 Security
© 2011 ITCourseware, LLC Rev 4.1.2 Page 143
Hands On:Change the login config in web.xml to the following and redeploy the application:
... <security-role> <role-name>blog-user</role-name> </security-role>
<login-config> <auth-method>BASIC</auth-method> <realm-name>News Blog</realm-name> </login-config></web-app>
Now a dialog box displays when you try to access the application. Submit the dialog using student andpassword to access the application.
Java Web Programming
Page 144 Rev 4.1.2 © 2011 ITCourseware, LLC
FORM Authentication
Customize the login form with FORM authentication.
BASIC authentication presents a standard dialog box that cannot becustomized.
Set the <auth-method> sub-element of <login-config> to FORM to useFORM authentication.
The <form-login-config> sub-element of <login-config> provides additionalinformation.
The <form-login-page> sub-element provides the URL of the customlogin form.
The <form-error-page> sub-element provides the URL of the customlogin error page.
The application server uses these pages instead of the standardauthentication dialog box.
FORM authentication does not use realms.
Usernames and passwords are plain text fields of a form.
Use HTTPS to keep these secret.
Chapter 8 Security
© 2011 ITCourseware, LLC Rev 4.1.2 Page 145
Hands On:Replace the <login-config> entry in web.xml and redeploy the application:
... <security-role> <role-name>blog-user</role-name> </security-role>
<login-config> <auth-method>FORM</auth-method> <form-login-config> <form-login-page>/CustomLogin.html</form-login-page> <form-error-page>/CustomLoginError.html</form-error-page> </form-login-config> </login-config></web-app>
Access the application and note that the custom login screen is now used. Enter an invalid username andpassword to bring up the custom error page. Login with a valid username and password to access theapplication.
Java Web Programming
Page 146 Rev 4.1.2 © 2011 ITCourseware, LLC
Login and Error Pages
The custom login page must contain a form that follows some simple rules.
The action for the form must be j_security_check.
The form must contain a field named j_username.
The form must also contain a field named j_password.
The custom login page can contain anything else you want.
The custom error page can be any page you want.
HTML or JSP is fine.
No special rules — it is just like any other page.
Possible additions to an error message are:
A link to try againA link to email a forgotten password or usernameA link to reset a forgotten password
Chapter 8 Security
© 2011 ITCourseware, LLC Rev 4.1.2 Page 147
Examples/WebContent/CustomLogin.html<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html> ... <body> Please Login below: <p> <form method="POST" action="j_security_check"> <table> <tr> <td>Login:</td> <td><input type="text" name="j_username"></td> </tr> <tr> <td>Password:</td> <td><input type="password" name="j_password"></td> </tr> <tr><td><input type="submit" value="Submit"></td></tr> <tr><td></td></tr> </table> </form> </body></html>
Examples/WebContent/CustomLoginError.html<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html> ... <body> Bad username/password combination - is the Caps Lock on? </body></html>
Java Web Programming
Page 148 Rev 4.1.2 © 2011 ITCourseware, LLC
Labs
The StarterCode directory contains a candy store application. Use Ant to deploy the application. The mainentry point to the application is http://localhost:8080/Truffles. An admin page is also available at http://localhost:8080/Truffles/admin/SetPrice.
Add BASIC authentication to the application such that any recognized user can run theapplication.(Solution: Solutions/WebContent/WEB-INF/web.xml)
Change the BASIC authentication to FORM authentication.(Solution: Solutions/WebContent/WEB-INF/web.xml.2, Solutions/WebContent/TruffleLogin.html, Solutions/WebContent/TruffleError.html)
Change the authentication so that only the manager can set prices.(Solution: Solutions/WebContent/WEB-INF/web.xml.3)
Chapter 8 Security
© 2011 ITCourseware, LLC Rev 4.1.2 Page 149
The application server contains the following accounts that you can use in the labs.
emanresu drowssap elor
1remotsuc drowssap tsuc
2remotsuc drowssap tsuc
reganam drowssap rgm