• No results found

Java Web Programming. Student Workbook

N/A
N/A
Protected

Academic year: 2021

Share "Java Web Programming. Student Workbook"

Copied!
51
0
0

Loading.... (view fulltext now)

Full text

(1)
(2)

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 quality

of this workbook and the many students who have offered comments, suggestions, criticisms, and insights.

Copyright © 2011 by ITCourseware, LLC. All rights reserved. No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photo-copying, recording, or by an information storage retrieval system, without permission in writing from the publisher. Inquiries should be addressed 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 respective owners.

(3)

© 2011 ITCourseware, LLC Rev 4.1.2 Page iii

Chapter 1 - Course Introduction ... 7

Course Objectives ... 8

Course Overview ... 10

Using the Workbook ... 11

Suggested References ... 12

Chapter 2 - Web Applications and MVC ... 15

Web Applications ... 16

JSPs and Servlets ... 18

Model-View-Controller ... 20

Model 2 Architecture ... 22

The WAR File ... 24

web.xml ... 26

Building the WAR ... 28

Deploying the WAR ... 30

Labs ... 32

Chapter 3 - JavaServer Pages ... 35

Introduction to JSP ... 36

JSP Syntax ... 38

JSP Scripting Elements ... 40

Request and Response Implicit Objects ... 42

page Directive ... 44

Error Handling ... 46

The include directive ... 48

include and forward Actions ... 50

Labs ... 52

Chapter 4 - Java Servlets ... 55

HTTP Requests ... 56

HttpServlet ... 58

Servlet Lifecycle ... 60

(4)

RequestDispatcher ... 64 HttpSession ... 66 ServletContext ... 68 Servlet Filters ... 70 JSP vs. Servlet ... 72 Labs ... 74 Chapter 5 - JavaBeans ... 77 What is a JavaBean? ... 78 Rules ... 80 Properties ... 82 Using JavaBeans in JSPs ... 84

Properties and Forms ... 86

Data Access Objects ... 88

Resource Reference ... 90

Bean Scopes in Servlets ... 92

Bean Scopes in JSPs ... 94

Labs ... 96

Chapter 6 - JSP Expression Language ... 99

JSP Expression Language ... 100

Literals ... 102

Variables ... 104

The . and [ ] Operators ... 106

Other Operators ... 108

Implicit Objects ... 110

Labs ... 112

Chapter 7 - Introduction to JSTL ... 115

What is JSTL? ... 116

(5)

© 2011 ITCourseware, LLC Rev 4.1.2 Page v Concepts ... 134 Constraints ... 136 Roles ... 138 login-config ... 140 BASIC Authentication ... 142 FORM Authentication ... 144

Login and Error Pages ... 146

Labs ... 148

Appendix A - Tag Libraries ... 151

Custom Tags ... 152

Using Custom Tags ... 154

Defining Tags ... 156

Tags with Attributes ... 158

Fragments and Variables ... 160

Packaging Tag Files ... 162

Labs ... 164

Appendix B - Ant ... 167

What Is Ant? ... 168

build.xml ... 170

Tasks ... 172

Properties and Property Files ... 174

Managing Files and Directories ... 176

Filesets ... 178

Java Tasks ... 180

Creating Java Archives ... 182

Specifying Paths ... 184

Miscellaneous Tasks ... 186

Solutions ... 189

(6)
(7)

© 2011 ITCourseware, LLC Rev 4.1.2 Page 7

(8)

”

Write web applications that combine Java Servlets, JavaServer Pages, and

JavaBeans 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 Expression

Language for functionality, such as conditionals, iteration, internationalization,

and XML processing.

(9)
(10)

”

Audience: Java programmers who need to develop web applications using

JSPs and Servlets.

”

Prerequisites: Java programming experience and basic HTML knowledge

are required.

”

Classroom Environment:

¾

A workstation per student.

(11)

© 2011 ITCourseware, LLC Rev 4.1.2 Page 11 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 you lay the workbook open flat, the Topic page is on the left and the Support page is on the right. The Topic page contains the points to be discussed in class. The Support page has code examples, diagrams, screen shots and additional information. Hands On sections provide opportunities for practical application of key concepts. 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 as on-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 provides

the main topics for classroom discussion.

The Support page has additional information, examples and suggestions.

Code examples are in a fixed font and shaded. The

on-line file name is listed above the shaded area.

Screen shots show examples of what you

should see in class. Topics are organized into

first (”), second (¾) and third (ƒ) level points.

Pages are numbered sequentially throughout the book, making lookup

easy.

Callout boxes point out important parts of the

(12)

Basham, Bryan, Kathy Sierra, and Bert Bates. 2004. Head First Servlets and JSP: Passing the Sun Certified 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.html JSP Technology: http://www.oracle.com/technetwork/java/jsp-138432.html

JSTL Technology: http://www.oracle.com/technetwork/java/jstl-137486.html Java EE 6 Tutorial: http://download.oracle.com/javaee/6/tutorial/doc/

(13)
(14)
(15)

© 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-Component

architecture applies to a web application.

”

Describe the structure of WAR files.

”

Build and deploy a web application.

(16)

”

Web applications are applications that the end user can access using a standard

web browser.

”

The Java Platform Enterprise Edition (Java EE) defines a web application as a

collection of web components and supporting files.

¾

Web components include Java servlets and JSP files.

¾

Supporting files include static HTML documents, image files, and

supporting classes.

”

Your web application runs in the environment of a web container, which is

managed 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 empty

context path.

¾

To access a component or file in the web application from a browser, you

must include the context path in the request URL.

(17)

© 2011 ITCourseware, LLC Rev 4.1.2 Page 17 Browser HTTP Application Server Web Container Web Application Servlet JSP

(18)

JSPs and Servlets

”

The standard protocol for communication between browsers and servers is

designed for static documents.

¾

Typically, a web server returns the contents of a static file in response to a

browser request.

”

Use servlets and JavaServer Pages (JSP) to handle requests from a browser

dynamically.

¾

A servlet is a web component which receives an object encapsulating the

browser 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 special

tags 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.

(19)
(20)

Model-View-Controller

”

The Model-View-Controller (MVC) architecture was originally described by

Smalltalk for implementing GUI applications.

”

The primary goal of MVC is to separate user interface code (the view) from

domain code (the model).

¾

The controller is introduced as a separate body of code that manages the

translation 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 without

impacting the model.

¾

Developers can focus on their skills — database programmers do not

need to understand user interface issues.

”

MVC adapts well to the needs of web applications.

¾

The view is further separated from the model both architecturally and

physically.

(21)

© 2011 ITCourseware, LLC Rev 4.1.2 Page 21

View

Controller

(22)

Model 2 Architecture

”

The typical adaptation of MVC to Java web applications is called the Model 2

Architecture.

”

Use JavaBeans to define the model.

¾

The controller should encapsulate business object data in JavaBeans to

make the data accessible to the JSP views.

¾

The controller can provide helper JavaBeans to convert data from the

business object to formats appropriate to the view.

ƒ

For example, a JavaBean could convert a date to an appropriate

string 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 the

request.

¾

Finally, it will forward the request to the JSP page, including any beans

needed to generate the view.

ƒ

The servlet might choose between JSP pages based on the results

of the request.

(23)

© 2011 ITCourseware, LLC Rev 4.1.2 Page 23

ArticleNotFound.jsp ListArticles.jsp

ShowArticle.jsp

In both Model 1 and Model 2 architectures, JavaBeans are the preferred mechanism for accessing business objects. The JSP specification has strong support for working with JavaBeans objects, which makes 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

(24)

”

You must organize your web application using a specific directory structure.

¾

The application root directory acts as the document root for your

application.

ƒ

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/classes

directory.

¾

Put any JAR files specific to your application in the WEB-INF/lib

directory.

ƒ

This is the preferred method for storing your JavaBeans.

ƒ

If a JAR file will be used by other applications, it may make more

sense to put it in a system-wide or server-wide directory.

”

You can package your application for distribution in a Web ARchive (WAR) file.

(25)

© 2011 ITCourseware, LLC Rev 4.1.2 Page 25 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 and MANIFEST.MF are

artifacts created by the

jar utility. They have no

effect on the war.

Most container vendors also suggest a vendor-specific XML file in the

(26)

web.xml

”

Provide an optional deployment descriptor to supply additional configuration

information 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 context

with 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 pages

dynamically.

¾

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>

(27)

© 2011 ITCourseware, LLC Rev 4.1.2 Page 27 The location is specified

relative to the web application root.

You can use a

<description> element

to provide documentation.

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 that you can add to your code to take the place of many, but not all, of the web.xml entries.

(28)

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 the

application 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.

(29)

© 2011 ITCourseware, LLC Rev 4.1.2 Page 29 for 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 the appropriate build target. Your instructor will give you the details of how to run Ant and which target to use.

(30)

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 to

locate 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 the

deployment descriptor.

ƒ

These might include database connections, JNDI services, and

security roles.

”

The mechanisms for performing these is determined by your web container.

¾

Some container providers have GUI or web-based tools for deploying

applications.

¾

You may need to create the appropriate configuration files manually and

include them in your WAR file.

(31)

© 2011 ITCourseware, LLC Rev 4.1.2 Page 31 The servlet creates a new directory within the WEB-INF directory of the deployed application. The articles are stored in this new directory as serialized objects. The upside of this implementation is that you do not need to configure a storage directory or database. The downside is that this directory is usually destroyed when the application is redeployed.

The classes in the blognews package represent the controller, the model, and the business logic. The

Article class is our model JavaBean. The ArticleFactory and supporting class

ArticleNotFoundException provide the business logic for working with articles. The ArticleServlet is

the controller

Start Tomcat, then build and deploy the application by running the ant command in the chapter's Examples directory. To view the application, navigate with your browser to http://localhost:8080/BlogNews.

(32)

…

Modify the deployment descriptor so that the 405 error (generated when a user tries to use a GET when a POST is required) is handled by the GenericErrorHandler. You can generate this error by entering the URL for the View command manually in your browser's address 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 or dereference 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 the servlet 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 need to create a form to enter the title of the article to edit and a new action in ArticleServlet to display the new view using the article entered in the form. The new view can use the existing

Post action in the servlet to save the changes. Add a link to index.html to display the new

form.

(Solutions: Solutions-Lab4/WebContent/EditArticle.jsp, Solutions-Lab4/WebContent/

EditArticle.html, Solutions-Lab4/src/blognews/ArticleServlet.java, Solutions-Lab4/ WebContent/index.html)

(33)
(34)
(35)

© 2011 ITCourseware, LLC Rev 4.1.2 Page 133

Chapter 8 - Security

Objectives

”

Add authentication and authorization to a

web application.

”

Use HTTP Basic and Form-based login

methods.

”

Create security roles and constraints in

(36)

”

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 your

identity.

¾

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 access

another person's account.

ƒ

Another person can tell the bank you should have access to their

account.

”

Web applications need to authenticate a user, and then determine if the user is

authorized to perform a request.

¾

A user often provides a password to authenticate their identity.

¾

The web application can then check requested actions against those

allowed for the user.

(37)

© 2011 ITCourseware, LLC Rev 4.1.2 Page 135 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 for the given realm.

Browser Application Server

HTTP Request 401 Authentication Required Access a Restricted URL Username/ password OK Prompt for username and

password Original HTTP Request + username and password

(38)

Constraints

”

Add <security-constraint> entries to web.xml to restrict access to portions of

a web application.

¾

Each security constraint entry describes what access is allowed on a set of

resources.

”

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-element

describing the collection.

¾

The collection can have any number of <url-pattern> sub-elements

describing 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.

(39)

© 2011 ITCourseware, LLC Rev 4.1.2 Page 137

...

</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 now restricted.

(40)

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 the

web 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 the

resource.

¾

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.

(41)

© 2011 ITCourseware, LLC Rev 4.1.2 Page 139 to 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>

(42)

login-config

”

Add a <login-config> element to tell the application what type of authentication

to use.

¾

BASIC and FORM authentication use a username and password type of

authentication.

¾

Other authentication methods exist, but require more setup and are

less-commonly used.

¾

The <login-config> element also provides any extra information needed

by the authentication method.

”

Once a user is authenticated, the container looks up which roles are associated

with that user.

¾

Requests against secured resources result in the container asking for

authentication.

¾

The container allows or denies the request based on whether the user has

a role that can use the resource.

¾

Use the getRemoteUser() method of the request inside a servlet to return

the user's name.

public void doGet(HttpServletRequest req, HttpServletResponse res){

(43)

© 2011 ITCourseware, LLC Rev 4.1.2 Page 141 ... <security-role> <role-name>blog-user</role-name> </security-role> <login-config> </login-config> </web-app>

(44)

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 client

prompt.

”

The application server tells the client which realm the resource is in, and asks

the 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 the

application 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 are

sent as plain text.

(45)

© 2011 ITCourseware, LLC Rev 4.1.2 Page 143 ... <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 and

(46)

FORM Authentication

”

Customize the login form with FORM authentication.

¾

BASIC authentication presents a standard dialog box that cannot be

customized.

”

Set the <auth-method> sub-element of <login-config> to FORM to use

FORM authentication.

”

The <form-login-config> sub-element of <login-config> provides additional

information.

¾

The <form-login-page> sub-element provides the URL of the custom

login form.

¾

The <form-error-page> sub-element provides the URL of the custom

login error page.

¾

The application server uses these pages instead of the standard

authentication dialog box.

”

FORM authentication does not use realms.

”

Usernames and passwords are plain text fields of a form.

¾

Use HTTPS to keep these secret.

(47)

© 2011 ITCourseware, LLC Rev 4.1.2 Page 145 ... <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 and password to bring up the custom error page. Login with a valid username and password to access the application.

(48)

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 again

ƒ

A link to email a forgotten password or username

ƒ

A link to reset a forgotten password

(49)

© 2011 ITCourseware, LLC Rev 4.1.2 Page 147

<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>

(50)

Labs

The StarterCode directory contains a candy store application. Use Ant to deploy the application. The main entry 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 the application.

(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)

(51)

© 2011 ITCourseware, LLC Rev 4.1.2 Page 149 e m a n r e s u password role 1 r e m o t s u c password cust 2 r e m o t s u c password cust r e g a n a m password mgr

References

Related documents

Transfer printing is the term used to describe textile and related printing processes in which the design is first printed on to a flexible nontextile substrate and later transferred

Old Habit: Paper CRF Process Primary Investigator Source Document CRC CRFs CRFs DB1 Double Data Entry Master Clinical 6 Query Report Form Site Sponsor Query Report Form CDM

The purpose of this project was to evaluate if the IBR program at SHZCH improves the patient’s perception of communication with nursing as evidenced by improved patient

◆ Guidelines for planning, implementing, and reviewing a comprehensive maintenance training program ◆ Easy-to-use techniques for improving your “Maintenance IQ” and your value to

Lead, Health IT VA Clinical Assessment, Reporting, and Tracking (CART) Program National Manager, VHA Web Solutions | Office of Informatics and Analytics September 12,

T-test (p&lt;0.05) for seedlings from large and small groups of acorns for all measured morphological parameters (ms – shoot dry weight, mr – root dry, ms / mr – shoot to root

PRESENT: Alister Stuck (Chair), Gary Duncan, Arie Geursen, Tony Lenart, Kay Nicholas, Arleen Schwartz, Norm Silcock, Noel Woodhall, and Fran Jenkins (Secretary).. IN ATTENDANCE:

Satellite-based nighttime lights data depicted here, represent a possibility for a border-breaching, interdisciplinary approach that may hold the promise to allow