1. Trang chủ
  2. » Công Nghệ Thông Tin

Addison wesley servlets and javaserver pages the J2EE technology web tier sep 2003 ISBN 0321136497

176 53 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 176
Dung lượng 1,68 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

The java.util.logging package can be generalized into two parts, Logger and Handler objects.. A logger object is responsible for logging information to one or more Handler objects.. Usin

Trang 2

Save error.jsp in the root directory of the jspbook_site Web Application.Deploy the page as the site's default error page by adding Listing 15-36 to

Reload the Web Application for the changes to take effect Now we have a fail-http://127.0.0.1/jspbook_site/error.jsp The page provides a polite errormessage and is rendered with the site's implicit header and footer Figure 15-18

provides a browser rendering of the results in English

Figure 15-18 Browser Rendering of the Polite Error Page

Trang 3

Logging Errors

Chapter 4 devoted a large section of its text to error handling, and it would be ashame to neglect the concepts for the book support site's Web Application

Logging could have been more extensively used to provide information aboutany of the book's code, such as database queries, but it was omitted for

simplicity Now logging cannot be omitted The error page handles importantinformation; we must be able to keep track of what goes wrong with the WebApplication so that administrators can attempt to correct the problem To handleerror logging, we shall re-use the SiteLogger code (Listing 4-24 in Chapter 4)

Deploy the SiteLogger listener, save, and compile Listing 4-23 and Listing 4-24

in the WEB-INF/classes/com/jspbook directory for the jspbook_site WebApplication The listener takes care of creating a Logger class that the error pagecan use at any time to log information Listing 15-37 is required to deploy the

Trang 4

directory of the jspbook_site Web Application Compile the code and reloadthe Web Application for the changes to take effect Now the Web Applicationboth appropriately handles errors and saves information for administrators in the

/WEB-INF/log.txt file If you have forgotten how the SiteLogger class works,revisit Chapter 4

Adding Security

Chapter 10 went to great lengths explaining the basics of security and why youshould use it The greater point to take away from Chapter 10 is if only certainpeople should be able to access part of a Web site, ensure only those people haveaccess Never assume users are too dumb to use administrative tools (like

ArbitrarySQLDataSource.jsp), and never think the administrative portion of

Trang 5

Various levels of security exist for a Web Application: simple unencrypted username and password combinations, hashed user name and password schemes, andfinally completely secure communication via SSL/TLS Each type of security issimple to implement and can be done by configuring web.xml For the booksupport site we need to make sure only administrators have access to the editpages Configure web.xml to restrict access to any URL beginning with /admin

(Listing 15-39); this will ensure regular users cannot use the administrative

tools[10]

[10] You'll recall security is always an arms race Current security schemesdon't guarantee absolute security, although the protection is very

Trang 6

You'll recall the user name and password information need to be provided onlyonce per session; once you correctly type in the user name and password, theHTTP protocol takes care of remembering you did so The particular user nameand password we are using are the same as configured in Chapter 10 (Listing 15-

Link Tracking

Most Web Applications care about tracking hits, referrers, and outbound traffic

Trang 7

Chapter 2 and Chapter 8 we saw examples of a link tracking Servlet and a linktracking Filter For the book support site, we will re-use the link tracking Filterdemonstrated in Chapter 8 Copy the code for the Filter (Listing 8-3, Listing 8-5,and Listing 8-6 from Chapter 8), and save it in the /WEB-

INF/classes/com/jspbook directory of the jspbook_site Web Application.Deploy the LinkTracker Filter to intercept all requests (Listing 15-41)

Figure 15-20 Updated Version of the Web Application

Trang 9

we need to add a Model 2 logic component that uses the LinkTracker class's

getRequests(), getResponses(), and getReferrers() methods to populaterequest-scoped variables Save Listing 15-43 as linktracker.java in the /WEB- INF/classes/com/jspbook directory of the jspbook_site Web Application

Figure 15-21 Browser Rendering of linktracker.jsp

Trang 10

The encoding scheme for links is simple: each link must go to /linktracker andcontain an HTTP parameter named "url" that provides the outbound URL Thedifficult part about encoding links is that each and every link in the Web

Application must be encoded Doing this task by hand is tedious and not

recommended for large Web Applications; however, we have little choice but to

do it for the book support site A quick search and replace, using your favoritetext editor, does the job Recall that in the multi-client chapter a much betterscheme was suggested for encoding links: abstract all links (similar to what theJSTL url tag does) Then the links can be encoded at runtime by the abstraction,likely a custom tag

After changing the links to use the link tracking Filter, note the links to externalreferences are now encoded to be local For example, the link to Tomcat,

normally http://jakarta.apache.org/tomcat, is changed to redirect?url= http://jakarta.apache.org/tomcat If you click on the link, it still appears to

Trang 11

http://127.0.0.1/jspbook_site/linktracker.jspnote the outbound linknow appears in the tracked statistics Figure 15-22 provides a browser rendering

of the results

Figure 15-22 Browser Rendering of Statistics on Outbound Links

The site's link tracking functionality is now complete The LinkTracker Filter is

an excellent modular component that is easy to add to most any site The onlytricky part is encoding all outbound links (if you want to track them), but theMulti-Client framework made this task trivial

Caching and Compression

A final touch to the book support site can make the site notably more efficientand fault-tolerant Several layers of functionality are abstracted in order to makecoding the site simpler Examples of this functionality include using the MCT forabstracting formatting, querying the database for dynamic information, and

using Model 2 logic components instead of embedding code For most practical

Trang 12

to generate a dynamic response, we can cache the response using a Filter, asdemonstrated in Chapter 8 The cache can also act as fault tolerance in case forsome reason, such as a poorly done code "fix" or the database crashes, a JSPthrows an exception Additionally, for optimal performance we can take

advantage of HTTP's compression mechanism, also demonstrated in Chapter 8

For the book support site we will be able to directly re-use the cache and

compression Filters created in Chapter 8 As described in Chapter 8, these twoFilters are easily re-used in most every Web Application, which is absolutelytrue, and make the code quite handy Once the Filters are applied, the conceptualview of the Web Application will look as in Figure 15-23

Figure 15-23 Updated Conceptual View of Web Application

The Filters are applied as they should be: compression first, caching second Notall HTTP clients support compression so we cannot assume compression shouldalways be used Deploy the two Filters by adding Listing 15-44 to web.xml

Listing 15-44 Cache and Compression Filter Deployment

Trang 13

jspbook_site/WEB-INF/com/jspbook directory (Listings 8-11, 8-12, 8-13, 8-15, 8-16, and 8-17,respectively, from Chapter 8) Finally, reload the Web Application for the twoFilters to take effect

An important point to note is that the cache Filter is still working properly eventhough we are using localized content Go ahead and try out the cache Filter byrequesting the same resources with different language preferences; you will getthe same content as we did previously in the chapter Recall in Chapter 8 that webased the cache solely off the request URL This strategy will obviously not

Trang 14

index-fra.jsp To solve this problem, the cache Filter has the locale-sensitiveparameter set

Trang 15

options via initial parameters This allows the same cache Filter to then be usedwith most any Web Application by simply configuring a few initial parametersahelpful Filter indeed

Don't Cache Always-Dynamic Resources!

There is another huge "gotcha" of using a cache Filter: caching resources thatmust be dynamic For simplicity we deployed the cache Filter to intercept allrequests to resources ending in .jsp; for practical use this is a mistake Think ofall the resources that must remain dynamicfor instance, the add news component

or any of the other components that rely on a client to upload information via anHTML form If we leave the cache Filter as it is now, all of these resources arebroken; the cache Filter occurs before the control Filter

Trang 16

What is the solution? Simply putting the cache Filter after the control Filterworks, but in a sense defeats the purpose of the cache Filter Control componentscan take a relatively long time compared to executing a JSP or Servlet, therefore,

it is helpful to cache away this time There are a few good solutions, which caneven be used together if required The first is to selectively cache only whatshould be cached For example, don't deploy the cache Filter to all JSP

Another good solution is to deploy the Filter to cache all resources and

selectively instruct the Filter to not cache specific resources via initial

parameters Recall the cache Filter from Chapter 8 treats any initial parameter

Trang 17

The final solution is to use two instances of the same Filter in combination withthe preceding methods There are two obvious points that are valid for caching:before execution of the logic component (and implicitly the JSP or Servlet

endpoint) or after the logic component but before the endpoint If the controllogic must always be executedfor example, in the case of addnews.jspyoucannot cache before the logic component, but you can cache after it to speed upthe time it takes to execute the endpoint (the Servlet or JSP)

If you are trying this chapter's code, it is assumed you will configure the cacheFilter to not cache all of the resources that must execute logic components,basically everything in the /admin directory or any of the user feedback

techniques learned from previous chapters For the egg we will add in a pagewhere people are encouraged to upload pictures of the book; this was mentioned

in the preface Given the strange phenomena surrounding yard gnomes and thatthe cover of this book is a yard gnome, you are encouraged to send in a photothat creatively displays the book or many copies of the book However, we haveyet to provide a method for uploading images A photo upload page is required

The egg, like all other components of the site, will be split into a Model 2 logiccomponent and a presentation JSP The JSP is a simple HTML form for

uploading a picture Save Listing 15-45 as egg.jsp in the root directory of the

jspbook_site Web Application

Listing 15-45 egg.jsp

<p class="h1">Photos of the yard gnome!</p>

Trang 18

corner of the Web site They will be images of people who have read Servlets and JSP the J2EE Web Tier cleverly placed in the photos How did we get them? Simple Readers sent them in The rules are

simple If you have bought and read the book, you can send a photo

hand corner of the Web site It is a silly way of saying thanks for reading the book.</p>

in From then on your photo will randomly appear in the top right-<p>Why do this? Mainly because it is fun, but in the United States many people have a tradition of taking a yard gnome with them on

vacations The gnome then serves as a hidden surprise in all of the various photos taken during the trip It can only be guessed as to how this tradition ever started, but it is likely that normal

vacation photos were just too bland or that many people enjoy being silly We figure a normal photo of your workplace is also bland or that you enjoy being silly So, send in photos of the gnome.</p>

<input type="submit" value="Submit Photo"/>

</form>

<center><image src="${image}"/></center>

The page consists of a lot of static text explaining the egg and a simple HTMLform The form is the only thing that merits discussion

upload.jsp (which we'll create later), the form is set to be encoded as

multipart/form-data, and an input exists for submitting a file Consult Chapter

Trang 19

Currently, upload.jsp does not exist, but that is where the form is posting itscontent The most important reason we have to upload.jsp is to create a logiccomponent that can deal with uploaded pictures The general scheme for

handling newly uploaded pictures will be similar to the scheme used for the rest

of the site's content The image will be saved in a special directory (/images),and an entry to the site's database will be made with the image set as not visible

It will be assumed that later on a site administrator will verify the image is okayand flag it as visible Listing 15-46 provides the code for the upload logic

Trang 20

Before trying to use the code for upload.java, be sure to create the Images table

Trang 21

Listing 15-47 upload.jsp

Upload Complete.

Test the file upload page by copying the JAR file for the Jakarta CommonsFileUpload API to the jspbook_site Web Application's /WEB-INF/lib

directory, compiling the new code, reloading Tomcat, and browsing to

http://127.0.0.1/jspbook_site/egg.jsp Select an image file to upload andclick on the Submit Photo button After the file uploads, the index page should

be displayed You can verify the upload worked by browsing the /images

directory of the jspbook_site Web Application A new image is there with atime-stamp for a name and the same extension of the uploaded image

By itself, the egg does little What good are uploaded images if they are notdisplayed on the Web site? To complement the egg page, we will modify theheader to randomly display uploaded images that have been set as visible Inorder to accomplish this, we will create a .tag file that replaces the static imagewith a dynamical image Recall the header displays an image in the top right-hand corner of the Web page

Trang 22

the /WEB-INF/tags directory of the jspbook_site Web Application

Trang 24

on the image to see the egg page

In order to fully test the egg page, you will need to upload more images andtoggle them to be visible (via ArbitrarySQLDataSource.jsp or perhaps anotherdatabase edit page similar to edit.jsp) This exercise is left up to you; it should

be straight-forward given that we have already done something similar for thenews, errata, FAQ, and feedback pages If you really want to see the tag in

action, visit the book support site, http://www.jspbook.com You'll notice theimage in the top right-hand corner is constantly changing

Trang 25

Exceptions are an integral part of the Java programming language When a

program violates the rules of Java, the Java Virtual Machine halts execution ofthe program and generates an exception Managing exceptions is somethingevery Java program must do Servlets and JSP are no different Until now, thetopic of programming errors has largely been ignored in favor of introducing JSPand Servlets While necessary for the start of this book, errors are inevitable andneed to be understood so they can be dealt with appropriately It is the goal ofthis chapter to clearly explain what exceptions are and how to deal with them inServlets and JSP

This chapter discusses the following topics:

A general review of Java's support for exceptions and how Java exceptionhandling works

How to handle Servlet and JSP exceptions using Java's built-in exceptionhandling mechanism

Trang 26

Logging is the act of keeping a record of important information in some

serialized form Some simple examples of logs include a text file with lines oferror messages or information printed to System.err or System.out Sometimeslogged information is designed to be kept for long periods of time Other timeslogged information is meant for short-term use to quickly debug a running

No attempt is given at distinguishing between different types of information tolog, and all logging relies on access to a ServletContext object

For the purpose of building a practical Web Application, a full-blown loggingAPI is introduced and demonstrated in this section The logging API is not

specifically defined by Servlets or JSP; however, it is a valuable tool for anyproject including a Web Application

The Problem with System.out.println()

The far too common mindset is to build a Java application and get by with arudimentary set of debugging calls Most commonly, this set of calls consists ofusing the PrintStream objects System.out or System.err to send temporaryinformation to a terminal This method of application debugging is simple andworks for small projects, but it quickly falls apart in most any real-world

situation

System.out.println() debugging, which is analogous to

System.err.println() debugging, is instant gratification If code does notwork, most every Java developer knows inserting a few simple

System.out.println() method calls makes something appear somewhere

Trang 27

System.out.println() works perfectly fine; however, a problem occurs when

an application needs to constantly log information and will need to log

information for the foreseeable future This information might be trivial

statements, such as "made it here", or important information such as runtimelistings of system workloads Far too many times, calls to

System.out.println() are used in these cases when they really should not

The issue to think about is, What will the debugging code do in the future?

Inserting System.out.println() calls only works until the calls are no longerneeded Going back and commenting the calls out for performance is not terriblyhelpful, especially when a bug arises What happens when more than one

developer starts working on the project? If two different developers use

completely arbitrary calls to System.out.println(), or equivalents, then each islikely to hinder the other Without a common logging mechanism it is hard tocollaborate Another very important issue is, What happens when the logginginformation needs to be piped to a different location? Instead of to a terminalscreen, what about a log file, email, or a common repository? Manually fixingcountless System.out.println() calls is a complete waste of time, especially ifthe fix is going to need even more changes later on

A good and commonly agreed-upon solution to saving debugging information is

by means of a simple, yet robust logging API A dedicated API can abstract thelogging process, provide a common interface for multiple developers, enable anddisable levels of logged information for performance, and allow easy changes to

http://jakarta.apache.org/log4j, and is at version 1.2 Log4j has some fantasticdevelopers working behind it and is a true and tested logging API In addition toLog4j, the standard Java development kit version 1.4 introduced a new logging

Trang 28

In writing this book the choice had to be made between which of these loggingAPI to use and push as a preferred choice After some careful consideration andthorough use of both APIs the choice was made to use the java.util.logging

package The truth of the matter is that both packages do a more than sufficientjob as a logging API Log4j does have a slight advantage in terms of previoustesting and widespread community use, but the java.util.logging package isalready included in the default Java 1.4 download and will be around in futuredistributions

Using the java.util.logging Package

The java.util.logging package is included with every Java SDK 1.4

distribution No extra installation is required to use the API with this book'sexamples If the code does not work, you probably did not follow the installationsteps in Chapter 1 Make sure you are using the Java 2 Standard DevelopmentKit 1.4 release or a later version

The java.util.logging package can be generalized into two parts, Logger and

Handler objects A logger object is responsible for logging information to one

or more Handler objects Handler objects are responsible for customizing whereand how information is logged Using the java.util.logging package is assimple as creating a instance of a Logger object, registering one or more Handler

objects, and logging information as needed

For common logging, such as to terminals or files, the java.util.logging

package includes everything that is needed to implement a simple logging

system In more complex cases the same functionality is used; however, customsubclasses of Logger and Handler objects might be required Overall, the

Trang 29

Information posted by the form is logged by the server to System.err This can

be verified by checking the location of System.err By default, Tomcat saves allinformation sent to System.err in the catalina.out file located in the /logs

directory of installation Open up this file to see the logged information Forexample, if "log test" was submitted via the HTML form, then the following line

Trang 30

Mar 18, 2002 8:30:11 PM org.apache.jsp.Logger$jsp _jspService

INFO: log test

For the time being, disregard the extra information included with the entry Thepoint of this example is to illustrate a quick and easy use of the

java.util.logging package Achieving a simple default-formatted log entryrequires a few lines of code Logger.jsp demonstrates this with the followingtwo lines

Logger logger = Logger.getLogger("example");

logger.addHandler(new ConsoleHandler());

After the Logger object was created and a Handler added, the system was ready

to log information There are many ways to log information, but in the example,the convenient info() method was used

logger.info(info);

Subsequent calls to log information could also be included as desired; however,

in this example, none were needed The main purpose of the example was tointroduce the general use of Logger and Handler objects The

java.util.logging package is easy to use and can be implemented with just afew lines of code Discussion now expands to using the individual parts of the

java.util.logging package for custom logging

Trang 31

Handlers are responsible for handling information that needs to be logged

Should the information go to a terminal screen, flat file, or any other resource, it

is the responsibility of a Handler to make sure it gets there Information

published to a Handler is represented by a java.util.logging.LogRecord

object A LogRecord object includes information to log, where the informationcame from, how important the information is, and a time-stamp How to

appropriately style and present this information is the responsibility of a

java.util.logging.Formatter object Each Handler object has a Formatter

object associated with it to appropriately style published LogRecords

A few Handler objects are included with the java.util.logging package:

StreamHandler: A StreamHandler object represents a Handler designed toexport logged information to a java.io.OutputStream The

StreamHandler object includes a constructor that takes an OutputStream

and Formatter object as parameters and uses them to format and streamlogged information

MemoryHandler: The MemoryHandler object provides a cheap way to keep

a set of LogRecord objects in memory After established amounts of

LogRecords are buffered, they are all published to an Handler object forappropriate handling The MemoryHandler object is best used when it isexpensive to constantly publish individual records, perhaps if a connectionneeds to be opened and closed during the logging of each record

Consolidating a set of logs during one connection can be much more

efficient

The MemoryHandler object provides a constructor that takes as arguments a

Handler, int value for a buffer size, and a push level The Handler object

is the Handler buffered LogRecord objects are published to, the int

represents how many LogRecord objects to buffer, and the push level allowsfor important messages to cause the buffer to automatically flush

SocketHandler: A SocketHandler is a convenient method for logging

information using a network socket By default the SocketHandler formatslogged information in an XML-compatible format The SocketHandler

object provides a constructor that takes as an argument a String

Trang 32

Handler automatically opens a java.net.Socket to the given URL on thespecified port for logging information

FileHandler: A FileHandler object is a convenient Handler for logginginformation to a local file The easiest use of the FileHandler object is tocall the constructor providing a String that represents the file to use forlogging information More complex uses also exist for using the

FileHandler object to automatically rotate logs between multiple files after

a certain space limit has been reached

The existing handlers in the J2SDK represent some of the most commonly usedresources for saving logged information Building an appropriate Handler objectfor most cases is nothing more than using one that already exists Using all theaforementioned convenience Handler objects is not fully demonstrated by thisbook The code is intuitive to use and is mentioned only to give an idea of whatcomes bundled with the java.util.logging package

Formatting

The style in which a Handler object exports information is completely

configurable Every Handler object relies on a Formatter object to convert a

LogRecord into an appropriate String of information to log The Formatter

object being used to style a specific Handler instance can be obtained or setusing the getFormatter() or setFormatter() methods

To code a custom Formatter object, extend the Formatter class and override therelevant methods There are four possible methods of interest:

format(LogRecord record): The format() method is invoked by a Logger

class when publishing information to be logged Passed as a parameter isthe LogRecord object describing the information to log The format()

method returns a String representing the final format of the information tolog

formatMessage(LogRecord): The formatMessage() method is a

convenience method that can be invoked by the format() method to

localize a message using a resource bundle Resource bundles are furtherexplained in Chapter 12

Trang 33

included, such as the start of a parent XML element, this method can beoverridden to produce the correct String

getTail(Handler handler): The getTail() method works much like the

getHeader() method but is used to return a tail to be placed at the end of aset of log records This method returns an empty String by default Incases where a tail must be included, this method can be overridden to

produce the correct text

There are two Formatting objects included with the java.util.logging

package: SimpleFormatter and XMLFormatter The SimpleFormatter objecttakes an instance of a LogRecord and converts it into a human-readable string.The string is usually one or two lines long and resembles the entries seen withthe Logger.jsp example, Listing 4-22 The XMLFormatter object takes a

LogRecord and formats it into an XML format

For most purposes the SimpleFormatter object does an adequate job of logginginformation Text returned by the SimpleFormatter object's format() methodincludes a time-stamp, the class sending the information to log, and the

information to log However, for the jspbook Web Application, a simple custom

Formatter object will be created for both example purposes and use throughoutthe book Save the code in Listing 4-23 as CustomLogger.java in the /WEB- INF/classes/com/jspbook directory of the jspbook Web Application

Trang 34

message

stack-trace

The brackets are used to easily distinguish separate log entries while the messageand stack-trace provide information about what went wrong with the Web

Application Before actually using the CustomFormatter class, a custom Logger

class needs to also be created for use with the jspbook Web Application

Loggers

A Logger object is used to log messages for a specific system of applicationcomponents Loggers are designed to be flexible and include features such aslocal-specific logging and logging information according to levels of

importance Logger objects are managed by a LogManager object that is

responsible for keeping and configuring a collection of loggers

Not all of the features of Logger and LogManager classes are covered in thisbook The flexibility of these classes is extensive and not commonly needed.What is covered in this section is the basic use of the Logger class with JSP and

Trang 35

java.util.logging package

Levels of Logged Information

All information logged through an instance of a Logger object is associated with

a specific level Levels are used to efficiently manage different types of loggedinformation A level may be arbitrarily assigned but is intended to give someinformation about the nature of the information to log Handler and Logger

objects can selectively log only certain levels of information, making it practical

to channel different types of information to desired locations

The level scheme the java.util.logging package uses is defined by the

java.util.logging.Level object The levels are listed, in descending order ofimportance, as follows:

SEVERE: The SEVERE level is the highest level of importance A SEVERE

level represents a severe, or critical, message that is to be logged Often the

SEVERE Level is associated with a thrown exception

WARNING: The WARNING level is the second highest level of importance A

WARNING level association represents a message to be logged that includes awarning Warnings are important to signal a future possibility of a severeproblem but are not severe problems themselves

INFO: The INFO level represents an informative message to be logged Themessage is less important than a warning or severe level message and ismost helpful when debugging an application The INFO level is commonlyassociated with the casual use of System.out.println() statements

CONFIG: The CONFIG level represents configuration information beingechoed back by an application Messages at the CONFIG level are less

important than informative messages and are meant for helping debug anapplication

FINE: The FINE level represents a message that falls in none of the previous

Trang 36

FINER: The FINER level represents a message less important than a FINE

message but more important than a FINEST message

FINEST: The FINEST level represents a message that is less important thanall the other messages

OFF: A level of OFF has the effect of turning off logging on either a

Handler or Logger object This level can be used when no logging is

desired and absolute performance is the goal A Logger or Handler objectset to the OFF level immediately returns when information logging is

attempted

ALL: The ALL level setting logs all levels of messages

Complementing these levels, the Logger object defines the following methods:

getLevel(): The getLevel() method returns a level object representing thecurrent level the Logger is set to log messages Messages of higher or equalpriority to the level are logged

setLevel(Level level): The setLevel() method sets the current level a

Logger object should log messages at Messages below the level are

discarded When the OFF level is specified, all messages are ignored

log(Level level, String message): The log() method logs a given message

at a given level Should the message be below the current Logger object'slevel setting, it is discarded For all of the allowed levels, self-named

convenience methods also exist: severe(), warning(), info(), config(),

fine(), finer(), and finest() All of the convenience methods take as aparameter a String representing the message to log Levels are implied

log(Level level, String message, Throwable throwable): The log() methodlogs a given message at a given level The LogRecord object published bythis method also includes the Throwable object specified as the throwableparameter

Using the preceding methods a Logger object can effectively log informationbased on arbitrary levels The common use of these levels is to safely log critical

Trang 37

information at all times while keeping warning and debugging informationaround only when developers need it The performance difference betweenlogging all information versus only the important information can be noticeableand it often makes sense to distinguish between the two.

Trang 38

java.util.logging package Normal logging schemes are usually inadequate;using System.out.println() method calls becomes inefficient as a projectgrows and is not easily maintained in the future Using ServletContext object's

as well as provide a Web interface for administrative use Listing 4-24 is theServletContextListener class

Trang 40

For the listener to be of much help it must be used by other code in the Webapplication First, let us create an administrative JSP for modifying the loggerduring runtime, as shown in Listing 4-26 The page will provide a method ofsetting the logger's current level and viewing the current log.

Ngày đăng: 26/03/2019, 17:12

TỪ KHÓA LIÊN QUAN

🧩 Sản phẩm bạn có thể quan tâm