The requested resource (/HTTP/1.1) is not available

linxinyidian 2011-03-19 07:44:55
编了个访问Tomcat的小程序,

package TestHttp;

import java.io.BufferedReader;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.io.*;


public class Test {

public static void main(String[] args) throws UnknownHostException, IOException {
String ss;

Socket s = new Socket("127.0.0.1", 8080);

OutputStream os = s.getOutputStream();

PrintWriter pw = new PrintWriter(os);

pw.println("GET /HTTP/1.1 ");
pw.println("Host:localhost");
pw.println("Content-type: text ml");
pw.println();
pw.flush();

BufferedReader bf = new BufferedReader(new InputStreamReader(s.getInputStream()));

while(( ss =bf.readLine())!=null) {
System.out.println(ss);
}

bf.close();
pw.close();
os.close();
s.close();

}
}

返回一些文本

<html><head><title>Apache Tomcat/7.0.11 - Error report</title><style><!--H1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} H2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} H3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} BODY {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} B {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} P {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;}A {color : black;}A.name {color : black;}HR {color : #525D76;}--></style> </head><body><h1>HTTP Status 404 - /HTTP/1.1</h1><HR size="1" noshade="noshade"><p><b>type</b> Status report</p><p><b>message</b> <u>/HTTP/1.1</u></p><p><b>description</b> <u>The requested resource (/HTTP/1.1) is not available.</u></p><HR size="1" noshade="noshade"><h3>Apache Tomcat/7.0.11</h3></body></html>

转为html格式,显示为 HTTP 404 异常
The requested resource (/HTTP/1.1) is not available.

我用的是Tomcat 7.0,不知什么原因产生此异常……


...全文
1116 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
Cary_诚 2011-10-12
  • 打赏
  • 举报
回复
pw.println("GET /HTTP/1.1 ");
第一个斜杠后面有个空格,写成pw.println("GET / HTTP/1.1 ");
不然会链接到127.0.0.1:8080/HTTP/1.1
sdk LCS/Telegraphics Wintab* Interface Specification 1.1: 16- and 32-bit API Reference By Rick Poyner Revised February 11, 2012 This specification was developed in response to a perceived need for a standardized programming inter-face to digitizing tablets, three dimensional position sensors, and other pointing devices by a group of lead-ing digitizer manufacturers and applications developers. The availability of drivers that support the features of the specification will simplify the process of developing Windows appli¬cation programs that in-corporate absolute coordinate input, and enhance the acceptance of ad¬vanced pointing de¬vices among users. This specification is intended to be an open standard, and as such the text and information contained herein may be freely used, copied, or distributed without compensation or licensing restrictions. This document is copyright 1991-2012 by LCS/Telegraphics.* Address questions and comments to: LCS/Telegraphics 150 Rogers St. Cambridge, MA 02142 (617)225-7970 (617)225-7969 FAX Compuserve: 76506,1676 Internet: wintab@pointing.com Note: sections marked with the “(1.1)” are new sections added for specification version 1.1. Sec-tions bearing the “(1.1 modified)” notation contain updated information for specification version 1.1. Version 1.1 Update Notation Conventions 1 1. Background Information 1 1.1. Features of Digitizers 1 1.2. The Windows Environment 1 2. Design Goals 2 2.1. User Control 2 2.2. Ease of Programming 2 2.3. Tablet Sharing 3 2.4. Tablet Feature Support 3 3. Design Concepts 3 3.1. Device Conventions 3 3.2. Device Information 4 3.3. Tablet Contexts 4 3.4. Event Packets 4 3.5. Tablet Managers 5 3.6. Extensions 5 3.7. Persistent Binding of Interface Features (1.1) 6 4. Interface Implementations 6 4.1. File and Module Conventions 6 4.2. Feature Support Options 6 5. Function Reference 7 5.1. Basic Functions 7 5.1.1. WTInfo 8 5.1.2. WTOpen 9 5.1.3. WTClose 10 5.1.4. WTPacketsGet 10 5.1.5. WTPacket 11 5.2. Visibility Functions 11 5.2.1. WTEnable 11 5.2.2. WTOverlap 12 5.3. Context Editing Functions 12 5.3.1. WTConfig 12 5.3.2. WTGet 13 5.3.3. WTSet (1.1 modified) 13 5.3.4. WTExtGet 14 5.3.5. WTExtSet 14 5.3.6. WTSave 15 5.3.7. WTRestore 15 5.4. Advanced Packet and Queue Functions 16 5.4.1. WTPacketsPeek 16 5.4.2. WTDataGet 17 5.4.3. WTDataPeek 17 5.4.4. WTQueuePackets (16-bit only) 18 5.4.5. WTQueuePacketsEx 18 5.4.6. WTQueueSizeGet 19 5.4.7. WTQueueSizeSet 19 5.5. Manager Handle Functions 19 5.5.1. WTMgrOpen 19 5.5.2. WTMgrClose 20 5.6. Manager Context Functions 20 5.6.1. WTMgrContextEnum 20 5.6.2. WTMgrContextOwner 21 5.6.3. WTMgrDefContext 22 5.6.4. WTMgrDefContextEx (1.1) 22 5.7. Manager Configuration Functions 23 5.7.1. WTMgrDeviceConfig 23 5.7.2. WTMgrConfigReplace (16-bit only) 24 5.7.3. WTMgrConfigReplaceEx 24 5.8. Manager Packet Hook Functions 25 5.8.1. WTMgrPacketHook (16-bit only) 26 5.8.2. WTMgrPacketHookEx 26 5.8.3. WTMgrPacketUnhook 29 5.8.4. WTMgrPacketHookDefProc (16-bit only) 30 5.8.5. WTMgrPacketHookNext 30 5.9. Manager Preference Data Functions 31 5.9.1. WTMgrExt 31 5.9.2. WTMgrCsrEnable 32 5.9.3. WTMgrCsrButtonMap 32 5.9.4. WTMgrCsrPressureBtnMarks (16-bit only) 33 5.9.5. WTMgrCsrPressureBtnMarksEx 33 5.9.6. WTMgrCsrPressureResponse 34 5.9.7. WTMgrCsrExt 35 6. Message Reference 36 6.1. Event Messages 36 6.1.1. WT_PACKET 36 6.1.2. WT_CSRCHANGE (1.1) 37 6.2. Context Messages 37 6.2.1. WT_CTXOPEN 37 6.2.2. WT_CTXCLOSE 37 6.2.3. WT_CTXUPDATE 38 6.2.4. WT_CTXOVERLAP 38 6.2.5. WT_PROXIMITY 38 6.3. Information Change Messages 39 6.3.1. WT_INFOCHANGE 39 7. Data Reference 39 7.1. Common Data Types (1.1 modified) 39 7.2. Information Data Structures 41 7.2.1. AXIS 41 7.2.2. Information Categories and Indices (1.1 modified) 42 7.3. Context Data Structures 50 7.3.1. LOGCONTEXT (1.1 modified) 50 7.4. Event Data Structures 55 7.4.1. PACKET (1.1 modified) 55 7.4.2. ORIENTATION 57 7.4.3. ROTATION (1.1) 58 Appendix A. Using PKTDEF.H 59 Appendix B. Extension Definitions 60 B.1. Extensions Programming 60 B.2. Out of Bounds Tracking 61 OBT Programming 61 Information Category 61 Turning OBT On and Off 61 B.3. Function Keys 62 FKEYS Programming 62 Information Category 62 B.4. Tilt 62 TILT Programming 63 Information Category 63 B.5. Cursor Mask 63 CSRMASK Programming 64 Information Category 64 B.6. Extended Button Masks 64 XBTNMASK Programming 64 Information Category 65 VERSION 1.1 UPDATE NOTATION CONVENTIONS Sections marked with the “(1.1)” are new sections added for specification version 1.1. Sections bearing the “(1.1 modified)” notation contain updated information for specification version 1.1. The “(1.1)” notation also marks the definitions of new functions, messages, and data structures. The nota-tion “1.1:” marks new text or commentaries explaining new functionality added to existing features. 1 BACKGROUND INFORMATION This document describes a programming interface for using digitizing tablets and other advanced pointing de¬vices with Microsoft Windows Version 3.0 and above. The design presented here is based on the input of numerous professionals from the pointing device manufacturing and Windows soft¬ware development industries. In this document, the words "tablet" and "digitizer" are used interchange¬ably to mean all absolute point¬ing or digitizing devices that can be made to work with this interface. The definition is not lim¬ited to de¬vices that use a physical tablet. In fact, this specification can support de¬vices that combine rela¬tive and absolute pointing as well as purely relative devices. The following sections describe features of tablets and of the Windows environment that helped mo¬tivate the design. 1.1 Features of Digitizers Digitizing tablets present several problems to device interface authors. • Many tablets have a very high report rate. • Many tablets have many configurable features and types of input information. • Tablets often control the system cursor, provide additional digitizing input, and provide template or macro functions. 1.2 The Windows Environment Programming for tablets in the Windows environment presents additional problems. • Multitasking means multiple applications may have to share the tablet. • The tablet must also be able to control the system cursor and/or the pen (in Pen Windows). • The tablet must work with legacy applications, and with applications written to take advan¬tage of tablet services. • The tablet driver must add minimal speed and memory overhead, so as many applications as possible can run as efficiently as possible. • The user should be able to control how applications use the tablet. The user interface must be ef-ficient, consistent, and customizable. 2 DESIGN GOALS While the tablet interface design must address the technical problems stated above, it must also be useful to the programmers who will write tablet programs, and ultimately, to the tablet users. Four design goals will help clarify these needs, and provide some criteria for evaluating the interface speci¬fication. The goals are user control, ease of programming, tablet sharing, and tablet feature support. 2.1 User Control The user should be able to use and control the tablet in as natural and easy a manner as possible. The user's preferences should take precedence over application requests, where possible. Here are questions to ask when thinking about user control as a design goal: • Can the user understand how applications use the tablet? • Is the interface for controlling tablet functions natural and unobtrusive? • Is the user allowed to change things that help to customize the work environment, but pre¬vented from changing things over which applications must have control? 2.2 Ease of Programming Programming is easiest when the amount of knowledge and effort required matches the task at hand. Writing simple programs should require only a few lines of code and a minimal understanding of the en-vironment. On the other hand, more advanced features and functions should be available to those who need them. The interface should accommodate three kinds of programmers: those who wish to write sim-ple tablet programs, programmers who wish to write complex applications that take full ad¬vantage of tab-let capabilities, and programmers who wish to provide tablet device control features. In addition, the inter-face should accommodate programmers in as many different programming lan¬guages, situations, and en-vironments as possible. Questions to ask when thinking about ease of programming include: • How hard is it to learn the interface and write a simple program that uses tablet input? • Can programmers of complex applications control the features they need? • Are more powerful tablet device control features available? • Can the interface be used in different programming environments? • Is the interface logical, consistent, and robust? 2.3 Tablet Sharing In the Windows environment, multiple applications that use the tablet may be running at once. Each ap-plication will require different services. Applications must be able to get the services they need without getting in each others' way. Questions to ask when thinking about tablet sharing include: • Can tablet applications use the tablet features they need, independent of other applications? • Does the interface prevent a rogue application from "hijacking" the tablet, or causing dead¬locks? • Does the sharing architecture promote efficiency? 2.4 Tablet Feature Support The interface gives standard access to as many features as possible, while leaving room for future ex¬ten-sions and vendor-specific customizations. Applications should be able to get the tablet informa¬tion and services they want, just the way they want them. Users should be able to use the tablet to set up an effi-cient, comfortable work environment. Questions to ask when thinking about tablet feature support include: • Does the interface provide the features applications need? Are any commonly available fea¬tures not supported? • Does the interface provide what users need? Is anything missing? • Are future extensions possible and fairly easy? • Are vendor-specific extensions possible? 3 DESIGN CONCEPTS The proposed interface design depends on several fundamental concepts. Devices and cursor types de-scribe physical hardware configurations. The interface publishes read-only information through a single information interface. Applications interact with the interface by setting up tablet contexts and consuming event packets. Applications may assume interface and hardware control functions by be¬coming tablet managers. The interface provides explicit support for future extensions. 3.1 Device Conventions The interface provides access to one or more devices that produce pointing input. Devices sup¬ported by this interface have some common characteristics. The device must define an absolute or relative coordi-nate space in at least two dimensions for which it can return position data. The device must have a point-ing ap¬para¬tus or method (such as a stylus, or a finger touching a touch pad), called the cursor, that de¬fines the current position. The cursor must be able to return at least one bit of additional state (via a but¬ton, touching a digitizing surface, etc.). Devices may have multiple cursor types that have different physical configurations, or that have differ¬ent numbers of buttons, or return auxiliary information, such as pressure information. Cursor types may also describe different optional hardware configurations. The interface defines a standard orientation for reporting device native coordinates. When the user is viewing the device in its normal position, the coordinate origin will be at the lower left of the device. The coordinate system will be right-handed, that is, the positive x axis points from left to right, and the posi¬tive y axis points either upward or away from the user. The z axis, if supported, points either to¬ward the user or upward. For devices that lay flat on a table top, the x-y plane will be horizontal and the z axis will point upward. For devices that are oriented vertically (for example, a touch screen on a conventional dis¬play), the x-y plane will be vertical, and the z axis will point toward the user. 3.2 Device Information Any program can get descriptive information about the tablet via the WTInfo function. The interface specifies certain information that must be available, but allows new implementations to add new types of information. The basic information includes device identifiers, version numbers, and overall ca¬pabilities. The information items are organized by category and index numbers. The combination of a category and index specifies a single information data item, which may be a scalar value, string, structure, or array. Applica¬tions may retrieve single items or whole categories at once. Some categories are multiplexed. A single category code represents the first of a group of identically in-dexed categories, one for each of a set of similar objects. Multiplexed categories in¬clude those for devices and cur¬sor types. One constructs the category number by adding the defined cate¬gory code to a zero-based device or cursor identification number. The information is read-only for normal tablet applications. Some information items may change during the course of a Windows session; tablet applications receive messages notifying them of changes in tablet information. 3.3 Tablet Contexts Tablet contexts play a central role in the interface; they are the objects that applications use to specify their use of the tablet. Con¬texts include not only the physical area of the tablet that the application will use, but also information about the type, con¬tents, and delivery method for tablet events, as well as other information. Tablet contexts are somewhat analo¬gous to display contexts in the GDI interface model; they contain context information about a spe¬cific application's use of the tablet. An application can open more than one context, but most only need one. Applications can customize their contexts, or they can open a context using a default context specification that is always available. The WTInfo function provides access to the default context specification. Opening a context requires a window handle. The window handle becomes the context's owner and will receive any window messages associated with the context. Contexts are remotely similar to screen windows in that they can physically overlap. The tablet inter¬face uses a combination of context overlap order and context attributes to decide which context will process a given event. The topmost context in the overlap order whose input context encompasses the event, and whose event masks select the event, will process the event. (Note that the notion of overlap order is sepa-rate from the notion of the physical z dimension.) Tablet managers (described below) provide a way to modify and overlap contexts. 3.4 Event Packets Tablet contexts generate and report tablet activity via event packets. Applications can control how they receive events, which events they receive, and what information they contain. Applications may receive events either by polling, or via Windows messages. • Polling: Any application that has opened a context can call the WTPacketsGet function to get the next state of the tablet for that context. • Window Messages: Applications that request messages will receive the WT_PACKET mes¬sage (described below), which indicates that something happened in the context and provides a refer-ence to more information. Applications can control which events they receive by using event masks. For example, some appli¬ca¬tions may only need to know when a button is pressed, while others may need to receive an event every time the cursor moves. Tablet context event masks implement this type of control. Applications can control the contents of the event packets they receive. Some tablets can return data that many applications will not need, like button pressure and three dimensional position and orien¬tation in-formation. The context object provides a way of specifying which data items the appli¬cation needs. This allows the driver to improve the efficiency of packet delivery to applications that only need a few items per packet. Packets are stored in context-specific packet queues and retrieved by explicit function calls. The interface provides ways to peek at and get packets, to query the size and contents of the queue, and to re-size the queue. 3.5 Tablet Managers The interface provides functions for tablet management. An application can become a tablet manager by opening a tablet manager handle. This handle allows the manager access to spe¬cial functions. These man-agement functions allow the application to arrange, overlap, and modify tablet contexts. Man¬agers may also perform other functions, such as changing default values used by applica¬tions, chang¬ing ergo¬nomic, preference, and configuration settings, controlling tablet behavior with non-tablet aware applica¬tions, modi¬fy¬ing user dialogs, and recording and playing back tablet packets. Opening a manager handle re¬quires a window handle. The window becomes a manager window and receives window messages about interface and con¬text activity. 3.6 Extensions The interface allows implementations to define additional features called extensions. Extensions can be made available to new applications without the need to modify ex¬isting applications. Extensions are sup-ported through the information categories, through the flexible definition of packets, and through special context and manager functions. Designing an extension involves defining the meaning and behavior of the extension packet and/or prefer-ence data, filling in the information category, defining the extension's interface with the special functions, and possibly defining additional functions to support the extension. Each extension will be assigned a unique tag for identification. Not all implementations will support all extensions. A multiplexed information category contains descriptive data about extensions. Note that applica¬tions must find their extensions by iterating through the categories and matching tags. While tags are fixed across all implementations, category numbers may vary among implementations. 3.7 Persistent Binding of Interface Features (1.1) The interface provides access to many of its features using consecutive numeric indices whose value is not guaranteed from session to session. However, sufficient information is provided to create unique identifi¬ers for devices, cursors, and interface extensions. Devices should be uniquely identified by the contents of their name strings. If multiple identical devices are present, implementation providers should provide unique, persistent id strings to the extent possible. Identical devices that return unique serial numbers are ideal. If supported by the hardware, cursors also may have a physical cursor id that uniquely identifies the cursor in a persistent and stable manner. Interface extensions are uniquely identified by their tag. 4 INTERFACE IMPLEMENTATIONS Implementations of this interface usually support one specific device, a class of similar devices, or a com-mon combination of devices. The following sections discuss guidelines for implementations. 4.1 File and Module Conventions For 16-bit implementations, the interface functions, and any additional vendor- or device-specific func-tions, reside in a dynamic link library with the file name "WINTAB.DLL" and module name "WINTAB"; 32-bit implementations use the file name "WINTAB32.DLL" and module name "WINTAB32." Any other file or module con¬ventions are implementation specific. Implementations may include other library mod-ules or data files as necessary. Installation processes are likewise implementa¬tion-specific. Wintab programs written in the C language require two header files. WINTAB.H contains definitions of all of the functions, constants, and fixed data types. PKTDEF.H contains a parameterized definition of the PACKET data structure, that can be tailored to fit the application. The Wintab Programmer's Kit con¬tains these and other files necessary for Wintab programming, plus several example programs with C-lan¬guage source files. The Wintab Programmer's Kit is available from the author. 4.2 Feature Support Options Some features of the interface are optional and may be left out by some implementations. Support of defined data items other than x, y, and buttons is optional. Many devices only report x, y, and button information. Support of system-cursor contexts is optional. This option relieves implementations of replacing the sys¬tem mouse driver in Windows versions before 3.1. Support of Pen Windows contexts is optional. Not all systems will have the Pen Windows hardware and software necessary. Support of external tablet manager applications is optional, and the number of manager handles is imple-mentation-dependent. However, the manager functions should be present in all implementa¬tions, return¬ing appropriate failure codes if not fully implemented. An implementation may provide context- and hardware-management support internally only, if desired. On the other hand, providing the external man-ager interface may relieve the implementation of a considerable amount of user in¬terface code, and make improvements to the manager interface easier to implement and distribute later. Support of extension data items is optional. Most extensions will be geared to unusual hardware features. 5 FUNCTION REFERENCE All tablet function names have the prefix "WT" and have attributes equivalent to WINAPI. Applica¬tions gain access to the tablet interface functions through a dynamic-link library with standard file and module names, as defined in the previous section. Applications may link to the functions by using the Windows functions LoadLibrary, FreeLibrary, and GetProcAddress, or use an import library. Specific to 32-bit Wintab: The functions WTInfo, WTOpen, WTGet, and WTSet have both ANSI and Unicode versions, using the same ANSI/Unicode porting conventions used in the Win32 API. Five non-portable functions, WTQueuePackets, WTMgrCsrPressureBtnMarks, WTMgrConfigReplace, WTMgrPacketHook, and WTMgrPacketHookDefProc are replaced by new portable functions WTQueuePacketsEx, WTMgrCsrPressureBtnMarksEx, WTMgrConfigReplaceEx, WTMgrPack-etHookEx, WTMgrPacketUnhook, and WTMgrPacketHookNext. WTMgrConfigReplaceEx and WTMgrPacketHookEx have both ANSI and Unicode versions. Table 5.1. Ordinal Function Numbers for Dynamic Linking Ordinal numbers for dynamic linking are defined in the table below. Where two ordinal entries appear, the first entry identifies the 16-bit and 32-bit ANSI versions of the function. The second entry identifies the 32-bit Unicode version. Function Name Ordinal Function Name Ordinal WTInfo 20, 1020 WTMgrOpen 100 WTOpen 21, 1021 WTMgrClose 101 WTClose 22 WTMgrContextEnum 120 WTPacketsGet 23 WTMgrContextOwner 121 WTPacket 24 WTMgrDefContext 122 WTEnable 40 WTMgrDefContextEx (1.1) 206 WTOverlap 41 WTMgrDeviceConfig 140 WTConfig 60 WTMgrConfigReplace 141 WTGet 61, 1061 WTMgrConfigReplaceEx 202, 1202 WTSet 62, 1062 WTMgrPacketHook 160 WTExtGet 63 WTMgrPacketHookEx 203, 1203 WTExtSet 64 WTMgrPacketUnhook 204 WTSave 65 WTMgrPacketHookDefProc 161 WTRestore 66 WTMgrPacketHookNext 205 WTPacketsPeek 80 WTMgrExt 180 WTDataGet 81 WTMgrCsrEnable 181 WTDataPeek 82 WTMgrCsrButtonMap 182 WTQueuePackets 83 WTMgrCsrPressureBtnMarks 183 WTQueuePacketsEx 200 WTMgrCsrPressureBtnMarksEx 201 WTQueueSizeGet 84 WTMgrCsrPressureResponse 184 WTQueueSizeSet 85 WTMgrCsrExt 185 5.1 Basic Functions The functions in the following section will be used by most tablet-aware applications. They include getting interface and device information, opening and closing contexts, and retrieving packets by polling or via Windows messages. 5.1.1 WTInfo Syntax UINT WTInfo(wCategory, nIndex, lpOutput) This function returns global information about the interface in an application-sup-plied buffer. Different types of information are specified by different index argu-ments. Applications use this function to receive information about tablet coordi-nates, physical dimensions, capabilities, and cursor types. Parameter Type/Description wCategory UINT Identifies the category from which information is being re-quested. nIndex UINT Identifies which information is being requested from within the category. lpOutput LPVOID Points to a buffer to hold the requested information. Return Value The return value specifies the size of the returned information in bytes. If the infor-mation is not supported, the function returns zero. If a tablet is not physi¬cally pres-ent, this function always returns zero. Comments Several important categories of information are available through this function. First, the function provides identification information, including specification and software version numbers, and tablet vendor and model information. Sec¬ond, the function provides general capability information, including dimensions, resolutions, optional features, and cursor types. Third, the function provides categories that give defaults for all tablet context attributes. Finally, the func¬tion may provide any other implementation- or vendor-specific information cat¬egories necessary. The information returned by this function is subject to change during a Win¬dows session. Applications cannot change the information returned here, but tablet man-ager applications or hardware changes or errors can. Applications can respond to information changes by fielding the WT_INFOCHANGE message. The parameters of the message indicate which information has changed. If the wCategory argument is zero, the function copies no data to the output buffer, but returns the size in bytes of the buffer necessary to hold the largest complete category. If the nIndex argument is zero, the function returns all of the information entries in the category in a single data structure. If the lpOutput argument is NULL, the function just returns the required buffer size. See Also Category and index definitions in tables 7.3 through 7.9, and the WT_INFOCHANGE message in section 6.3.1. 5.1.2 WTOpen Syntax HCTX WTOpen(hWnd, lpLogCtx, fEnable) This function establishes an active context on the tablet. On successful comple¬tion of this function, the application may begin receiving tablet events via mes¬sages (if they were requested), and may use the handle returned to poll the con¬text, or to per-form other context-related functions. Parameter Type/Description hWnd HWND Identifies the window that owns the tablet context, and receives messages from the context. lpLogCtx LPLOGCONTEXT Points to an application-provided LOGCONTEXT data structure describing the context to be opened. fEnable BOOL Specifies whether the new context will immediately begin processing input data. Return Value The return value identifies the new context. It is NULL if the context is not opened. Comments Opening a new context allows the application to receive tablet input or creates a context that controls the system cursor or Pen Windows pen. The owning window (and all manager windows) will immediately receive a WT_CTXOPEN message when the context has been opened. If the fEnable argument is zero, the context will be created, but will not process input. The context can be enabled using the WTEnable function. If tablet event messages were requested in the context specification, the owning window will receive them. The application can control the message numbers used the lcMsgBase field of the LOGCONTEXT structure. The window that owns the new context will receive context and information change messages even if event messages were not requested. It is not necessary to handle these in many cases, but some applications may wish to do so. The newly opened tablet context will be placed on the top of the context overlap or-der. Invalid or out-of-range attribute values in the logical context structure will ei¬ther be validated, or cause the open to fail, depending on the attributes involved. Upon a successful return from the function, the context specification pointed to by lpLogCtx will contain the validated values. See Also The WTEnable function in section 5.2.1, the LOGCONTEXT data structure in section 7.3.1, and the context and infor¬mation change messages in sections 6.2 and 6.3. 5.1.3 WTClose Syntax BOOL WTClose(hCtx) This function closes and destroys the tablet context object. Parameter Type/Description hCtx HCTX Identifies the context to be closed. Return Value The function returns a non-zero value if the context was valid and was destroyed. Otherwise, it returns zero. Comments After a call to this function, the passed handle is no longer valid. The owning win¬dow (and all manager windows) will receive a WT_CTXCLOSE message when the context has been closed. See Also The WTOpen function in section 5.1.2. 5.1.4 WTPacketsGet Syntax int WTPacketsGet(hCtx, cMaxPkts, lpPkts) This function copies the next cMaxPkts events from the packet queue of context hCtx to the passed lpPkts buffer and removes them from the queue. Parameter Type/Description hCtx HCTX Identifies the context whose packets are being returned. cMaxPkts int Specifies the maximum number of packets to return. lpPkts LPVOID Points to a buffer to receive the event packets. Return Value The return value is the number of packets copied in the buffer. Comments The exact structure of the returned packet is determined by the packet infor¬mation that was requested when the context was opened. The buffer pointed to by lpPkts must be at least cMaxPkts * sizeof(PACKET) bytes long to prevent overflow. Applications may flush packets from the queue by calling this function with a NULL lpPkt argument. See Also The WTPacketsPeek function in section 5.4.1, and the descriptions of the LOGCONTEXT (section 7.3.1) and PACKET (section 7.4.1) data structures. 5.1.5 WTPacket Syntax BOOL WTPacket(hCtx, wSerial, lpPkt) This function fills in the passed lpPkt buffer with the context event packet having the specified serial number. The returned packet and any older packets are removed from the context's internal queue. Parameter Type/Description hCtx HCTX Identifies the context whose packets are being returned. wSerial UINT Serial number of the tablet event to return. lpPkt LPVOID Points to a buffer to receive the event packet. Return Value The return value is non-zero if the specified packet was found and returned. It is zero if the specified packet was not found in the queue. Comments The exact structure of the returned packet is determined by the packet infor¬mation that was requested when the context was opened. The buffer pointed to by lpPkts must be at least sizeof(PACKET) bytes long to pre-vent overflow. Applications may flush packets from the queue by calling this function with a NULL lpPkts argument. See Also The descriptions of the LOGCONTEXT (section 7.3.1) and PACKET (section 7.4.1) data structures. 5.2 Visibility Functions The functions in this section allow applications to control contexts' visibility, whether or not they are pro-cessing input, and their overlap order. 5.2.1 WTEnable Syntax BOOL WTEnable(hCtx, fEnable) This function enables or disables a tablet context, temporarily turning on or off the processing of packets. Parameter Type/Description hCtx HCTX Identifies the context to be enabled or disabled. fEnable BOOL Specifies enabling if non-zero, disabling if zero. Return Value The function returns a non-zero value if the enable or disable request was satis¬fied, zero otherwise. Comments Calls to this function to enable an already enabled context, or to disable an al¬ready disabled context will return a non-zero value, but otherwise do nothing. The context’s packet queue is flushed on disable. Applications can determine whether a context is currently enabled by using the WTGet function and examining the lcStatus field of the LOGCONTEXT struc¬ture. See Also The WTGet function in section 5.3.2, and the LOGCONTEXT structure in sec¬tion 7.3.1. 5.2.2 WTOverlap Syntax BOOL WTOverlap(hCtx, fToTop) This function sends a tablet context to the top or bottom of the order of over¬lapping tablet contexts. Parameter Type/Description hCtx HCTX Identifies the context to move within the overlap order. fToTop BOOL Specifies sending the context to the top of the overlap or-der if non-zero, or to the bottom if zero. Return Value The function returns non-zero if successful, zero otherwise. Comments Tablet contexts' input areas are allowed to overlap. The tablet interface main¬tains an overlap order that helps determine which context will process a given event. The topmost context in the overlap order whose input context encom¬passes the event, and whose event masks select the event will process the event. This function is useful for getting access to input events when the application's con-text is overlapped by other contexts. The function will fail only if the context argument is invalid. 5.3 Context Editing Functions This group of functions allows applications to edit, save, and restore contexts. 5.3.1 WTConfig Syntax BOOL WTConfig(hCtx, hWnd) This function prompts the user for changes to the passed context via a dialog box. Parameter Type/Description hCtx HCTX Identifies the context that the user will modify via the dialog box. hWnd HWND Identifies the window that will be the parent window of the dialog box. Return Value The function returns a non-zero value if the tablet context was changed, zero oth-erwise. Comments Tablet applications can use this function to let the user choose context attributes that the application doesn't need to control. Applications can control the editing of con¬text attributes via the lcLocks logical context structure member. Applications should consider providing access to this function through a menu item or command. See Also The LOGCONTEXT structure in section 7.3.1 and the context lock values in table 7.13. 5.3.2 WTGet Syntax BOOL WTGet(hCtx, lpLogCtx) This function fills the passed structure with the current context attributes for the passed handle. Parameter Type/Description hCtx HCTX Identifies the context whose attributes are to be copied. lpLogCtx LPLOGCONTEXT Points to a LOGCONTEXT data structure to which the context attributes are to be copied. Return Value The function returns a non-zero value if the data is retrieved successfully. Oth¬er¬wise, it returns zero. See Also The LOGCONTEXT structure in section 7.3.1. 5.3.3 WTSet (1.1 modified) Syntax BOOL WTSet(hCtx, lpLogCtx) This function allows some of the context's attributes to be changed on the fly. Parameter Type/Description hCtx HCTX Identifies the context whose attributes are being changed. lpLogCtx LPLOGCONTEXT Points to a LOGCONTEXT data structure containing the new context attributes. Return Value The function returns a non-zero value if the context was changed to match the passed context specification; it returns zero if any of the requested changes could not be made. Comments If this function is called by the task or process that owns the context, any context attribute may be changed. Otherwise, the function can change attributes that do not affect the format or meaning of the context's event packets and that were not speci-fied as locked when the context was opened. Context lock values can only be changed by the context’s owner. 1.1: If the hCtx argument is a default context handle returned from WTMgrDef-Context or WTMgrDefContextEx, and the lpLogCtx argument is WTP_LPDEFAULT, the default context will be reset to its initial factory default values. See Also The LOGCONTEXT structure in section 7.3.1 and the context lock values in table 7.13. 5.3.4 WTExtGet Syntax BOOL WTExtGet(hCtx, wExt, lpData) This function retrieves any context-specific data for an extension. Parameter Type/Description hCtx HCTX Identifies the context whose extension attributes are being retrieved. wExt UINT Identifies the extension tag for which context-specific data is being retrieved. lpData LPVOID Points to a buffer to hold the retrieved data. Return Value The function returns a non-zero value if the data is retrieved successfully. Oth¬er¬wise, it returns zero. See Also The extension definitions in Appendix B. 5.3.5 WTExtSet Syntax BOOL WTExtSet(hCtx, wExt, lpData) This function sets any context-specific data for an extension. Parameter Type/Description hCtx HCTX Identifies the context whose extension attributes are being modified. wExt UINT Identifies the extension tag for which context-specific data is being modified. lpData LPVOID Points to the new data. Return Value The function returns a non-zero value if the data is modified successfully. Oth¬er¬wise, it returns zero. Comments Extensions may forbid their context-specific data to be changed during the life¬time of a context. For such extensions, calls to this function would always fail. Extensions may also limit context data editing to the task of the owning window, as with the context locks. See Also The extension definitions in Appendix B, the LOGCONTEXT data structure in section 7.3.1 and the context locking values in table 7.13. 5.3.6 WTSave Syntax BOOL WTSave(hCtx, lpSaveInfo) This function fills the passed buffer with binary save information that can be used to restore the equivalent context in a subsequent Windows session. Parameter Type/Description hCtx HCTX Identifies the context that is being saved. lpSaveInfo LPVOID Points to a buffer to contain the save information. Return Value The function returns non-zero if the save information is successfully retrieved. Oth-erwise, it returns zero. Comments The size of the save information buffer can be determined by calling the WTInfo function with category WTI_INTERFACE, index IFC_CTXSAVESIZE. The save information is returned in a private binary data format. Applications should store the information unmodified and recreate the context by passing the save information to the WTRestore function. Using WTSave and WTRestore allows applications to easily save and restore ex-tension data bound to contexts. See Also The WTRestore function in section 5.3.7. 5.3.7 WTRestore Syntax HCTX WTRestore(hWnd, lpSaveInfo, fEnable) This function creates a tablet context from save information returned from the WTSave function. Parameter Type/Description hWnd HWND Identifies the window that owns the tablet context, and receives messages from the context. lpSaveInfo LPVOID Points to a buffer containing save information. fEnable BOOL Specifies whether the new context will immediately begin processing input data. Return Value The function returns a valid context handle if successful. If a context equivalent to the save information could not be created, the function returns NULL. Comments The save information is in a private binary data format. Applications should only pass save information retrieved by the WTSave function. This function is much like WTOpen, except that it uses save in¬formation for input instead of a logical context. In particular, it will generate a WT_CTXOPEN mes¬sage for the new context. See Also The WTOpen function in section 5.1.2, the WTSave function in section 5.3.6, and the WT_CTXOPEN message in section 6.2.1. 5.4 Advanced Packet and Queue Functions These functions provide advanced packet retrieval and queue manipulation. The packet retrieval functions require the application to provide a packet output buffer. To prevent overflow, the buffer must be large enough to hold the requested number of packets from the specified context. It is up to the caller to deter¬mine the packet size (by interrogating the context, if necessary), and to allocate a large enough buffer. Ap¬plications may flush packets from the queue by passing a NULL buffer pointer. 5.4.1 WTPacketsPeek Syntax int WTPacketsPeek(hCtx, cMaxPkts, lpPkts) This function copies the next cMaxPkts events from the packet queue of context hCtx to the passed lpPkts buffer without removing them from the queue. Parameter Type/Description hCtx HCTX Identifies the context whose packets are being read. cMaxPkts int Specifies the maximum number of packets to return. lpPkts LPVOID Points to a buffer to receive the event packets. Return Value The return value is the number of packets copied in the buffer. Comments The buffer pointed to by lpPkts must be at least cMaxPkts * sizeof(PACKET) bytes long to prevent overflow. See Also the WTPacketsGet function in section 5.1.4. 5.4.2 WTDataGet Syntax int WTDataGet(hCtx, wBegin, wEnd, cMaxPkts, lpPkts, lpNPkts) This function copies all packets with serial numbers between wBegin and wEnd in-clusive from the context's queue to the passed buffer and removes them from the queue. Parameter Type/Description hCtx HCTX Identifies the context whose packets are being returned. wBegin UINT Serial number of the oldest tablet event to return. wEnd UINT Serial number of the newest tablet event to return. cMaxPkts int Specifies the maximum number of packets to return. lpPkts LPVOID Points to a buffer to receive the event packets. lpNPkts LPINT Points to an integer to receive the number of packets ac-tually copied. Return Value The return value is the total number of packets found in the queue between wBegin and wEnd. Comments The buffer pointed to by lpPkts must be at least cMaxPkts * sizeof(PACKET) bytes long to prevent overflow. See Also The WTDataPeek function in section 5.4.3, and the WTQueuePacketsEx function in section 5.4.5. 5.4.3 WTDataPeek Syntax int WTDataPeek(hCtx, wBegin, wEnd, cMaxPkts, lpPkts, lpNPkts) This function copies all packets with serial numbers between wBegin and wEnd in-clusive, from the context's queue to the passed buffer without removing them from the queue. Parameter Type/Description hCtx HCTX Identifies the context whose packets are being read. wBegin UINT Serial number of the oldest tablet event to return. wEnd UINT Serial number of the newest tablet event to return. cMaxPkts int Specifies the maximum number of packets to return. lpPkts LPVOID Points to a buffer to receive the event packets. lpNPkts LPINT Points to an integer to receive the number of packets ac-tually copied. Return Value The return value is the total number of packets found in the queue between wBegin and wEnd. Comments The buffer pointed to by lpPkts must be at least cMaxPkts * sizeof(PACKET) bytes long to prevent overflow. See Also The WTDataGet function in section 5.4.2, and the WTQueuePacketsEx function in section 5.4.5. 5.4.4 WTQueuePackets (16-bit only) Syntax DWORD WTQueuePackets(hCtx) This function returns the serial numbers of the oldest and newest packets cur¬rently in the queue. Parameter Type/Description hCtx HCTX Identifies the context whose queue is being queried. Return Value The high word of the return value contains the newest packet's serial number; the low word contains the oldest. Comments This function is non-portable and is superseded by WTQueuePacketsEx. See Also The WTQueuePacketsEx function in section 5.4.5. 5.4.5 WTQueuePacketsEx Syntax BOOL WTQueuePacketsEx(hCtx, lpOld, lpNew) This function returns the serial numbers of the oldest and newest packets cur¬rently in the queue. Parameter Type/Description hCtx HCTX Identifies the context whose queue is being queried. lpOld UINT FAR * Points to an unsigned integer to receive the oldest packet's serial number. lpNew UINT FAR * Points to an unsigned integer to receive the newest packet's serial number. Return Value The function returns non-zero if successful, zero otherwise. 5.4.6 WTQueueSizeGet Syntax int WTQueueSizeGet(hCtx) This function returns the number of packets the context's queue can hold. Parameter Type/Description hCtx HCTX Identifies the context whose queue size is being re¬turned. Return Value The return value is the number of packet the queue can hold. See Also The WTQueueSizeSet function in section 5.4.7. 5.4.7 WTQueueSizeSet Syntax BOOL WTQueueSizeSet(hCtx, nPkts) This function attempts to change the context's queue size to the value specified in nPkts. Parameter Type/Description hCtx HCTX Identifies the context whose queue size is being set. nPkts int Specifies the requested queue size. Return Value The return value is non-zero if the queue size was successfully changed. Other¬wise, it is zero. Comments If the return value is zero, the context has no queue because the function deletes the original queue before attempting to create a new one. The application must continue calling the function with a smaller queue size until the function returns a non-zero value. See Also The WTQueueSizeGet function in section 5.4.6. 5.5 Manager Handle Functions The functions described in this and subsequent sections are for use by tablet manager applications. The functions of this section create and destroy manager handles. These handles allow the interface code to limit the degree of simultaneous access to the powerful manager functions. Also, opening a manager handle lets the application receive messages about tablet interface activity. 5.5.1 WTMgrOpen Syntax HMGR WTMgrOpen(hWnd, wMsgBase) This function opens a tablet manager handle for use by tablet manager and con¬figu-ration applications. This handle is required to call the tablet management func¬tions. Parameter Type/Description hWnd HWND Identifies the window which owns the manager handle. wMsgBase UINT Specifies the message base number to use when notifying the manager window. Return Value The function returns a manager handle if successful, otherwise it returns NULL. Comments While the manager handle is open, the manager window will receive context mes-sages from all tablet contexts. Manager windows also receive information change messages. The number of manager handles available is interface implementation-dependent, and can be determined by calling the WTInfo function with category WTI_INTERFACE and index IFC_NMANAGERS. See Also The WTInfo function in section 5.1.1, the WTMgrClose function in section 5.5.2, the description of message base numbers in section 6 and the context and in¬for¬ma-tion change messages in sections 6.2 and 6.3. 5.5.2 WTMgrClose Syntax BOOL WTMgrClose(hMgr) This function closes a tablet manager handle. After this function returns, the passed manager handle is no longer valid. Parameter Type/Description hMgr HMGR Identifies the manager handle to close. Return Value The function returns non-zero if the handle was valid; otherwise, it returns zero. 5.6 Manager Context Functions These functions provide access to all open contexts and their owners, and allow changing context de¬faults. Only tablet managers are allowed to manipulate tablet contexts belonging to other applica¬tions. 5.6.1 WTMgrContextEnum Syntax BOOL WTMgrContextEnum(hMgr, lpEnumFunc, lParam) This function enumerates all tablet context handles by passing the handle of each context, in turn, to the callback function pointed to by the lpEnumFunc pa¬rameter. The enumeration terminates when the callback function returns zero. Parameter Type/Description hMgr HMGR Is the valid manager handle that identifies the caller as a manager application. lpEnumFunc WTENUMPROC Is the procedure-instance address of the call-back function. See the following "Comments" section for details. lParam LPARAM Specifies the value to be passed to the callback func-tion for the application's use. Return Value The return value specifies the outcome of the function. It is non-zero if all con¬texts have been enumerated. Otherwise, it is zero. Comments The address passed as the lpEnumFunc parameter must be created by using the MakeProcInstance function. The callback function must have attributes equivalent to WINAPI. The callback function must have the following form: Callback BOOL WINAPI EnumFunc(hCtx, lParam) HCTX hCtx; LPARAM lParam; EnumFunc is a place holder for the application-supplied function name. The actual name must be exported by including it in an EXPORTS statement in the applica-tion's module-definition file. Parameter Description hCtx Identifies the context. lParam Specifies the 32-bit argument of the WTMgrContextEnum func-tion. Return Value The function must return a non-zero value to continue enumeration, or zero to stop it. 5.6.2 WTMgrContextOwner Syntax HWND WTMgrContextOwner(hMgr, hCtx) This function returns the handle of the window that owns a tablet context. Parameter Type/Description hMgr HMGR Is the valid manager handle that identifies the caller as a manager application. hCtx HCTX Identifies the context whose owner is to be returned. Return Value The function returns the context owner's window handle if the passed arguments are valid. Otherwise, it returns NULL. Comments This function allows the tablet manager to coordinate tablet context manage¬ment with the states of the context-owning windows. 5.6.3 WTMgrDefContext Syntax HCTX WTMgrDefContext(hMgr, fSystem) This function retrieves a context handle that allows setting values for the current default digit¬izing or system context. Parameter Type/Description hMgr HMGR Is the valid manager handle that identifies the caller as a manager application. fSystem BOOL Specifies retrieval of the default system context if non-zero, or the default digitizing context if zero. Return Value The return value is the context handle for the specified default context, or NULL if the arguments were invalid. Comments The default digitizing context is the context whose attributes are returned by the WTInfo function WTI_DEFCONTEXT category. The default system context is the context whose attributes are returned by the WTInfo function WTI_DEFSYSCTX category. Editing operations on the retrieved handles will fail if the new default contexts do not meet certain requirements. The digitizing context must include at least buttons, x, and y in its packet data, and must return absolute coordinates. 1.1: Editing the current default digitizing context will also update the device-spe¬cific default context for the device listed in the lcDevice field of the default con¬text’s LOGCONTEXT structure. See Also The WTInfo function in section 5.1.1 the WTMgrDefContextEx function in section 5.6.4, and the category and index definitions in tables 7.3 through 7.9. 5.6.4 WTMgrDefContextEx (1.1) Syntax HCTX WTMgrDefContextEx(hMgr, wDevice, fSystem) This function retrieves a context handle that allows setting values for the default digit¬izing or system context for a specified device. Parameter Type/Description hMgr HMGR Is the valid manager handle that identifies the caller as a manager application. wDevice UINT Specifies the device for which a default context handle will be returned. fSystem BOOL Specifies retrieval of the default system context if non-zero, or the default digitizing context if zero. Return Value The return value is the context handle for the specified default context, or NULL if the arguments were invalid. Comments The default digitizing contexts are contexts whose attributes are returned by the WTInfo function WTI_DDCTXS multiplexed category. The default system con-texts are contexts whose attributes are returned by the WTInfo function WTI_DSCTXS multiplexed category. Editing operations on the retrieved handles will fail if the new default contexts do not meet certain requirements. The digitizing context must include at least buttons, x, and y in its packet data, and must return absolute coordinates. See Also The WTInfo function in section 5.1.1, and the category and index definitions in tables 7.3 through 7.9. 5.7 Manager Configuration Functions These functions allow manager applications to replace the default context configuration dialog and to display a configuration dialog for each hardware device. 5.7.1 WTMgrDeviceConfig Syntax UINT WTMgrDeviceConfig(hMgr, wDevice, hWnd) This function displays a custom modal tablet-hardware configuration dialog box, if one is supported. Parameter Type/Description hMgr HMGR Is the valid manager handle that identifies the caller as a manager application. wDevice UINT Identifies the device that the user will configure via the dialog box. hWnd HWND Identifies the window that will be the parent window of the dialog box. If this argument is NULL, the function will return non-zero if the dialog is supported, or zero otherwise. Return Value The return value is zero if the dialog box is not supported. Otherwise, it is one of the following non-zero values. Value Meaning WTDC_CANCEL The user canceled the dialog without making any changes. WTDC_OK The user made and confirmed changes. WTDC_RESTART The user made and confirmed changes that require a sys-tem restart in order to take effect. The calling program should query the user to determine whether to restart. Restart Windows using the function call ExitWin-dows(EW_RESTARTWINDOWS, 0);. 5.7.2 WTMgrConfigReplace (16-bit only) Syntax BOOL WTMgrConfigReplace(hMgr, fInstall, lpConfigProc) This function allows a manager application to replace the default behavior of the WTConfig function. Parameter Type/Description hMgr HMGR Is the valid manager handle that identifies the caller as a manager application. fInstall BOOL Specifies installation of a replacement function if non-zero, or removal of the current replacement if zero. lpConfigProc WTCONFIGPROC Is the procedure-instance address of the new configuration function. This argument is ignored during a re¬moval request. Return Value The function return non-zero if the installation or removal request succeeded. Oth-erwise, it returns zero. Comments This function is non-portable and is superseded by WTMgrConfigReplaceEx. See Also The WTConfig function in section 5.3.1, and for a description of the configuration callback function, see the WTMgrConfigReplaceEx function in section 5.7.3. 5.7.3 WTMgrConfigReplaceEx Syntax BOOL WTMgrConfigReplaceEx(hMgr, fInstall, lpszModule, lpszCfgProc) This function allows a manager application to replace the default behavior of the WTConfig function. Parameter Type/Description hMgr HMGR Is the valid manager handle that identifies the caller as a manager application. fInstall BOOL Specifies installation of a replacement function if non-zero, or removal of the current replacement if zero. lpszModule LPCTSTR Points to a null-terminated string that names a DLL module containing the new configuration function. This argument is ignored during a re¬moval request lpszCfgProc LPCSTR Points to a null-terminated string that names the new configuration function. This argument is ignored during a re¬moval request. Return Value The function return non-zero if the installation or removal request succeeded. Oth-erwise, it returns zero. Comments The configuration callback function must have attributes equivalent to WINAPI. Only one callback function may be installed at a time. The manager handle passed with the removal request must match the handle passed with the corre¬sponding in-stallation request. Tablet managers that install a replacement context configuration function must re-move it before exiting. Callback BOOL WINAPI ConfigProc(hWnd, hCtx) HWND hWnd; HCTX hCtx; ConfigProc is a place holder for the application-supplied function name. The actual name must be exported by including it in an EXPORTS statement in the applica-tion's module-definition file. Parameter Description hWnd Identifies the window that will be the parent window of the dialog box. hCtx Identifies the context that the user will modify via the dialog box. Return Value The function returns a non-zero value if the tablet context was changed, zero oth-erwise. Comments The configuration function and resulting dialog box should analyze the lcLocks context structure member, and only allow editing of unlocked context attributes. See Also The WTConfig function in section 5.3.1. 5.8 Manager Packet Hook Functions These functions allow manager applications to monitor, record, and play back sequences of tablet packets. 5.8.1 WTMgrPacketHook (16-bit only) Syntax WTHOOKPROC WTMgrPacketHook(hMgr, fInstall, nType, lpFunc) This function installs or removes a packet hook function. Parameter Type/Description hMgr HMGR Is the valid manager handle that identifies the caller as a manager application. fInstall BOOL Specifies installation of a hook function if non-zero, or removal of the specified hook if zero. nType int Specifies the packet hook to be installed. It can be any one of the following values: Value Meaning WTH_PLAYBACK Installs a packet playback hook. WTH_RECORD Installs a packet record hook. lpFunc WTHOOKPROC Is the procedure-instance address of the hook function to be installed. See the "Comments" section under WTMgrPacketHookEx for details. Return Value When installing a hook, the return value points to the procedure-instance ad¬dress of the previously installed hook (if any). It is NULL if there is no previous hook; it is negative one if the hook cannot be installed. The application or library that calls this func¬tion should save this return value in the library's data segment. The fourth argument of the WTPacketHookDefProc function points to the location in memory where the library saves this return value. When removing a hook, the return value is the passed lpFunc if successful, NULL otherwise. Comments This function is non-portable and is superseded by WTMgrPacketHookEx and WTMgrPacketUnhook. See Also the WTMgrPacketHookEx function in section 5.8.2, and the WTMgrPacketUn-hook function in section 5.8.3. 5.8.2 WTMgrPacketHookEx Syntax HWTHOOK WTMgrPacketHookEx(hMgr, nType, lpszModule, lpszHookProc) This function installs a packet hook function. Parameter Type/Description hMgr HMGR Is the valid manager handle that identifies the caller as a manager application. nType int Specifies the packet hook to be installed. It can be any one of the following values: Value Meaning WTH_PLAYBACK Installs a packet playback hook. WTH_RECORD Installs a packet record hook. lpszModule LPCTSTR Points to a null-terminated string that names a DLL module containing the new hook function. See the following "Comments" section for details. lpszHookProc LPCSTR Points to a null-terminated string that names the new hook function. See the following "Comments" section for details. Return Value If the function succeeds, the return value is the handle of the installed hook func-tion. Otherwise, the return value is NULL. Comments Packet hooks are a shared resource. Installing a hook affects all applications using the interface. All Wintab hook functions must be exported functions residing in a DLL module. The following section describes how to support the individual hook functions. WTH_PLAYBACK Wintab calls the WTH_PLAYBACK hook whenever a request for an event packet is made. The function is intended to be used to supply a previously recorded event packet for a compatible context. The hook function must have attributes equivalent to WINAPI. The filter function must have the following form: Hook Function LRESULT WINAPI HookFunc(nCode, wParam, lParam); int nCode; WPARAM wParam; LPARAM lParam; HookFunc is a place holder for the library-supplied function name. The actual name must be exported by including it in an EXPORTS statement in the library's mod¬ule-definition file. Parameter Description nCode Specifies whether the hook function should process the mes¬sage or call the WTMgrPacketHookDefProc (if installed by WTMgrPacketHook)or WTMgrPacketHookNext (if installed by WTMgrPacketHookEx) function. If the nCode parame¬ter is less than zero, the hook function should pass the message to the appropriate function without further process¬ing. wParam Specifies the context handle whose event is being requested. lParam Points to the packet being processed by the hook function. Comments The WTH_PLAYBACK function should copy an event packet to the buffer pointed to by the lParam pa¬rameter. The packet must have been previously recorded by us-ing the WTH_RECORD hook. It should not modify the packet. The return value should be the amount of time (in milliseconds) Wintab should wait before pro¬cess¬ing the mes¬sage. This time can be computed by calculation the difference between the time stamps of the current and previous packets. If the function returns zero, the message is processed immediately. Once it returns control to Wintab, the packet continues to be processed. If the nCode parameter is WTHC_SKIP, the hook func-tion should prepare to return the next recorded event message on its next call. The packet pointed to by lParam will have the same structure as packets re¬trieved from the context normally. Wintab will validate the following packet items to en¬sure consistency: context handle, time stamp, and serial number. The remaining fields will be valid if the context used for playback is equivalent to the context from which the events were recorded. The WTH_PLAYBACK hook will not be called to notify it of the display or re¬moval of system modal dialog boxes. It is expected that applications playing back packets will also be playing back window event messages using Windows' own hook functions. While the WTH_PLAYBACK function is in effect, Wintab ignores all hardware in-put. WTH_RECORD The interface calls the WTH_RECORD hook whenever it processes a packet from a context event queue. The hook can be used to record the packet for later playback. The hook function must have attributes equivalent to WINAPI. The hook function must have the following form: Hook Function LRESULT WINAPI HookFunc(nCode, wParam, lParam); int nCode; WPARAM wParam; LPARAM lParam; HookFunc is a place holder for the library-supplied function name. The actual name must be exported by including it in an EXPORTS statement in the library's mod¬ule-definition file. Parameter Description nCode Specifies whether the hook function should process the mes¬sage or call the WTMgrPacketHookDefProc (if installed by WTMgrPacketHook)or WTMgrPacketHookNext (if installed by WTMgrPacketHookEx) function. If the nCode parame¬ter is less than zero, the hook function should pass the message to the appropriate function without further process¬ing. wParam Specifies the context handle whose event is being processed. lParam Points to the packet being processed by the hook function. Comments The WTH_RECORD function should save a copy of the packet for later play¬back. It should not modify the packet. Once it returns control to Wintab, the message con-tinues to be processed. The filter function does not require a return value. The packet pointed to by lParam will have the same structure as packets re¬trieved from the context normally. The WTH_RECORD hook will not be called to notify it of the display or re¬moval of system modal dialog boxes. It is expected that applications recording packets will also be recording window event messages using Windows' own hook functions. 5.8.3 WTMgrPacketUnhook Syntax BOOL WTMgrPacketUnhook(hHook) This function removes a hook function installed by the WTMgrPacketHookEx function. Parameter Type/Description hHook HWTHOOK Identifies the hook function to be removed. Return Value The function returns a non-zero value if successful, zero otherwise. See Also The WTMgrPacketHookEx function in section 5.8.2, and the WTMgrPack-etHookNext function in section 5.8.5. 5.8.4 WTMgrPacketHookDefProc (16-bit only) Syntax LRESULT WTMgrPacketHookDefProc(nCode, wParam, lParam, lplpFunc) This function calls the next function in a chain of packet hook functions. A packet hook function is a function that processes packets before they are re¬trieved from a context's queue. When applications define more than one hook function by using the WTMgrPacketHook function, Wintab places func¬tions of the same type in a chain. Parameter Type/Description nCode int Specifies a code used by the hook function to determine how to process the message. wParam WPARAM Specifies the word parameter of the message that the hook function is processing. lParam LPARAM Specifies the long parameter of the message that the hook function is processing. lplpFunc WTHOOKPROC FAR * Points to a memory location that con-tains the WTHOOKPROC returned by the WTMgrPacketHook function. Wintab changes the value at this location after an appli-cation unhooks the hook using the WTMgrPacketHook function. Return Value The return value specifies a value that is directly related to the nCode parameter. Comments This function is non-portable and is superseded by the WTMgrPacketHookNext function. See Also The WTMgrPacketHookNext function in section 5.8.5. 5.8.5 WTMgrPacketHookNext Syntax LRESULT WTMgrPacketHookNext(hHook, nCode, wParam, lParam) This function passes the hook information to the next hook function in the current hook chain. Parameter Type/Description hHook HWTHOOK Identifies the current hook. nCode int Specifies the hook code passed to the current hook function. wParam WPARAM Specifies the wParam value
Overview Package Class Tree Deprecated Index Help PREV NEXT FRAMES NO FRAMES A B C D E F G H I J L P R S U V -------------------------------------------------------------------------------- A addCookie(Cookie) - Method in class javax.servlet.http.HttpServletResponseWrapper The default behavior of this method is to call addCookie(Cookie cookie) on the wrapped response object. addCookie(Cookie) - Method in interface javax.servlet.http.HttpServletResponse Adds the specified cookie to the response. addDateHeader(String, long) - Method in class javax.servlet.http.HttpServletResponseWrapper The default behavior of this method is to call addDateHeader(String name, long date) on the wrapped response object. addDateHeader(String, long) - Method in interface javax.servlet.http.HttpServletResponse Adds a response header with the given name and date-value. addHeader(String, String) - Method in class javax.servlet.http.HttpServletResponseWrapper The default behavior of this method is to return addHeader(String name, String value) on the wrapped response object. addHeader(String, String) - Method in interface javax.servlet.http.HttpServletResponse Adds a response header with the given name and value. addIntHeader(String, int) - Method in class javax.servlet.http.HttpServletResponseWrapper The default behavior of this method is to call addIntHeader(String name, int value) on the wrapped response object. addIntHeader(String, int) - Method in interface javax.servlet.http.HttpServletResponse Adds a response header with the given name and integer value. attributeAdded(HttpSessionBindingEvent) - Method in interface javax.servlet.http.HttpSessionAttributeListener Notification that an attribute has been added to a session. attributeAdded(ServletContextAttributeEvent) - Method in interface javax.servlet.ServletContextAttributeListener Notification that a new attribute was added to the servlet context. attributeAdded(ServletRequestAttributeEvent) - Method in interface javax.servlet.ServletRequestAttributeListener Notification that a new attribute was added to the servlet request. attributeRemoved(HttpSessionBindingEvent) - Method in interface javax.servlet.http.HttpSessionAttributeListener Notification that an attribute has been removed from a session. attributeRemoved(ServletContextAttributeEvent) - Method in interface javax.servlet.ServletContextAttributeListener Notification that an existing attribute has been removed from the servlet context. attributeRemoved(ServletRequestAttributeEvent) - Method in interface javax.servlet.ServletRequestAttributeListener Notification that a new attribute was removed from the servlet request. attributeReplaced(HttpSessionBindingEvent) - Method in interface javax.servlet.http.HttpSessionAttributeListener Notification that an attribute has been replaced in a session. attributeReplaced(ServletContextAttributeEvent) - Method in interface javax.servlet.ServletContextAttributeListener Notification that an attribute on the servlet context has been replaced. attributeReplaced(ServletRequestAttributeEvent) - Method in interface javax.servlet.ServletRequestAttributeListener Notification that an attribute was replaced on the servlet request. -------------------------------------------------------------------------------- B BASIC_AUTH - Static variable in interface javax.servlet.http.HttpServletRequest String identifier for Basic authentication. -------------------------------------------------------------------------------- C CLIENT_CERT_AUTH - Static variable in interface javax.servlet.http.HttpServletRequest String identifier for Client Certificate authentication. clone() - Method in class javax.servlet.http.Cookie Overrides the standard java.lang.Object.clone method to return a copy of this cookie. containsHeader(String) - Method in class javax.servlet.http.HttpServletResponseWrapper The default behavior of this method is to call containsHeader(String name) on the wrapped response object. containsHeader(String) - Method in interface javax.servlet.http.HttpServletResponse Returns a boolean indicating whether the named response header has already been set. contextDestroyed(ServletContextEvent) - Method in interface javax.servlet.ServletContextListener Notification that the servlet context is about to be shut down. contextInitialized(ServletContextEvent) - Method in interface javax.servlet.ServletContextListener Notification that the web application initialization process is starting. Cookie - class javax.servlet.http.Cookie. Creates a cookie, a small amount of information sent by a servlet to a Web browser, saved by the browser, and later sent back to the server. Cookie(String, String) - Constructor for class javax.servlet.http.Cookie Constructs a cookie with a specified name and value. -------------------------------------------------------------------------------- D destroy() - Method in interface javax.servlet.Filter Called by the web container to indicate to a filter that it is being taken out of service. destroy() - Method in interface javax.servlet.Servlet Called by the servlet container to indicate to a servlet that the servlet is being taken out of service. destroy() - Method in class javax.servlet.GenericServlet Called by the servlet container to indicate to a servlet that the servlet is being taken out of service. DIGEST_AUTH - Static variable in interface javax.servlet.http.HttpServletRequest String identifier for Digest authentication. doDelete(HttpServletRequest, HttpServletResponse) - Method in class javax.servlet.http.HttpServlet Called by the server (via the service method) to allow a servlet to handle a DELETE request. doFilter(ServletRequest, ServletResponse) - Method in interface javax.servlet.FilterChain Causes the next filter in the chain to be invoked, or if the calling filter is the last filter in the chain, causes the resource at the end of the chain to be invoked. doFilter(ServletRequest, ServletResponse, FilterChain) - Method in interface javax.servlet.Filter The doFilter method of the Filter is called by the container each time a request/response pair is passed through the chain due to a client request for a resource at the end of the chain. doGet(HttpServletRequest, HttpServletResponse) - Method in class javax.servlet.http.HttpServlet Called by the server (via the service method) to allow a servlet to handle a GET request. doHead(HttpServletRequest, HttpServletResponse) - Method in class javax.servlet.http.HttpServlet Receives an HTTP HEAD request from the protected service method and handles the request. doOptions(HttpServletRequest, HttpServletResponse) - Method in class javax.servlet.http.HttpServlet Called by the server (via the service method) to allow a servlet to handle a OPTIONS request. doPost(HttpServletRequest, HttpServletResponse) - Method in class javax.servlet.http.HttpServlet Called by the server (via the service method) to allow a servlet to handle a POST request. doPut(HttpServletRequest, HttpServletResponse) - Method in class javax.servlet.http.HttpServlet Called by the server (via the service method) to allow a servlet to handle a PUT request. doTrace(HttpServletRequest, HttpServletResponse) - Method in class javax.servlet.http.HttpServlet Called by the server (via the service method) to allow a servlet to handle a TRACE request. -------------------------------------------------------------------------------- E encodeRedirectUrl(String) - Method in class javax.servlet.http.HttpServletResponseWrapper The default behavior of this method is to return encodeRedirectUrl(String url) on the wrapped response object. encodeRedirectUrl(String) - Method in interface javax.servlet.http.HttpServletResponse Deprecated. As of version 2.1, use encodeRedirectURL(String url) instead encodeRedirectURL(String) - Method in class javax.servlet.http.HttpServletResponseWrapper The default behavior of this method is to return encodeRedirectURL(String url) on the wrapped response object. encodeRedirectURL(String) - Method in interface javax.servlet.http.HttpServletResponse Encodes the specified URL for use in the sendRedirect method or, if encoding is not needed, returns the URL unchanged. encodeUrl(String) - Method in class javax.servlet.http.HttpServletResponseWrapper The default behavior of this method is to call encodeUrl(String url) on the wrapped response object. encodeUrl(String) - Method in interface javax.servlet.http.HttpServletResponse Deprecated. As of version 2.1, use encodeURL(String url) instead encodeURL(String) - Method in class javax.servlet.http.HttpServletResponseWrapper The default behavior of this method is to call encodeURL(String url) on the wrapped response object. encodeURL(String) - Method in interface javax.servlet.http.HttpServletResponse Encodes the specified URL by including the session ID in it, or, if encoding is not needed, returns the URL unchanged. -------------------------------------------------------------------------------- F Filter - interface javax.servlet.Filter. A filter is an object that performs filtering tasks on either the request to a resource (a servlet or static content), or on the response from a resource, or both. Filters perform filtering in the doFilter method. FilterChain - interface javax.servlet.FilterChain. A FilterChain is an object provided by the servlet container to the developer giving a view into the invocation chain of a filtered request for a resource. FilterConfig - interface javax.servlet.FilterConfig. A filter configuration object used by a servlet container to pass information to a filter during initialization. flushBuffer() - Method in interface javax.servlet.ServletResponse Forces any content in the buffer to be written to the client. flushBuffer() - Method in class javax.servlet.ServletResponseWrapper The default behavior of this method is to call flushBuffer() on the wrapped response object. FORM_AUTH - Static variable in interface javax.servlet.http.HttpServletRequest String identifier for Form authentication. forward(ServletRequest, ServletResponse) - Method in interface javax.servlet.RequestDispatcher Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server. -------------------------------------------------------------------------------- G GenericServlet - class javax.servlet.GenericServlet. Defines a generic, protocol-independent servlet. GenericServlet() - Constructor for class javax.servlet.GenericServlet Does nothing. getAttribute(String) - Method in interface javax.servlet.ServletContext Returns the servlet container attribute with the given name, or null if there is no attribute by that name. getAttribute(String) - Method in class javax.servlet.ServletRequestWrapper The default behavior of this method is to call getAttribute(String name) on the wrapped request object. getAttribute(String) - Method in interface javax.servlet.ServletRequest Returns the value of the named attribute as an Object, or null if no attribute of the given name exists. getAttribute(String) - Method in interface javax.servlet.http.HttpSession Returns the object bound with the specified name in this session, or null if no object is bound under the name. getAttributeNames() - Method in interface javax.servlet.ServletContext Returns an Enumeration containing the attribute names available within this servlet context. getAttributeNames() - Method in class javax.servlet.ServletRequestWrapper The default behavior of this method is to return getAttributeNames() on the wrapped request object. getAttributeNames() - Method in interface javax.servlet.ServletRequest Returns an Enumeration containing the names of the attributes available to this request. getAttributeNames() - Method in interface javax.servlet.http.HttpSession Returns an Enumeration of String objects containing the names of all the objects bound to this session. getAuthType() - Method in interface javax.servlet.http.HttpServletRequest Returns the name of the authentication scheme used to protect the servlet. getAuthType() - Method in class javax.servlet.http.HttpServletRequestWrapper The default behavior of this method is to return getAuthType() on the wrapped request object. getBufferSize() - Method in interface javax.servlet.ServletResponse Returns the actual buffer size used for the response. getBufferSize() - Method in class javax.servlet.ServletResponseWrapper The default behavior of this method is to return getBufferSize() on the wrapped response object. getCharacterEncoding() - Method in interface javax.servlet.ServletResponse Returns the name of the character encoding (MIME charset) used for the body sent in this response. getCharacterEncoding() - Method in class javax.servlet.ServletRequestWrapper The default behavior of this method is to return getCharacterEncoding() on the wrapped request object. getCharacterEncoding() - Method in interface javax.servlet.ServletRequest Returns the name of the character encoding used in the body of this request. getCharacterEncoding() - Method in class javax.servlet.ServletResponseWrapper The default behavior of this method is to return getCharacterEncoding() on the wrapped response object. getComment() - Method in class javax.servlet.http.Cookie Returns the comment describing the purpose of this cookie, or null if the cookie has no comment. getContentLength() - Method in class javax.servlet.ServletRequestWrapper The default behavior of this method is to return getContentLength() on the wrapped request object. getContentLength() - Method in interface javax.servlet.ServletRequest Returns the length, in bytes, of the request body and made available by the input stream, or -1 if the length is not known. getContentType() - Method in interface javax.servlet.ServletResponse Returns the content type used for the MIME body sent in this response. getContentType() - Method in class javax.servlet.ServletRequestWrapper The default behavior of this method is to return getContentType() on the wrapped request object. getContentType() - Method in interface javax.servlet.ServletRequest Returns the MIME type of the body of the request, or null if the type is not known. getContentType() - Method in class javax.servlet.ServletResponseWrapper The default behavior of this method is to return getContentType() on the wrapped response object. getContext(String) - Method in interface javax.servlet.ServletContext Returns a ServletContext object that corresponds to a specified URL on the server. getContextPath() - Method in interface javax.servlet.http.HttpServletRequest Returns the portion of the request URI that indicates the context of the request. getContextPath() - Method in class javax.servlet.http.HttpServletRequestWrapper The default behavior of this method is to return getContextPath() on the wrapped request object. getCookies() - Method in interface javax.servlet.http.HttpServletRequest Returns an array containing all of the Cookie objects the client sent with this request. getCookies() - Method in class javax.servlet.http.HttpServletRequestWrapper The default behavior of this method is to return getCookies() on the wrapped request object. getCreationTime() - Method in interface javax.servlet.http.HttpSession Returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT. getDateHeader(String) - Method in interface javax.servlet.http.HttpServletRequest Returns the value of the specified request header as a long value that represents a Date object. getDateHeader(String) - Method in class javax.servlet.http.HttpServletRequestWrapper The default behavior of this method is to return getDateHeader(String name) on the wrapped request object. getDomain() - Method in class javax.servlet.http.Cookie Returns the domain name set for this cookie. getFilterName() - Method in interface javax.servlet.FilterConfig Returns the filter-name of this filter as defined in the deployment descriptor. getHeader(String) - Method in interface javax.servlet.http.HttpServletRequest Returns the value of the specified request header as a String. getHeader(String) - Method in class javax.servlet.http.HttpServletRequestWrapper The default behavior of this method is to return getHeader(String name) on the wrapped request object. getHeaderNames() - Method in interface javax.servlet.http.HttpServletRequest Returns an enumeration of all the header names this request contains. getHeaderNames() - Method in class javax.servlet.http.HttpServletRequestWrapper The default behavior of this method is to return getHeaderNames() on the wrapped request object. getHeaders(String) - Method in interface javax.servlet.http.HttpServletRequest Returns all the values of the specified request header as an Enumeration of String objects. getHeaders(String) - Method in class javax.servlet.http.HttpServletRequestWrapper The default behavior of this method is to return getHeaders(String name) on the wrapped request object. getId() - Method in interface javax.servlet.http.HttpSession Returns a string containing the unique identifier assigned to this session. getIds() - Method in interface javax.servlet.http.HttpSessionContext Deprecated. As of Java Servlet API 2.1 with no replacement. This method must return an empty Enumeration and will be removed in a future version of this API. getInitParameter(String) - Method in interface javax.servlet.FilterConfig Returns a String containing the value of the named initialization parameter, or null if the parameter does not exist. getInitParameter(String) - Method in interface javax.servlet.ServletConfig Returns a String containing the value of the named initialization parameter, or null if the parameter does not exist. getInitParameter(String) - Method in interface javax.servlet.ServletContext Returns a String containing the value of the named context-wide initialization parameter, or null if the parameter does not exist. getInitParameter(String) - Method in class javax.servlet.GenericServlet Returns a String containing the value of the named initialization parameter, or null if the parameter does not exist. getInitParameterNames() - Method in interface javax.servlet.FilterConfig Returns the names of the filter's initialization parameters as an Enumeration of String objects, or an empty Enumeration if the filter has no initialization parameters. getInitParameterNames() - Method in interface javax.servlet.ServletConfig Returns the names of the servlet's initialization parameters as an Enumeration of String objects, or an empty Enumeration if the servlet has no initialization parameters. getInitParameterNames() - Method in interface javax.servlet.ServletContext Returns the names of the context's initialization parameters as an Enumeration of String objects, or an empty Enumeration if the context has no initialization parameters. getInitParameterNames() - Method in class javax.servlet.GenericServlet Returns the names of the servlet's initialization parameters as an Enumeration of String objects, or an empty Enumeration if the servlet has no initialization parameters. getInputStream() - Method in class javax.servlet.ServletRequestWrapper The default behavior of this method is to return getInputStream() on the wrapped request object. getInputStream() - Method in interface javax.servlet.ServletRequest Retrieves the body of the request as binary data using a ServletInputStream. getIntHeader(String) - Method in interface javax.servlet.http.HttpServletRequest Returns the value of the specified request header as an int. getIntHeader(String) - Method in class javax.servlet.http.HttpServletRequestWrapper The default behavior of this method is to return getIntHeader(String name) on the wrapped request object. getLastAccessedTime() - Method in interface javax.servlet.http.HttpSession Returns the last time the client sent a request associated with this session, as the number of milliseconds since midnight January 1, 1970 GMT, and marked by the time the container received the request. getLastModified(HttpServletRequest) - Method in class javax.servlet.http.HttpServlet Returns the time the HttpServletRequest object was last modified, in milliseconds since midnight January 1, 1970 GMT. getLocalAddr() - Method in class javax.servlet.ServletRequestWrapper The default behavior of this method is to return getLocalAddr() on the wrapped request object. getLocalAddr() - Method in interface javax.servlet.ServletRequest Returns the Internet Protocol (IP) address of the interface on which the request was received. getLocale() - Method in interface javax.servlet.ServletResponse Returns the locale specified for this response using the ServletResponse.setLocale(java.util.Locale) method. getLocale() - Method in class javax.servlet.ServletRequestWrapper The default behavior of this method is to return getLocale() on the wrapped request object. getLocale() - Method in interface javax.servlet.ServletRequest Returns the preferred Locale that the client will accept content in, based on the Accept-Language header. getLocale() - Method in class javax.servlet.ServletResponseWrapper The default behavior of this method is to return getLocale() on the wrapped response object. getLocales() - Method in class javax.servlet.ServletRequestWrapper The default behavior of this method is to return getLocales() on the wrapped request object. getLocales() - Method in interface javax.servlet.ServletRequest Returns an Enumeration of Locale objects indicating, in decreasing order starting with the preferred locale, the locales that are acceptable to the client based on the Accept-Language header. getLocalName() - Method in class javax.servlet.ServletRequestWrapper The default behavior of this method is to return getLocalName() on the wrapped request object. getLocalName() - Method in interface javax.servlet.ServletRequest Returns the host name of the Internet Protocol (IP) interface on which the request was received. getLocalPort() - Method in class javax.servlet.ServletRequestWrapper The default behavior of this method is to return getLocalPort() on the wrapped request object. getLocalPort() - Method in interface javax.servlet.ServletRequest Returns the Internet Protocol (IP) port number of the interface on which the request was received. getMajorVersion() - Method in interface javax.servlet.ServletContext Returns the major version of the Java Servlet API that this servlet container supports. getMaxAge() - Method in class javax.servlet.http.Cookie Returns the maximum age of the cookie, specified in seconds, By default, -1 indicating the cookie will persist until browser shutdown. getMaxInactiveInterval() - Method in interface javax.servlet.http.HttpSession Returns the maximum time interval, in seconds, that the servlet container will keep this session open between client accesses. getMethod() - Method in interface javax.servlet.http.HttpServletRequest Returns the name of the HTTP method with which this request was made, for example, GET, POST, or PUT. getMethod() - Method in class javax.servlet.http.HttpServletRequestWrapper The default behavior of this method is to return getMethod() on the wrapped request object. getMimeType(String) - Method in interface javax.servlet.ServletContext Returns the MIME type of the specified file, or null if the MIME type is not known. getMinorVersion() - Method in interface javax.servlet.ServletContext Returns the minor version of the Servlet API that this servlet container supports. getName() - Method in class javax.servlet.ServletContextAttributeEvent Return the name of the attribute that changed on the ServletContext. getName() - Method in class javax.servlet.ServletRequestAttributeEvent Return the name of the attribute that changed on the ServletRequest getName() - Method in class javax.servlet.http.HttpSessionBindingEvent Returns the name with which the attribute is bound to or unbound from the session. getName() - Method in class javax.servlet.http.Cookie Returns the name of the cookie. getNamedDispatcher(String) - Method in interface javax.servlet.ServletContext Returns a RequestDispatcher object that acts as a wrapper for the named servlet. getOutputStream() - Method in interface javax.servlet.ServletResponse Returns a ServletOutputStream suitable for writing binary data in the response. getOutputStream() - Method in class javax.servlet.ServletResponseWrapper The default behavior of this method is to return getOutputStream() on the wrapped response object. getParameter(String) - Method in class javax.servlet.ServletRequestWrapper The default behavior of this method is to return getParameter(String name) on the wrapped request object. getParameter(String) - Method in interface javax.servlet.ServletRequest Returns the value of a request parameter as a String, or null if the parameter does not exist. getParameterMap() - Method in class javax.servlet.ServletRequestWrapper The default behavior of this method is to return getParameterMap() on the wrapped request object. getParameterMap() - Method in interface javax.servlet.ServletRequest Returns a java.util.Map of the parameters of this request. getParameterNames() - Method in class javax.servlet.ServletRequestWrapper The default behavior of this method is to return getParameterNames() on the wrapped request object. getParameterNames() - Method in interface javax.servlet.ServletRequest Returns an Enumeration of String objects containing the names of the parameters contained in this request. getParameterValues(String) - Method in class javax.servlet.ServletRequestWrapper The default behavior of this method is to return getParameterValues(String name) on the wrapped request object. getParameterValues(String) - Method in interface javax.servlet.ServletRequest Returns an array of String objects containing all of the values the given request parameter has, or null if the parameter does not exist. getPath() - Method in class javax.servlet.http.Cookie Returns the path on the server to which the browser returns this cookie. getPathInfo() - Method in interface javax.servlet.http.HttpServletRequest Returns any extra path information associated with the URL the client sent when it made this request. getPathInfo() - Method in class javax.servlet.http.HttpServletRequestWrapper The default behavior of this method is to return getPathInfo() on the wrapped request object. getPathTranslated() - Method in interface javax.servlet.http.HttpServletRequest Returns any extra path information after the servlet name but before the query string, and translates it to a real path. getPathTranslated() - Method in class javax.servlet.http.HttpServletRequestWrapper The default behavior of this method is to return getPathTranslated() on the wrapped request object. getProtocol() - Method in class javax.servlet.ServletRequestWrapper The default behavior of this method is to return getProtocol() on the wrapped request object. getProtocol() - Method in interface javax.servlet.ServletRequest Returns the name and version of the protocol the request uses in the form protocol/majorVersion.minorVersion, for example, HTTP/1.1. getQueryString() - Method in interface javax.servlet.http.HttpServletRequest Returns the query string that is contained in the request URL after the path. getQueryString() - Method in class javax.servlet.http.HttpServletRequestWrapper The default behavior of this method is to return getQueryString() on the wrapped request object. getReader() - Method in class javax.servlet.ServletRequestWrapper The default behavior of this method is to return getReader() on the wrapped request object. getReader() - Method in interface javax.servlet.ServletRequest Retrieves the body of the request as character data using a BufferedReader. getRealPath(String) - Method in interface javax.servlet.ServletContext Returns a String containing the real path for a given virtual path. getRealPath(String) - Method in class javax.servlet.ServletRequestWrapper The default behavior of this method is to return getRealPath(String path) on the wrapped request object. getRealPath(String) - Method in interface javax.servlet.ServletRequest Deprecated. As of Version 2.1 of the Java Servlet API, use ServletContext.getRealPath(java.lang.String) instead. getRemoteAddr() - Method in class javax.servlet.ServletRequestWrapper The default behavior of this method is to return getRemoteAddr() on the wrapped request object. getRemoteAddr() - Method in interface javax.servlet.ServletRequest Returns the Internet Protocol (IP) address of the client or last proxy that sent the request. getRemoteHost() - Method in class javax.servlet.ServletRequestWrapper The default behavior of this method is to return getRemoteHost() on the wrapped request object. getRemoteHost() - Method in interface javax.servlet.ServletRequest Returns the fully qualified name of the client or the last proxy that sent the request. getRemotePort() - Method in class javax.servlet.ServletRequestWrapper The default behavior of this method is to return getRemotePort() on the wrapped request object. getRemotePort() - Method in interface javax.servlet.ServletRequest Returns the Internet Protocol (IP) source port of the client or last proxy that sent the request. getRemoteUser() - Method in interface javax.servlet.http.HttpServletRequest Returns the login of the user making this request, if the user has been authenticated, or null if the user has not been authenticated. getRemoteUser() - Method in class javax.servlet.http.HttpServletRequestWrapper The default behavior of this method is to return getRemoteUser() on the wrapped request object. getRequest() - Method in class javax.servlet.ServletRequestWrapper Return the wrapped request object. getRequestDispatcher(String) - Method in interface javax.servlet.ServletContext Returns a RequestDispatcher object that acts as a wrapper for the resource located at the given path. getRequestDispatcher(String) - Method in class javax.servlet.ServletRequestWrapper The default behavior of this method is to return getRequestDispatcher(String path) on the wrapped request object. getRequestDispatcher(String) - Method in interface javax.servlet.ServletRequest Returns a RequestDispatcher object that acts as a wrapper for the resource located at the given path. getRequestedSessionId() - Method in interface javax.servlet.http.HttpServletRequest Returns the session ID specified by the client. getRequestedSessionId() - Method in class javax.servlet.http.HttpServletRequestWrapper The default behavior of this method is to return getRequestedSessionId() on the wrapped request object. getRequestURI() - Method in interface javax.servlet.http.HttpServletRequest Returns the part of this request's URL from the protocol name up to the query string in the first line of the HTTP request. getRequestURI() - Method in class javax.servlet.http.HttpServletRequestWrapper The default behavior of this method is to return getRequestURI() on the wrapped request object. getRequestURL() - Method in interface javax.servlet.http.HttpServletRequest Reconstructs the URL the client used to make the request. getRequestURL() - Method in class javax.servlet.http.HttpServletRequestWrapper The default behavior of this method is to return getRequestURL() on the wrapped request object. getRequestURL(HttpServletRequest) - Static method in class javax.servlet.http.HttpUtils Deprecated. Reconstructs the URL the client used to make the request, using information in the HttpServletRequest object. getResource(String) - Method in interface javax.servlet.ServletContext Returns a URL to the resource that is mapped to a specified path. getResourceAsStream(String) - Method in interface javax.servlet.ServletContext Returns the resource located at the named path as an InputStream object. getResourcePaths(String) - Method in interface javax.servlet.ServletContext Returns a directory-like listing of all the paths to resources within the web application whose longest sub-path matches the supplied path argument. getResponse() - Method in class javax.servlet.ServletResponseWrapper Return the wrapped ServletResponse object. getRootCause() - Method in class javax.servlet.ServletException Returns the exception that caused this servlet exception. getScheme() - Method in class javax.servlet.ServletRequestWrapper The default behavior of this method is to return getScheme() on the wrapped request object. getScheme() - Method in interface javax.servlet.ServletRequest Returns the name of the scheme used to make this request, for example, http, https, or ftp. getSecure() - Method in class javax.servlet.http.Cookie Returns true if the browser is sending cookies only over a secure protocol, or false if the browser can send cookies using any protocol. getServerInfo() - Method in interface javax.servlet.ServletContext Returns the name and version of the servlet container on which the servlet is running. getServerName() - Method in class javax.servlet.ServletRequestWrapper The default behavior of this method is to return getServerName() on the wrapped request object. getServerName() - Method in interface javax.servlet.ServletRequest Returns the host name of the server to which the request was sent. getServerPort() - Method in class javax.servlet.ServletRequestWrapper The default behavior of this method is to return getServerPort() on the wrapped request object. getServerPort() - Method in interface javax.servlet.ServletRequest Returns the port number to which the request was sent. getServlet() - Method in class javax.servlet.UnavailableException Deprecated. As of Java Servlet API 2.2, with no replacement. Returns the servlet that is reporting its unavailability. getServlet(String) - Method in interface javax.servlet.ServletContext Deprecated. As of Java Servlet API 2.1, with no direct replacement. This method was originally defined to retrieve a servlet from a ServletContext. In this version, this method always returns null and remains only to preserve binary compatibility. This method will be permanently removed in a future version of the Java Servlet API. In lieu of this method, servlets can share information using the ServletContext class and can perform shared business logic by invoking methods on common non-servlet classes. getServletConfig() - Method in interface javax.servlet.Servlet Returns a ServletConfig object, which contains initialization and startup parameters for this servlet. getServletConfig() - Method in class javax.servlet.GenericServlet Returns this servlet's ServletConfig object. getServletContext() - Method in class javax.servlet.ServletRequestEvent Returns the ServletContext of this web application. getServletContext() - Method in interface javax.servlet.FilterConfig Returns a reference to the ServletContext in which the caller is executing. getServletContext() - Method in interface javax.servlet.ServletConfig Returns a reference to the ServletContext in which the caller is executing. getServletContext() - Method in class javax.servlet.ServletContextEvent Return the ServletContext that changed. getServletContext() - Method in class javax.servlet.GenericServlet Returns a reference to the ServletContext in which this servlet is running. getServletContext() - Method in interface javax.servlet.http.HttpSession Returns the ServletContext to which this session belongs. getServletContextName() - Method in interface javax.servlet.ServletContext Returns the name of this web application corresponding to this ServletContext as specified in the deployment descriptor for this web application by the display-name element. getServletInfo() - Method in interface javax.servlet.Servlet Returns information about the servlet, such as author, version, and copyright. getServletInfo() - Method in class javax.servlet.GenericServlet Returns information about the servlet, such as author, version, and copyright. getServletName() - Method in interface javax.servlet.ServletConfig Returns the name of this servlet instance. getServletName() - Method in class javax.servlet.GenericServlet Returns the name of this servlet instance. getServletNames() - Method in interface javax.servlet.ServletContext Deprecated. As of Java Servlet API 2.1, with no replacement. This method was originally defined to return an Enumeration of all the servlet names known to this context. In this version, this method always returns an empty Enumeration and remains only to preserve binary compatibility. This method will be permanently removed in a future version of the Java Servlet API. getServletPath() - Method in interface javax.servlet.http.HttpServletRequest Returns the part of this request's URL that calls the servlet. getServletPath() - Method in class javax.servlet.http.HttpServletRequestWrapper The default behavior of this method is to return getServletPath() on the wrapped request object. getServletRequest() - Method in class javax.servlet.ServletRequestEvent Returns the ServletRequest that is changing. getServlets() - Method in interface javax.servlet.ServletContext Deprecated. As of Java Servlet API 2.0, with no replacement. This method was originally defined to return an Enumeration of all the servlets known to this servlet context. In this version, this method always returns an empty enumeration and remains only to preserve binary compatibility. This method will be permanently removed in a future version of the Java Servlet API. getSession() - Method in class javax.servlet.http.HttpSessionEvent Return the session that changed. getSession() - Method in class javax.servlet.http.HttpSessionBindingEvent Return the session that changed. getSession() - Method in interface javax.servlet.http.HttpServletRequest Returns the current session associated with this request, or if the request does not have a session, creates one. getSession() - Method in class javax.servlet.http.HttpServletRequestWrapper The default behavior of this method is to return getSession() on the wrapped request object. getSession(boolean) - Method in interface javax.servlet.http.HttpServletRequest Returns the current HttpSession associated with this request or, if there is no current session and create is true, returns a new session. getSession(boolean) - Method in class javax.servlet.http.HttpServletRequestWrapper The default behavior of this method is to return getSession(boolean create) on the wrapped request object. getSession(String) - Method in interface javax.servlet.http.HttpSessionContext Deprecated. As of Java Servlet API 2.1 with no replacement. This method must return null and will be removed in a future version of this API. getSessionContext() - Method in interface javax.servlet.http.HttpSession Deprecated. As of Version 2.1, this method is deprecated and has no replacement. It will be removed in a future version of the Java Servlet API. getUnavailableSeconds() - Method in class javax.servlet.UnavailableException Returns the number of seconds the servlet expects to be temporarily unavailable. getUserPrincipal() - Method in interface javax.servlet.http.HttpServletRequest Returns a java.security.Principal object containing the name of the current authenticated user. getUserPrincipal() - Method in class javax.servlet.http.HttpServletRequestWrapper The default behavior of this method is to return getUserPrincipal() on the wrapped request object. getValue() - Method in class javax.servlet.ServletContextAttributeEvent Returns the value of the attribute that has been added, removed, or replaced. getValue() - Method in class javax.servlet.ServletRequestAttributeEvent Returns the value of the attribute that has been added, removed or replaced. getValue() - Method in class javax.servlet.http.HttpSessionBindingEvent Returns the value of the attribute that has been added, removed or replaced. getValue() - Method in class javax.servlet.http.Cookie Returns the value of the cookie. getValue(String) - Method in interface javax.servlet.http.HttpSession Deprecated. As of Version 2.2, this method is replaced by HttpSession.getAttribute(java.lang.String). getValueNames() - Method in interface javax.servlet.http.HttpSession Deprecated. As of Version 2.2, this method is replaced by HttpSession.getAttributeNames() getVersion() - Method in class javax.servlet.http.Cookie Returns the version of the protocol this cookie complies with. getWriter() - Method in interface javax.servlet.ServletResponse Returns a PrintWriter object that can send character text to the client. getWriter() - Method in class javax.servlet.ServletResponseWrapper The default behavior of this method is to return getWriter() on the wrapped response object. -------------------------------------------------------------------------------- H HttpServlet - class javax.servlet.http.HttpServlet. Provides an abstract class to be subclassed to create an HTTP servlet suitable for a Web site. HttpServlet() - Constructor for class javax.servlet.http.HttpServlet Does nothing, because this is an abstract class. HttpServletRequest - interface javax.servlet.http.HttpServletRequest. Extends the ServletRequest interface to provide request information for HTTP servlets. HttpServletRequestWrapper - class javax.servlet.http.HttpServletRequestWrapper. Provides a convenient implementation of the HttpServletRequest interface that can be subclassed by developers wishing to adapt the request to a Servlet. HttpServletRequestWrapper(HttpServletRequest) - Constructor for class javax.servlet.http.HttpServletRequestWrapper Constructs a request object wrapping the given request. HttpServletResponse - interface javax.servlet.http.HttpServletResponse. Extends the ServletResponse interface to provide HTTP-specific functionality in sending a response. HttpServletResponseWrapper - class javax.servlet.http.HttpServletResponseWrapper. Provides a convenient implementation of the HttpServletResponse interface that can be subclassed by developers wishing to adapt the response from a Servlet. HttpServletResponseWrapper(HttpServletResponse) - Constructor for class javax.servlet.http.HttpServletResponseWrapper Constructs a response adaptor wrapping the given response. HttpSession - interface javax.servlet.http.HttpSession. Provides a way to identify a user across more than one page request or visit to a Web site and to store information about that user. HttpSessionActivationListener - interface javax.servlet.http.HttpSessionActivationListener. Objects that are bound to a session may listen to container events notifying them that sessions will be passivated and that session will be activated. HttpSessionAttributeListener - interface javax.servlet.http.HttpSessionAttributeListener. This listener interface can be implemented in order to get notifications of changes to the attribute lists of sessions within this web application. HttpSessionBindingEvent - class javax.servlet.http.HttpSessionBindingEvent. Events of this type are either sent to an object that implements HttpSessionBindingListener when it is bound or unbound from a session, or to a HttpSessionAttributeListener that has been configured in the deployment descriptor when any attribute is bound, unbound or replaced in a session. HttpSessionBindingEvent(HttpSession, String) - Constructor for class javax.servlet.http.HttpSessionBindingEvent Constructs an event that notifies an object that it has been bound to or unbound from a session. HttpSessionBindingEvent(HttpSession, String, Object) - Constructor for class javax.servlet.http.HttpSessionBindingEvent Constructs an event that notifies an object that it has been bound to or unbound from a session. HttpSessionBindingListener - interface javax.servlet.http.HttpSessionBindingListener. Causes an object to be notified when it is bound to or unbound from a session. HttpSessionContext - interface javax.servlet.http.HttpSessionContext. Deprecated. As of Java(tm) Servlet API 2.1 for security reasons, with no replacement. This interface will be removed in a future version of this API. HttpSessionEvent - class javax.servlet.http.HttpSessionEvent. This is the class representing event notifications for changes to sessions within a web application. HttpSessionEvent(HttpSession) - Constructor for class javax.servlet.http.HttpSessionEvent Construct a session event from the given source. HttpSessionListener - interface javax.servlet.http.HttpSessionListener. Implementations of this interface are notified of changes to the list of active sessions in a web application. HttpUtils - class javax.servlet.http.HttpUtils. Deprecated. As of Java(tm) Servlet API 2.3. These methods were only useful with the default encoding and have been moved to the request interfaces. HttpUtils() - Constructor for class javax.servlet.http.HttpUtils Deprecated. Constructs an empty HttpUtils object. -------------------------------------------------------------------------------- I include(ServletRequest, ServletResponse) - Method in interface javax.servlet.RequestDispatcher Includes the content of a resource (servlet, JSP page, HTML file) in the response. init() - Method in class javax.servlet.GenericServlet A convenience method which can be overridden so that there's no need to call super.init(config). init(FilterConfig) - Method in interface javax.servlet.Filter Called by the web container to indicate to a filter that it is being placed into service. init(ServletConfig) - Method in interface javax.servlet.Servlet Called by the servlet container to indicate to a servlet that the servlet is being placed into service. init(ServletConfig) - Method in class javax.servlet.GenericServlet Called by the servlet container to indicate to a servlet that the servlet is being placed into service. invalidate() - Method in interface javax.servlet.http.HttpSession Invalidates this session then unbinds any objects bound to it. isCommitted() - Method in interface javax.servlet.ServletResponse Returns a boolean indicating if the response has been committed. isCommitted() - Method in class javax.servlet.ServletResponseWrapper The default behavior of this method is to return isCommitted() on the wrapped response object. isNew() - Method in interface javax.servlet.http.HttpSession Returns true if the client does not yet know about the session or if the client chooses not to join the session. isPermanent() - Method in class javax.servlet.UnavailableException Returns a boolean indicating whether the servlet is permanently unavailable. isRequestedSessionIdFromCookie() - Method in interface javax.servlet.http.HttpServletRequest Checks whether the requested session ID came in as a cookie. isRequestedSessionIdFromCookie() - Method in class javax.servlet.http.HttpServletRequestWrapper The default behavior of this method is to return isRequestedSessionIdFromCookie() on the wrapped request object. isRequestedSessionIdFromUrl() - Method in interface javax.servlet.http.HttpServletRequest Deprecated. As of Version 2.1 of the Java Servlet API, use HttpServletRequest.isRequestedSessionIdFromURL() instead. isRequestedSessionIdFromUrl() - Method in class javax.servlet.http.HttpServletRequestWrapper The default behavior of this method is to return isRequestedSessionIdFromUrl() on the wrapped request object. isRequestedSessionIdFromURL() - Method in interface javax.servlet.http.HttpServletRequest Checks whether the requested session ID came in as part of the request URL. isRequestedSessionIdFromURL() - Method in class javax.servlet.http.HttpServletRequestWrapper The default behavior of this method is to return isRequestedSessionIdFromURL() on the wrapped request object. isRequestedSessionIdValid() - Method in interface javax.servlet.http.HttpServletRequest Checks whether the requested session ID is still valid. isRequestedSessionIdValid() - Method in class javax.servlet.http.HttpServletRequestWrapper The default behavior of this method is to return isRequestedSessionIdValid() on the wrapped request object. isSecure() - Method in class javax.servlet.ServletRequestWrapper The default behavior of this method is to return isSecure() on the wrapped request object. isSecure() - Method in interface javax.servlet.ServletRequest Returns a boolean indicating whether this request was made using a secure channel, such as HTTPS. isUserInRole(String) - Method in interface javax.servlet.http.HttpServletRequest Returns a boolean indicating whether the authenticated user is included in the specified logical "role". isUserInRole(String) - Method in class javax.servlet.http.HttpServletRequestWrapper The default behavior of this method is to return isUserInRole(String role) on the wrapped request object. -------------------------------------------------------------------------------- J javax.servlet - package javax.servlet This chapter describes the javax.servlet package. javax.servlet.http - package javax.servlet.http This chapter describes the javax.servlet.http package. -------------------------------------------------------------------------------- L log(Exception, String) - Method in interface javax.servlet.ServletContext Deprecated. As of Java Servlet API 2.1, use ServletContext.log(String message, Throwable throwable) instead. This method was originally defined to write an exception's stack trace and an explanatory error message to the servlet log file. log(String) - Method in interface javax.servlet.ServletContext Writes the specified message to a servlet log file, usually an event log. log(String) - Method in class javax.servlet.GenericServlet Writes the specified message to a servlet log file, prepended by the servlet's name. log(String, Throwable) - Method in interface javax.servlet.ServletContext Writes an explanatory message and a stack trace for a given Throwable exception to the servlet log file. log(String, Throwable) - Method in class javax.servlet.GenericServlet Writes an explanatory message and a stack trace for a given Throwable exception to the servlet log file, prepended by the servlet's name. -------------------------------------------------------------------------------- P parsePostData(int, ServletInputStream) - Static method in class javax.servlet.http.HttpUtils Deprecated. Parses data from an HTML form that the client sends to the server using the HTTP POST method and the application/x-www-form-urlencoded MIME type. parseQueryString(String) - Static method in class javax.servlet.http.HttpUtils Deprecated. Parses a query string passed from the client to the server and builds a HashTable object with key-value pairs. print(boolean) - Method in class javax.servlet.ServletOutputStream Writes a boolean value to the client, with no carriage return-line feed (CRLF) character at the end. print(char) - Method in class javax.servlet.ServletOutputStream Writes a character to the client, with no carriage return-line feed (CRLF) at the end. print(double) - Method in class javax.servlet.ServletOutputStream Writes a double value to the client, with no carriage return-line feed (CRLF) at the end. print(float) - Method in class javax.servlet.ServletOutputStream Writes a float value to the client, with no carriage return-line feed (CRLF) at the end. print(int) - Method in class javax.servlet.ServletOutputStream Writes an int to the client, with no carriage return-line feed (CRLF) at the end. print(long) - Method in class javax.servlet.ServletOutputStream Writes a long value to the client, with no carriage return-line feed (CRLF) at the end. print(String) - Method in class javax.servlet.ServletOutputStream Writes a String to the client, without a carriage return-line feed (CRLF) character at the end. println() - Method in class javax.servlet.ServletOutputStream Writes a carriage return-line feed (CRLF) to the client. println(boolean) - Method in class javax.servlet.ServletOutputStream Writes a boolean value to the client, followed by a carriage return-line feed (CRLF). println(char) - Method in class javax.servlet.ServletOutputStream Writes a character to the client, followed by a carriage return-line feed (CRLF). println(double) - Method in class javax.servlet.ServletOutputStream Writes a double value to the client, followed by a carriage return-line feed (CRLF). println(float) - Method in class javax.servlet.ServletOutputStream Writes a float value to the client, followed by a carriage return-line feed (CRLF). println(int) - Method in class javax.servlet.ServletOutputStream Writes an int to the client, followed by a carriage return-line feed (CRLF) character. println(long) - Method in class javax.servlet.ServletOutputStream Writes a long value to the client, followed by a carriage return-line feed (CRLF). println(String) - Method in class javax.servlet.ServletOutputStream Writes a String to the client, followed by a carriage return-line feed (CRLF). putValue(String, Object) - Method in interface javax.servlet.http.HttpSession Deprecated. As of Version 2.2, this method is replaced by HttpSession.setAttribute(java.lang.String, java.lang.Object) -------------------------------------------------------------------------------- R readLine(byte[], int, int) - Method in class javax.servlet.ServletInputStream Reads the input stream, one line at a time. removeAttribute(String) - Method in interface javax.servlet.ServletContext Removes the attribute with the given name from the servlet context. removeAttribute(String) - Method in class javax.servlet.ServletRequestWrapper The default behavior of this method is to call removeAttribute(String name) on the wrapped request object. removeAttribute(String) - Method in interface javax.servlet.ServletRequest Removes an attribute from this request. removeAttribute(String) - Method in interface javax.servlet.http.HttpSession Removes the object bound with the specified name from this session. removeValue(String) - Method in interface javax.servlet.http.HttpSession Deprecated. As of Version 2.2, this method is replaced by HttpSession.removeAttribute(java.lang.String) requestDestroyed(ServletRequestEvent) - Method in interface javax.servlet.ServletRequestListener The request is about to go out of scope of the web application. RequestDispatcher - interface javax.servlet.RequestDispatcher. Defines an object that receives requests from the client and sends them to any resource (such as a servlet, HTML file, or JSP file) on the server. requestInitialized(ServletRequestEvent) - Method in interface javax.servlet.ServletRequestListener The request is about to come into scope of the web application. reset() - Method in interface javax.servlet.ServletResponse Clears any data that exists in the buffer as well as the status code and headers. reset() - Method in class javax.servlet.ServletResponseWrapper The default behavior of this method is to call reset() on the wrapped response object. resetBuffer() - Method in interface javax.servlet.ServletResponse Clears the content of the underlying buffer in the response without clearing headers or status code. resetBuffer() - Method in class javax.servlet.ServletResponseWrapper The default behavior of this method is to call resetBuffer() on the wrapped response object. -------------------------------------------------------------------------------- S SC_ACCEPTED - Static variable in interface javax.servlet.http.HttpServletResponse Status code (202) indicating that a request was accepted for processing, but was not completed. SC_BAD_GATEWAY - Static variable in interface javax.servlet.http.HttpServletResponse Status code (502) indicating that the HTTP server received an invalid response from a server it consulted when acting as a proxy or gateway. SC_BAD_REQUEST - Static variable in interface javax.servlet.http.HttpServletResponse Status code (400) indicating the request sent by the client was syntactically incorrect. SC_CONFLICT - Static variable in interface javax.servlet.http.HttpServletResponse Status code (409) indicating that the request could not be completed due to a conflict with the current state of the resource. SC_CONTINUE - Static variable in interface javax.servlet.http.HttpServletResponse Status code (100) indicating the client can continue. SC_CREATED - Static variable in interface javax.servlet.http.HttpServletResponse Status code (201) indicating the request succeeded and created a new resource on the server. SC_EXPECTATION_FAILED - Static variable in interface javax.servlet.http.HttpServletResponse Status code (417) indicating that the server could not meet the expectation given in the Expect request header. SC_FORBIDDEN - Static variable in interface javax.servlet.http.HttpServletResponse Status code (403) indicating the server understood the request but refused to fulfill it. SC_FOUND - Static variable in interface javax.servlet.http.HttpServletResponse Status code (302) indicating that the resource reside temporarily under a different URI. SC_GATEWAY_TIMEOUT - Static variable in interface javax.servlet.http.HttpServletResponse Status code (504) indicating that the server did not receive a timely response from the upstream server while acting as a gateway or proxy. SC_GONE - Static variable in interface javax.servlet.http.HttpServletResponse Status code (410) indicating that the resource is no longer available at the server and no forwarding address is known. SC_HTTP_VERSION_NOT_SUPPORTED - Static variable in interface javax.servlet.http.HttpServletResponse Status code (505) indicating that the server does not support or refuses to support the HTTP protocol version that was used in the request message. SC_INTERNAL_SERVER_ERROR - Static variable in interface javax.servlet.http.HttpServletResponse Status code (500) indicating an error inside the HTTP server which prevented it from fulfilling the request. SC_LENGTH_REQUIRED - Static variable in interface javax.servlet.http.HttpServletResponse Status code (411) indicating that the request cannot be handled without a defined Content-Length. SC_METHOD_NOT_ALLOWED - Static variable in interface javax.servlet.http.HttpServletResponse Status code (405) indicating that the method specified in the Request-Line is not allowed for the resource identified by the Request-URI. SC_MOVED_PERMANENTLY - Static variable in interface javax.servlet.http.HttpServletResponse Status code (301) indicating that the resource has permanently moved to a new location, and that future references should use a new URI with their requests. SC_MOVED_TEMPORARILY - Static variable in interface javax.servlet.http.HttpServletResponse Status code (302) indicating that the resource has temporarily moved to another location, but that future references should still use the original URI to access the resource. SC_MULTIPLE_CHOICES - Static variable in interface javax.servlet.http.HttpServletResponse Status code (300) indicating that the requested resource corresponds to any one of a set of representations, each with its own specific location. SC_NO_CONTENT - Static variable in interface javax.servlet.http.HttpServletResponse Status code (204) indicating that the request succeeded but that there was no new information to return. SC_NON_AUTHORITATIVE_INFORMATION - Static variable in interface javax.servlet.http.HttpServletResponse Status code (203) indicating that the meta information presented by the client did not originate from the server. SC_NOT_ACCEPTABLE - Static variable in interface javax.servlet.http.HttpServletResponse Status code (406) indicating that the resource identified by the request is only capable of generating response entities which have content characteristics not acceptable according to the accept headers sent in the request. SC_NOT_FOUND - Static variable in interface javax.servlet.http.HttpServletResponse Status code (404) indicating that the requested resource is not available. SC_NOT_IMPLEMENTED - Static variable in interface javax.servlet.http.HttpServletResponse Status code (501) indicating the HTTP server does not support the functionality needed to fulfill the request. SC_NOT_MODIFIED - Static variable in interface javax.servlet.http.HttpServletResponse Status code (304) indicating that a conditional GET operation found that the resource was available and not modified. SC_OK - Static variable in interface javax.servlet.http.HttpServletResponse Status code (200) indicating the request succeeded normally. SC_PARTIAL_CONTENT - Static variable in interface javax.servlet.http.HttpServletResponse Status code (206) indicating that the server has fulfilled the partial GET request for the resource. SC_PAYMENT_REQUIRED - Static variable in interface javax.servlet.http.HttpServletResponse Status code (402) reserved for future use. SC_PRECONDITION_FAILED - Static variable in interface javax.servlet.http.HttpServletResponse Status code (412) indicating that the precondition given in one or more of the request-header fields evaluated to false when it was tested on the server. SC_PROXY_AUTHENTICATION_REQUIRED - Static variable in interface javax.servlet.http.HttpServletResponse Status code (407) indicating that the client MUST first authenticate itself with the proxy. SC_REQUEST_ENTITY_TOO_LARGE - Static variable in interface javax.servlet.http.HttpServletResponse Status code (413) indicating that the server is refusing to process the request because the request entity is larger than the server is willing or able to process. SC_REQUEST_TIMEOUT - Static variable in interface javax.servlet.http.HttpServletResponse Status code (408) indicating that the client did not produce a request within the time that the server was prepared to wait. SC_REQUEST_URI_TOO_LONG - Static variable in interface javax.servlet.http.HttpServletResponse Status code (414) indicating that the server is refusing to service the request because the Request-URI is longer than the server is willing to interpret. SC_REQUESTED_RANGE_NOT_SATISFIABLE - Static variable in interface javax.servlet.http.HttpServletResponse Status code (416) indicating that the server cannot serve the requested byte range. SC_RESET_CONTENT - Static variable in interface javax.servlet.http.HttpServletResponse Status code (205) indicating that the agent SHOULD reset the document view which caused the request to be sent. SC_SEE_OTHER - Static variable in interface javax.servlet.http.HttpServletResponse Status code (303) indicating that the response to the request can be found under a different URI. SC_SERVICE_UNAVAILABLE - Static variable in interface javax.servlet.http.HttpServletResponse Status code (503) indicating that the HTTP server is temporarily overloaded, and unable to handle the request. SC_SWITCHING_PROTOCOLS - Static variable in interface javax.servlet.http.HttpServletResponse Status code (101) indicating the server is switching protocols according to Upgrade header. SC_TEMPORARY_REDIRECT - Static variable in interface javax.servlet.http.HttpServletResponse Status code (307) indicating that the requested resource resides temporarily under a different URI. SC_UNAUTHORIZED - Static variable in interface javax.servlet.http.HttpServletResponse Status code (401) indicating that the request requires HTTP authentication. SC_UNSUPPORTED_MEDIA_TYPE - Static variable in interface javax.servlet.http.HttpServletResponse Status code (415) indicating that the server is refusing to service the request because the entity of the request is in a format not supported by the requested resource for the requested method. SC_USE_PROXY - Static variable in interface javax.servlet.http.HttpServletResponse Status code (305) indicating that the requested resource MUST be accessed through the proxy given by the Location field. sendError(int) - Method in class javax.servlet.http.HttpServletResponseWrapper The default behavior of this method is to call sendError(int sc) on the wrapped response object. sendError(int) - Method in interface javax.servlet.http.HttpServletResponse Sends an error response to the client using the specified status code and clearing the buffer. sendError(int, String) - Method in class javax.servlet.http.HttpServletResponseWrapper The default behavior of this method is to call sendError(int sc, String msg) on the wrapped response object. sendError(int, String) - Method in interface javax.servlet.http.HttpServletResponse Sends an error response to the client using the specified status. sendRedirect(String) - Method in class javax.servlet.http.HttpServletResponseWrapper The default behavior of this method is to return sendRedirect(String location) on the wrapped response object. sendRedirect(String) - Method in interface javax.servlet.http.HttpServletResponse Sends a temporary redirect response to the client using the specified redirect location URL. service(HttpServletRequest, HttpServletResponse) - Method in class javax.servlet.http.HttpServlet Receives standard HTTP requests from the public service method and dispatches them to the doXXX methods defined in this class. service(ServletRequest, ServletResponse) - Method in interfac
Fundamentals of the JavaMail API Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Table of Contents If you're viewing this document online, you can click any of the topics below to link directly to that section. 1. Tutorial tips 2 2. Introducing the JavaMail API 3 3. Reviewing related protocols 4 4. Installing JavaMail 6 5. Reviewing the core classes 8 6. Using the JavaMail API 13 7. Searching with SearchTerm 21 8. Exercises 22 9. Wrapup 32 Fundamentals of the JavaMail API Page 1 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Section 1. Tutorial tips Should I take this tutorial? Looking to incorporate mail facilities into your platform-independent Java solutions? Look no further than the JavaMail API, which offers a protocol-independent model for working with IMAP, POP, SMTP, MIME, and all those other Internet-related messaging protocols. With the help of the JavaBeans Activation Framework (JAF), your applications can now be mail-enabled through the JavaMail API. Concepts After completing this module you will understand the: * Basics of the Internet mail protocols SMTP, POP3, IMAP, and MIME * Architecture of the JavaMail framework * Connections between the JavaMail API and the JavaBeans Activation Framework Objectives By the end of this module you will be able to: * Send and read mail using the JavaMail API * Deal with sending and receiving attachments * Work with HTML messages * Use search terms to search for messages Prerequisites Instructions on how to download and install the JavaMail API are contained in the course. In addition, you will need a development environment such as the JDK 1.1.6+ or the Java 2 Platform, Standard Edition (J2SE) 1.2.x or 1.3.x. A general familiarity with object-oriented programming concepts and the Java programming language is necessary. The Java language essentials tutorial can help. copyright 1996-2000 Magelang Institute dba jGuru Contact jGuru has been dedicated to promoting the growth of the Java technology community through evangelism, education, and software since 1995. You can find out more about their activities, including their huge collection of FAQs at jGuru.com . To send feedback to jGuru about this course, send mail to producer@jguru.com . Course author: Formerly with jGuru.com , John Zukowski does strategic Java consulting for JZ Ventures, Inc. His latest book is titled Java Collections from Apress . Fundamentals of the JavaMail API Page 2 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Section 2. Introducing the JavaMail API What is the JavaMail API? The JavaMail API is an optional package (standard extension) for reading, composing, and sending electronic messages. You use the package to create Mail User Agent (MUA) type programs, similar to Eudora, pine, and Microsoft Outlook. The API's main purpose is not for transporting, delivering, and forwarding messages; this is the purview of applications such as sendmail and other Mail Transfer Agent (MTA) type programs. MUA-type programs let users read and write e-mail, whereas MUAs rely on MTAs to handle the actual delivery. The JavaMail API is designed to provide protocol-independent access for sending and receiving messages by dividing the API into two parts: * The first part of the API is the focus of this course --basically, how to send and receive messages independent of the provider/protocol. * The second part speaks the protocol-specific languages, like SMTP, POP, IMAP, and NNTP. With the JavaMail API, in order to communicate with a server, you need a provider for a protocol. The creation of protocol-specific providers is not covered in this course because Sun provides a sufficient set for free. Fundamentals of the JavaMail API Page 3 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Section 3. Reviewing related protocols Introduction Before looking into the JavaMail API specifics, let's step back and take a look at the protocols used with the API. There are basically four that you'll come to know and love: * SMTP * POP * IMAP * MIME You will also run across NNTP and some others. Understanding the basics of all the protocols will help you understand how to use the JavaMail API. While the API is designed to be protocol agnostic, you can't overcome the limitations of the underlying protocols. If a capability isn't supported by a chosen protocol, the JavaMail API doesn't magically add the capability on top of it. (As you'll soon see, this can be a problem when working with POP.) SMTP The Simple Mail Transfer Protocol (SMTP) is defined by RFC 821 . It defines the mechanism for delivery of e-mail. In the context of the JavaMail API, your JavaMail-based program will communicate with your company or Internet Service Provider's (ISP's) SMTP server. That SMTP server will relay the message on to the SMTP server of the recipient(s) to eventually be acquired by the user(s) through POP or IMAP. This does not require your SMTP server to be an open relay, as authentication is supported, but it is your responsibility to ensure the SMTP server is configured properly. There is nothing in the JavaMail API for tasks like configuring a server to relay messages or to add and remove e-mail accounts. POP POP stands for Post Office Protocol. Currently in version 3, also known as POP3, RFC 1939 defines this protocol. POP is the mechanism most people on the Internet use to get their mail. It defines support for a single mailbox for each user. That is all it does, and that is also the source of a lot of confusion. Much of what people are familiar with when using POP, like the ability to see how many new mail messages they have, are not supported by POP at all. These capabilities are built into programs like Eudora or Microsoft Outlook, which remember things like the last mail received and calculate how many are new for you. So, when using the JavaMail API, if you want this type of information, you have to calculate it yourself. IMAP IMAP is a more advanced protocol for receiving messages. Defined in RFC 2060 , IMAP stands for Internet Message Access Protocol, and is currently in version 4, also known as IMAP4. When using IMAP, your mail server must support the protocol. You can't just change your program to use IMAP instead of POP and expect everything in IMAP to be supported. Assuming your mail server supports IMAP, your JavaMail-based program can take Fundamentals of the JavaMail API Page 4 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks advantage of users having multiple folders on the server and these folders can be shared by multiple users. Due to the more advanced capabilities, you might think IMAP would be used by everyone. It isn't. It places a much heavier burden on the mail server, requiring the server to receive the new messages, deliver them to users when requested, and maintain them in multiple folders for each user. While this does centralize backups, as users' long-term mail folders get larger and larger, everyone suffers when disk space is exhausted. With POP, saved messages get offloaded from the mail server. MIME MIME stands for Multipurpose Internet Mail Extensions. It is not a mail transfer protocol. Instead, it defines the content of what is transferred: the format of the messages, attachments, and so on. There are many different documents that take effect here: RFC 822 , RFC 2045 , RFC 2046 , and RFC 2047 . As a user of the JavaMail API, you usually don't need to worry about these formats. However, these formats do exist and are used by your programs. NNTP and others Because of the split of the JavaMail API between provider and everything else, you can easily add support for additional protocols. Sun maintains a list of third-party providers that take advantage of protocols for which Sun does not provide out-of-the-box support. You'll find support for NNTP (Network News Transport Protocol) [newsgroups], S/MIME (Secure Multipurpose Internet Mail Extensions), and more. Fundamentals of the JavaMail API Page 5 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Section 4. Installing JavaMail Introduction There are two versions of the JavaMail API commonly used today: 1.2 and 1.1.3. All the examples in this course will work with both. While 1.2 is the latest, 1.1.3 is the version included with the 1.2.1 version of the Java 2 Platform, Enterprise Edition (J2EE), so it is still commonly used. The version of the JavaMail API you want to use affects what you download and install. All will work with JDK 1.1.6+, Java 2 Platform, Standard Edition (J2SE) version 1.2.x, and J2SE version 1.3.x. Note: After installing Sun's JavaMail implementation, you can find many example programs in the demo directory. Installing JavaMail 1.2 To use the JavaMail 1.2 API, download the JavaMail 1.2 implementation, unbundle the javamail-1_2.zip file, and add the mail.jar file to your CLASSPATH. The 1.2 implementation comes with an SMTP, IMAP4, and POP3 provider besides the core classes. After installing JavaMail 1.2, install the JavaBeans Activation Framework. Installing JavaMail 1.1.3 To use the JavaMail 1.1.3 API, download the JavaMail 1.1.3 implementation, unbundle the javamail1_1_3.zip file, and add the mail.jar file to your CLASSPATH. The 1.1.3 implementation comes with an SMTP and IMAP4 provider, besides the core classes. If you want to access a POP server with JavaMail 1.1.3, download and install a POP3 provider. Sun has one available separate from the JavaMail implementation. After downloading and unbundling pop31_1_1.zip, add pop3.jar to your CLASSPATH, too. After installing JavaMail 1.1.3, install the JavaBeans Activation Framework. Installing the JavaBeans Activation Framework All versions of the JavaMail API require the JavaBeans Activation Framework. The framework adds support for typing arbitrary blocks of data and handling it accordingly. This doesn't sound like much, but it is your basic MIME-type support found in many browsers and mail tools today. After downloading the framework, unbundle the jaf1_0_1.zip file, and add the activation.jar file to your CLASSPATH. For JavaMail 1.2 users, you should now have added mail.jar and activation.jar to your CLASSPATH. For JavaMail 1.1.3 users, you should now have added mail.jar, pop3.jar, and activation.jar to your CLASSPATH. If you have no plans of using POP3, you don't Fundamentals of the JavaMail API Page 6 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks need to add pop3.jar to your CLASSPATH. If you don't want to change the CLASSPATH environment variable, copy the jar files to your lib/ext directory under the Java Runtime Environment (JRE) directory. For instance, for the J2SE 1.3 release, the default directory would be C:\jdk1.3\jre\lib\ext on a Windows platform. Using JavaMail with the Java 2 Enterprise Edition If you use J2EE, there is nothing special you have to do to use the basic JavaMail API; it comes with the J2EE classes. Just make sure the j2ee.jar file is in your CLASSPATH and you're all set. For J2EE 1.2.1, the POP3 provider comes separately, so download and follow the steps to include the POP3 provider as shown in the previous section "Installing JavaMail 1.1.3." J2EE 1.3 users get the POP3 provider with J2EE so do not require the separate installation. Neither installation requires you to install the JavaBeans Activation Framework. Exercise Exercise 1. How to set up a JavaMail environment on page 22 Fundamentals of the JavaMail API Page 7 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Section 5. Reviewing the core classes Introduction Before taking a how-to approach at looking at the JavaMail classes in depth, this section walks you through the core classes that make up the API: Session, Message, Address, Authenticator, Transport, Store, and Folder. All these classes are found in the top-level package for the JavaMail API, javax.mail, though you'll frequently find yourself using subclasses found in the javax.mail.internet package. Session The Session class defines a basic mail session. It is through this session that everything else works. The Session object takes advantage of a java.util.Properties object to get information like mail server, username, password, and other information that can be shared across your entire application. The constructors for the class are private. You can get a single default session that can be shared with the getDefaultInstance() method: Properties props = new Properties(); // fill props with any information Session session = Session.getDefaultInstance(props, null); Or, you can create a unique session with getInstance(): Properties props = new Properties(); // fill props with any information Session session = Session.getDefaultInstance(props, null); In both cases, the null argument is an Authenticator object that is not being used at this time. In most cases, it is sufficient to use the shared session, even if working with mail sessions for multiple user mailboxes. You can add the username and password combination in at a later step in the communication process, keeping everything separate. Message Once you have your Session object, it is time to move on to creating the message to send. This is done with a type of Message . Because Message is an abstract class, you must work with a subclass, in most cases javax.mail.internet.MimeMessage .A MimeMessage is an e-mail message that understands MIME types and headers, as defined in the different RFCs. Message headers are restricted to US-ASCII characters only, though non-ASCII characters can be encoded in certain header fields. To create a Message, pass along the Session object to the MimeMessage constructor: MimeMessage message = new MimeMessage(session); Fundamentals of the JavaMail API Page 8 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Note: There are other constructors, like for creating messages from RFC822-formatted input streams. Once you have your message, you can set its parts, as Message implements the Part interface (with MimeMessage implementing MimePart ). The basic mechanism to set the content is the setContent() method, with arguments for the content and the mime type: message.setContent("Hello", "text/plain"); If, however, you know you are working with a MimeMessage and your message is plain text, you can use its setText() method, which only requires the actual content, defaulting to the MIME type of text/plain: message.setText("Hello"); For plain text messages, the latter form is the preferred mechanism to set the content. For sending other kinds of messages, like HTML messages, use the former. For setting the subject, use the setSubject() method: message.setSubject("First"); Address Once you've created the Session and the Message, as well as filled the message with content, it is time to address your letter with an Address . Like Message, Address is an abstract class. You use the javax.mail.internet.InternetAddress class. To create an address with just the e-mail address, pass the e-mail address to the constructor: Address address = new InternetAddress("president@whitehouse.gov"); If you want a name to appear next to the e-mail address, you can pass that along to the constructor, too: Address address = new InternetAddress("president@whitehouse.gov", "George Bush"); You will need to create address objects for the message's from field as well as the to field. Unless your mail server prevents you, there is nothing stopping you from sending a message that appears to be from anyone. Once you've created the addresses, you connect them to a message in one of two ways. For identifying the sender, you use the setFrom() and setReplyTo() methods. message.setFrom(address) If your message needs to show multiple from addresses, use the addFrom() method: Fundamentals of the JavaMail API Page 9 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Address address[] = ...; message.addFrom(address); For identifying the message recipients, you use the addRecipient() method. This method requires a Message.RecipientType besides the address. message.addRecipient(type, address) The three predefined types of address are: * Message.RecipientType.TO * Message.RecipientType.CC * Message.RecipientType.BCC So, if the message was to go to the vice president, sending a carbon copy to the first lady, the following would be appropriate: Address toAddress = new InternetAddress("vice.president@whitehouse.gov"); Address ccAddress = new InternetAddress("first.lady@whitehouse.gov"); message.addRecipient(Message.RecipientType.TO, toAddress); message.addRecipient(Message.RecipientType.CC, ccAddress); The JavaMail API provides no mechanism to check for the validity of an e-mail address. While you can program in support to scan for valid characters (as defined by RFC 822) or verify the MX (mail exchange) record yourself, these are all beyond the scope of the JavaMail API. Authenticator Like the java.net classes, the JavaMail API can take advantage of an Authenticator to access protected resources via a username and password. For the JavaMail API, that resource is the mail server. The JavaMail Authenticator is found in the javax.mail package and is different from the java.net class of the same name. The two don't share the same Authenticator as the JavaMail API works with Java 1.1, which didn't have the java.net variety. To use the Authenticator, you subclass the abstract class and return a PasswordAuthentication instance from the getPasswordAuthentication() method. You must register the Authenticator with the session when created. Then, your Authenticator will be notified when authentication is necessary. You could pop up a window or read the username and password from a configuration file (though if not encrypted is not secure), returning them to the caller as a PasswordAuthentication object. Properties props = new Properties(); // fill props with any information Authenticator auth = new MyAuthenticator(); Session session = Session.getDefaultInstance(props, auth); Transport The final part of sending a message is to use the Transport class. This class speaks the Fundamentals of the JavaMail API Page 10 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks protocol-specific language for sending the message (usually SMTP). It's an abstract class and works something like Session. You can use the default version of the class by just calling the static send() method: Transport.send(message); Or, you can get a specific instance from the session for your protocol, pass along the username and password (blank if unnecessary), send the message, and close the connection: message.saveChanges(); // implicit with send() Transport transport = session.getTransport("smtp"); transport.connect(host, username, password); transport.sendMessage(message, message.getAllRecipients()); transport.close(); This latter way is best when you need to send multiple messages, as it will keep the connection with the mail server active between messages. The basic send() mechanism makes a separate connection to the server for each method call. Note: To watch the mail commands go by to the mail server, set the debug flag with session.setDebug(true). Store and folder Getting messages starts similarly to sending messages with a Session. However, after getting the session, you connect to a Store , quite possibly with a username and password or Authenticator. Like Transport, you tell the Store what protocol to use: // Store store = session.getStore("imap"); Store store = session.getStore("pop3"); store.connect(host, username, password); After connecting to the Store, you can then get a Folder , which must be opened before you can read messages from it: Folder folder = store.getFolder("INBOX"); folder.open(Folder.READ_ONLY); Message message[] = folder.getMessages(); For POP3, the only folder available is the INBOX. If you are using IMAP, you can have other folders available. Note: Sun's providers are meant to be smart. While Message message[] = folder.getMessages(); might look like a slow operation reading every message from the server, only when you actually need to get a part of the message is the message content retrieved. Once you have a Message to read, you can get its content with getContent() or write its content to a stream with writeTo(). The getContent() method only gets the message content, while writeTo() output includes headers. Fundamentals of the JavaMail API Page 11 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks System.out.println(((MimeMessage)message).getContent()); Once you're done reading mail, close the connection to the folder and store. folder.close(aBoolean); store.close(); The boolean passed to the close() method of folder states whether or not to update the folder by removing deleted messages. Moving on Essentially, understanding how to use these seven classes is all you need for nearly everything with the JavaMail API. Most of the other capabilities of the JavaMail API build off these seven classes to do something a little different or in a particular way, like if the content is an attachment. Certain tasks, like searching, are isolated and are discussed later. Fundamentals of the JavaMail API Page 12 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Section 6. Using the JavaMail API Introduction You've seen how to work with the core parts of the JavaMail API. In the following sections you'll find a how-to approach for connecting the pieces to do specific tasks. Sending messages Sending an e-mail message involves getting a session, creating and filling a message, and sending it. You can specify your SMTP server by setting the mail.smtp.host property for the Properties object passed when getting the Session: String host = ...; String from = ...; String to = ...; // Get system properties Properties props = System.getProperties(); // Setup mail server props.put("mail.smtp.host", host); // Get session Session session = Session.getDefaultInstance(props, null); // Define message MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject("Hello JavaMail"); message.setText("Welcome to JavaMail"); // Send message Transport.send(message); You should place the code in a try-catch block, as setting up the message and sending it can throw exceptions. Exercise: Exercise 2. How to send your first message on page 23 Fetching messages For reading mail, you get a session, get and connect to an appropriate store for your mailbox, open the appropriate folder, and get your messages. Also, don't forget to close the connection when done. String host = ...; String username = ...; String password = ...; // Create empty properties Properties props = new Properties(); // Get session Session session = Session.getDefaultInstance(props, null); Fundamentals of the JavaMail API Page 13 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks // Get the store Store store = session.getStore("pop3"); store.connect(host, username, password); // Get folder Folder folder = store.getFolder("INBOX"); folder.open(Folder.READ_ONLY); // Get directory Message message[] = folder.getMessages(); for (int i=0, n=message.length; iedReader reader = new BufferedReader ( new InputStreamReader(System.in)); // Get directory Message message[] = folder.getMessages(); for (int i=0, n=message.length; ied with the messages. There are different flags for different states, some system-defined and some user-defined. The predefined flags are defined in the inner class Flags.Flag and are listed below: * Flags.Flag.ANSWERED * Flags.Flag.DELETED * Flags.Flag.DRAFT * Flags.Flag.FLAGGED * Flags.Flag.RECENT * Flags.Flag.SEEN * Flags.Flag.USER Fundamentals of the JavaMail API Page 14 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Just because a flag exists doesn't mean the flag is supported by all mail servers or providers. For instance, except for deleting messages, the POP protocol supports none of them. Checking for new mail is not a POP task but a task built into mail clients. To find out what flags are supported, ask the folder with getPermanentFlags(). To delete messages, you set the message's DELETED flag: message.setFlag(Flags.Flag.DELETED, true); Open up the folder in READ_WRITE mode first though: folder.open(Folder.READ_WRITE); Then, when you are done processing all messages, close the folder, passing in a true value to expunge the deleted messages. folder.close(true); There is an expunge() method of Folder that can be used to delete the messages. However, it doesn't work for Sun's POP3 provider. Other providers may or may not implement the capabilities. It will more than likely be implemented for IMAP providers. Because POP only supports single access to the mailbox, you have to close the folder to delete the messages with Sun's provider. To unset a flag, just pass false to the setFlag() method. To see if a flag is set, check it with isSet(). Authenticating yourself You learned that you can use an Authenticator to prompt for username and password when needed, instead of passing them in as strings. Here you'll actually see how to more fully use authentication. Instead of connecting to the Store with the host, username, and password, you configure the Properties to have the host, and tell the Session about your custom Authenticator instance, as shown here: // Setup properties Properties props = System.getProperties(); props.put("mail.pop3.host", host); // Setup authentication, get session Authenticator auth = new PopupAuthenticator(); Session session = Session.getDefaultInstance(props, auth); // Get the store Store store = session.getStore("pop3"); store.connect(); You then subclass Authenticator and return a PasswordAuthentication object from the getPasswordAuthentication() method. The following is one such implementation, with a single field for both. (This isn't a Project Swing tutorial; just enter the two parts in the one field, separated by a comma.) Fundamentals of the JavaMail API Page 15 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks import javax.mail.*; import javax.swing.*; import java.util.*; public class PopupAuthenticator extends Authenticator { public PasswordAuthentication getPasswordAuthentication() { String username, password; String result = JOptionPane.showInputDialog( "Enter 'username,password'"); StringTokenizer st = new StringTokenizer(result, ","); username = st.nextToken(); password = st.nextToken(); return new PasswordAuthentication(username, password); } } Because the PopupAuthenticator relies on Swing, it will start up the event-handling thread for AWT. This basically requires you to add a call to System.exit() in your code to stop the program. Replying to messages The Message class includes a reply() method to configure a new Message with the proper recipient and subject, adding "Re: " if not already there. This does not add any content to the message, only copying the from or reply-to header to the new recipient. The method takes a boolean parameter indicating whether to reply to only the sender (false) or reply to all (true). MimeMessage reply = (MimeMessage)message.reply(false); reply.setFrom(new InternetAddress("president@whitehouse.gov")); reply.setText("Thanks"); Transport.send(reply); To configure the reply-to address when sending a message, use the setReplyTo() method. Exercise: Exercise 4. How to reply to mail on page 27 Forwarding messages Forwarding messages is a little more involved. There is no single method to call, and you build up the message to forward by working with the parts that make up a message. A mail message can be made up of multiple parts. Each part is a BodyPart , or more specifically, a MimeBodyPart when working with MIME messages. The different body parts get combined into a container called Multipart or, again, more specifically a MimeMultipart . To forward a message, you create one part for the text of your message and a second part with the message to forward, and combine the two into a multipart. Then you add the multipart to a properly addressed message and send it. That's essentially it. To copy the content from one message to another, just copy over its Fundamentals of the JavaMail API Page 16 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks DataHandler , a class from the JavaBeans Activation Framework. // Create the message to forward Message forward = new MimeMessage(session); // Fill in header forward.setSubject("Fwd: " + message.getSubject()); forward.setFrom(new InternetAddress(from)); forward.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // Create your new message part BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText( "Here you go with the original message:\n\n"); // Create a multi-part to combine the parts Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); // Create and fill part for the forwarded content messageBodyPart = new MimeBodyPart(); messageBodyPart.setDataHandler(message.getDataHandler()); // Add part to multi part multipart.addBodyPart(messageBodyPart); // Associate multi-part with message forward.setContent(multipart); // Send message Transport.send(forward); Working with attachments Attachments are resources associated with a mail message, usually kept outside of the message like a text file, spreadsheet, or image. As with common mail programs like Eudora and pine, you can attach resources to your mail message with the JavaMail API and get those attachments when you receive the message. Sending attachments: Sending attachments is quite like forwarding messages. You build up the parts to make the complete message. After the first part, your message text, you add other parts where the DataHandler for each is your attachment, instead of the shared handler in the case of a forwarded message. If you are reading the attachment from a file, your attachment data source is a FileDataSource . Reading from a URL, it is a URLDataSource . Once you have your DataSource, just pass it on to the DataHandler constructor, before finally attaching it to the BodyPart with setDataHandler(). Assuming you want to retain the original filename for the attachment, the last thing to do is to set the filename associated with the attachment with the setFileName() method of BodyPart. All this is shown here: // Define message Message message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject("Hello JavaMail Attachment"); // Create the message part BodyPart messageBodyPart = new MimeBodyPart(); // Fill the message messageBodyPart.setText("Pardon Ideas"); Fundamentals of the JavaMail API Page 17 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); // Part two is attachment messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(filename); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(filename); multipart.addBodyPart(messageBodyPart); // Put parts in message message.setContent(multipart); // Send the message Transport.send(message); When including attachments with your messages, if your program is a servlet, your users must upload the attachment besides telling you where to send the message. Uploading each file can be handled with a form encoding type of multipart/form-data.
Note: Message size is limited by your SMTP server, not the JavaMail API. If you run into problems, consider increasing the Java heap size by setting the ms and mx parameters. Exercise: Exercise 5. How to send attachments on page 28 Getting attachments: Getting attachments out of your messages is a little more involved then sending them because MIME has no simple notion of attachments. The content of your message is a Multipart object when it has attachments. You then need to process each Part, to get the main content and the attachment(s). Parts marked with a disposition of Part.ATTACHMENT from part.getDisposition() are clearly attachments. However, attachments can also come across with no disposition (and a non-text MIME type) or a disposition of Part.INLINE. When the disposition is either Part.ATTACHMENT or Part.INLINE, you can save off the content for that message part. Just get the original filename with getFileName() and the input stream with getInputStream(). Multipart mp = (Multipart)message.getContent(); for (int i=0, n=multipart.getCount(); ied to the end of the filename until one is found that doesn't exist. // from saveFile() File file = new File(filename); Fundamentals of the JavaMail API Page 18 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks for (int i=0; file.exists(); i++) { file = new File(filename+i); } The code above covers the simplest case where message parts are flagged appropriately. To cover all cases, handle when the disposition is null and get the MIME type of the part to handle accordingly. if (disposition == null) { // Check if plain MimeBodyPart mbp = (MimeBodyPart)part; if (mbp.isMimeType("text/plain")) { // Handle plain } else { // Special non-attachment cases here of image/gif, text/html, ... } ... } Processing HTML messages Sending HTML-based messages can be a little more work than sending plain text message, though it doesn't have to be that much more work. It all depends on your specific requirements. Sending HTML messages: If all you need to do is send the equivalent of an HTML file as the message and let the mail reader worry about fetching any embedded images or related pieces, use the setContent() method of Message, passing along the content as a String and setting the content type to text/html. String htmlText = "

Hello

" + "http://www.jguru.com/images/logo.gif\">"; message.setContent(htmlText, "text/html")); On the receiving end, if you fetch the message with the JavaMail API, there is nothing built into the API to display the message as HTML. The JavaMail API only sees it as a stream of bytes. To display the message as HTML, you must either use the Swing JEditorPane or some third-party HTML viewer component. if (message.getContentType().equals("text/html")) { String content = (String)message.getContent(); JFrame frame = new JFrame(); JEditorPane text = new JEditorPane("text/html", content); text.setEditable(false); JScrollPane pane = new JScrollPane(text); frame.getContentPane().add(pane); frame.setSize(300, 300); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.show(); } Including images with your messages: On the other hand, if you want your HTML content message to be complete, with embedded images included as part of the message, you must treat the image as an attachment and reference the image with a special cid URL, where the cid is a reference to the Content-ID header of the image attachment. The process of embedding an image is quite similar to attaching a file to a message, the only Fundamentals of the JavaMail API Page 19 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks difference is you have to tell the MimeMultipart that the parts are related by setting its subtype in the constructor (or with setSubType()) and set the Content-ID header for the image to a random string which is used as the src for the image in the img tag. The following demonstrates this completely. String file = ...; // Create the message Message message = new MimeMessage(session); // Fill its headers message.setSubject("Embedded Image"); message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // Create your new message part BodyPart messageBodyPart = new MimeBodyPart(); String htmlText = "

Hello

" + ""; messageBodyPart.setContent(htmlText, "text/html"); // Create a related multi-part to combine the parts MimeMultipart multipart = new MimeMultipart("related"); multipart.addBodyPart(messageBodyPart); // Create part for the image messageBodyPart = new MimeBodyPart(); // Fetch the image and associate to part DataSource fds = new FileDataSource(file); messageBodyPart.setDataHandler(new DataHandler(fds)); messageBodyPart.setHeader("Content-ID","memememe"); // Add part to multi-part multipart.addBodyPart(messageBodyPart); // Associate multi-part with message message.setContent(multipart); Exercise: Exercise 6. How to send HTML messages with images on page 29 Fundamentals of the JavaMail API Page 20 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Section 7. Searching with SearchTerm Introduction The JavaMail API includes a filtering mechanism found in the javax.mail.search package to build up a SearchTerm . Once built, you then ask a Folder what messages match, retrieving an array of Message objects: SearchTerm st = ...; Message[] msgs = folder.search(st); There are 22 different classes available to help you build a search term. * AND terms (class AndTerm) * OR terms (class OrTerm) * NOT terms (class NotTerm) * SENT DATE terms (class SentDateTerm) * CONTENT terms (class BodyTerm) * HEADER terms (FromTerm / FromStringTerm, RecipientTerm / RecipientStringTerm, SubjectTerm, etc..) Essentially, you build up a logical expression for matching messages, then search. For instance the following term searches for messages with a (partial) subject string of ADV or a from field of friend@public.com. You might consider periodically running this query and automatically deleting any messages returned. SearchTerm st = new OrTerm( new SubjectTerm("ADV:"), new FromStringTerm("friend@public.com")); Message[] msgs = folder.search(st); Fundamentals of the JavaMail API Page 21 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Section 8. Exercises About the exercises These exercises are designed to provide help according to your needs. For example, you might simply complete the exercise given the information and the task list in the exercise body; you might want a few hints; or you may want a step-by-step guide to successfully complete a particular exercise. You can use as much or as little help as you need per exercise. Moreover, because complete solutions are also provided, you can skip a few exercises and still be able to complete future exercises requiring the skipped ones. Each exercise has a list of any prerequisite exercises, a list of skeleton code for you to start with, links to necessary API pages, and a text description of the exercise goal. In addition, there is help for each task and a solutions page with links to files that comprise a solution to the exercise. Exercise 1. How to set up a JavaMail environment In this exercise you will install Sun's JavaMail reference implementation. After installing, you will be introduced to the demonstration programs that come with the reference implementation. Task 1: Download the latest version of the JavaMail API implementation from Sun. Task 2: Download the latest version of the JavaBeans Activation Framework from Sun. Task 3: Unzip the downloaded packages. You get a ZIP file for all platforms for both packages. Help for task 3: You can use the jar tool to unzip the packages. Task 4: Add the mail.jar file from the JavaMail 1.2 download and the activation.jar file from the JavaBeans Activation Framework download to your CLASSPATH. Help for task 4: Copy the files to your extension library directory. For Microsoft Windows, using the default installation copy, the command might look like the following: cd \javamail-1.2 copy mail.jar \jdk1.3\jre\lib\ext cd \jaf-1.0.1 copy activation.jar \jdk1.3\jre\lib\ext If you don't like copying the files to the extension library directory, detailed instructions are available from Sun for setting your CLASSPATH on Windows NT. Task 5: Go into the demo directory that comes with the JavaMail API implementation and compile the msgsend program to send a test message. Help for task 5: javac msgsend.java Fundamentals of the JavaMail API Page 22 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Task 6: Execute the program passing in a from address with the -o option, your SMTP server with the -M option, and the to address (with no option). You'll then enter the subject, the text of your message, and the end-of-file character (CTRL-Z) to signal the end of the message input. Help for task 6: Be sure to replace the from address, SMTP server, and to address. java msgsend -o from@address -M SMTP.Server to@address If you are not sure of your SMTP server, contact your system administrator or check with your Internet Service Provider. Task 7: Check to make sure you received the message with your normal mail reader (Eudora, Outlook Express, pine, ...). Exercise 1. How to set up a JavaMail environment: Solution Upon successful completion, the JavaMail reference implementation will be in your CLASSPATH. Exercise 2. How to send your first message In the last exercise you sent a mail message using the demonstration program provided with the JavaMail implementation. In this exercise, you'll create the program yourself. For more help with exercises, see About the exercises on page 22 . Prerequisites: * Exercise 1. How to set up a JavaMail environment on page 22 Skeleton code: * MailExample.java Task 1: Starting with the skeleton code , get the system Properties. Help for task 1: Properties props = System.getProperties(); Task 2: Add the name of your SMTP server to the properties for the mail.smtp.host key. Fundamentals of the JavaMail API Page 23 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Help for task 2: props.put("mail.smtp.host", host); Task 3: Get a Session object based on the Properties. Help for task 3: Session session = Session.getDefaultInstance(props, null); Task 4: Create a MimeMessage from the session. Help for task 4: MimeMessage message = new MimeMessage(session); Task 5: Set the from field of the message. Help for task 5: message.setFrom(new InternetAddress(from)); Task 6: Set the to field of the message. Help for task 6: message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); Task 7: Set the subject of the message. Help for task 7: message.setSubject("Hello JavaMail"); Task 8: Set the content of the message. Help for task 8: message.setText("Welcome to JavaMail"); Task 9: Use a Transport to send the message. Help for task 9: Transport.send(message); Task 10: Compile and run the program, passing your SMTP server, from address, and to address on the command line. Fundamentals of the JavaMail API Page 24 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Help for task 10: java MailExample SMTP.Server from@address to@address Task 11: Check to make sure you received the message with your normal mail reader (Eudora, Outlook Express, pine, ...). Exercise 2. How to send your first message: Solution The following Java source file represents a solution to this exercise: * Solution/MailExample.java Exercise 3. How to check for mail In this exercise, create a program that displays the from address and subject for each message and prompts to display the message content. For more help with exercises, see About the exercises on page 22 . Prerequisites: * Exercise 1. How to set up a JavaMail environment on page 22 Skeleton Code * GetMessageExample.java Task 1: Starting with the skeleton code , get or create a Properties object. Help for task 1: Properties props = new Properties(); Task 2: Get a Session object based on the Properties. Help for task 2: Session session = Session.getDefaultInstance(props, null); Task 3: Get a Store for your e-mail protocol, either pop3 or imap. Help for task 3: Store store = session.getStore("pop3"); Task 4: Connect to your mail host's store with the appropriate username and password. Fundamentals of the JavaMail API Page 25 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Help for task 4: store.connect(host, username, password); Task 5: Get the folder you want to read. More than likely, this will be the INBOX. Help for task 5: Folder folder = store.getFolder("INBOX"); Task 6: Open the folder read-only. Help for task 6: folder.open(Folder.READ_ONLY); Task 7: Get a directory of the messages in the folder. Save the message list in an array variable named message. Help for task 7: Message message[] = folder.getMessages(); Task 8: For each message, display the from field and the subject. Help for task 8: System.out.println(i + ": " + message[i].getFrom()[0] + "\t" + message[i].getSubject()); Task 9: Display the message content when prompted. Help for task 9: System.out.println(message[i].getContent()); Task 10: Close the connection to the folder and store. Help for task 10: folder.close(false); store.close(); Task 11: Compile and run the program, passing your mail server, username, and password on the command line. Answer YES to the messages you want to read. Just hit ENTER if you don't. If you want to stop reading your mail before making your way through all the messages, enter QUIT. Help for task 11: java GetMessageExample POP.Server username password Fundamentals of the JavaMail API Page 26 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Exercise 3. How to check for mail: Solution The following Java source file represents a solution to this exercise. * Solution/GetMessageExample.java Exercise 4. How to reply to mail In this exercise, create a program that creates a canned reply message and attaches the original message if it's plain text. For more help with exercises, see About the exercises on page 22 . Prerequisites: * Exercise 3. How to check for mail on page 25 Skeleton Code: * ReplyExample.java Task 1: The skeleton code already includes the code to get the list of messages from the folder and prompt you to create a reply. Task 2: When answered affirmatively, create a new MimeMessage from the original message. Help for task 2: MimeMessage reply = (MimeMessage)message[i].reply(false); Task 3: Set the from field to your e-mail address. Task 4: Create the text for the reply. Include a canned message to start. When the original message is plain text, add each line of the original message, prefix each line with the "> " characters. Help for task 4: To check for plain text messages, check the messages MIME type with mimeMessage.isMimeType("text/plain"). Task 5: Set the message's content, once the message content is fully determined. Task 6: Send the message. Task 7: Compile and run the program, passing your mail server, SMTP server, username, password, and from address on the command line. Answer YES to the messages you want to send replies. Just hit ENTER if you don't. If you want to stop going through your mail before Fundamentals of the JavaMail API Page 27 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks making your way through all the messages, enter QUIT. Help for task 7: java ReplyExample POP.Server SMTP.Server username password from@address Task 8: Check to make sure you received the message with your normal mail reader (Eudora, Outlook Express, pine, ...). Exercise 4. How to reply to mail: Solution The following Java source file represents a solution to this exercise. * Solution/ReplyExample.java Exercise 5. How to send attachments In this exercise, create a program that sends a message with an attachment. For more help with exercises, see About the exercises on page 22 . Prerequisites: * Exercise 2. How to send your first message on page 23 Skeleton Code: * AttachExample.java Task 1: The skeleton code already includes the code to get the initial mail session. Task 2: From the session, get a Message and set its header fields: to, from, and subject. Task 3: Create a BodyPart for the main message content and fill its content with the text of the message. Help for task 3: BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText("Here's the file"); Task 4: Create a Multipart to combine the main content with the attachment. Add the main content to the multipart. Help for task 4: Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); Fundamentals of the JavaMail API Page 28 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Task 5: Create a second BodyPart for the attachment. Task 6: Get the attachment as a DataSource. Help for task 6: DataSource source = new FileDataSource(filename); Task 7: Set the DataHandler for the message part to the data source. Carry the original filename along. Help for task 7: messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(filename); Task 8: Add the second part of the message to the multipart. Task 9: Set the content of the message to the multipart. Help for task 9: message.setContent(multipart); Task 10: Send the message. Task 11: Compile and run the program, passing your SMTP server, from address, to address, and filename on the command line. This will send the file as an attachment. Help for task 11: java AttachExample SMTP.Server from@address to@address filename Task 12: Check to make sure you received the message with your normal mail reader (Eudora, Outlook Express, pine, ...). Exercise 5. How to send attachments: Solution The following Java source file represents a solution to this exercise. * Solution/AttachExample.java Exercise 6. How to send HTML messages with images In this exercise, create a program that sends an HTML message with an image attachment where the image is displayed within the HTML message. Fundamentals of the JavaMail API Page 29 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks For more help with exercises, see About the exercises on page 22 . Prerequisites: * Exercise 5. How to send attachments on page 28 Skeleton code: * logo.gif * HtmlImageExample.java Task 1: The skeleton code already includes the code to get the initial mail session, create the main message, and fill its headers (to, from, subject). Task 2: Create a BodyPart for the HTML message content. Task 3: Create a text string of the HTML content. Include a reference in the HTML to an image () that is local to the mail message. Help for task 3: Use a cid URL. The content-id will need to be specified for the image later. String htmlText = "

Hello

" + ""; Task 4: Set the content of the message part. Be sure to specify the MIME type is text/html. Help for task 4: messageBodyPart.setContent(htmlText, "text/html"); Task 5: Create a Multipart to combine the main content with the attachment. Be sure to specify that the parts are related. Add the main content to the multipart. Help for task 5: MimeMultipart multipart = new MimeMultipart("related"); multipart.addBodyPart(messageBodyPart); Task 6: Create a second BodyPart for the attachment. Task 7: Get the attachment as a DataSource, and set the DataHandler for the message part to the data source. Task 8: Set the Content-ID header for the part to match the image reference specified in the HTML. Help for task 8: messageBodyPart.setHeader("Content-ID","memememe"); Task 9: Add the second part of the message to the multipart, and set the content of the Fundamentals of the JavaMail API Page 30 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks message to the multipart. Task 10: Send the message. Task 11: Compile and run the program, passing your SMTP server, from address, to address, and filename on the command line. This will send the images as an inline image within the HTML text. Help for task 11: java HtmlImageExample SMTP.Server from@address to@address filename Task 12: Check if your mail reader recognizes the message as HTML and displays the image within the message, instead of as a link to an external attachment file. Help for task 12: If your mail reader can't display HTML messages, consider sending the message to a friend. Exercise 6. How to send HTML messages with images: Solution The following Java source files represent a solution to this exercise. * Solution/logo.gif * Solution/HtmlImageExample.java Fundamentals of the JavaMail API Page 31 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Section 9. Wrapup In summary The JavaMail API is a Java package used for reading, composing, and sending e-mail messages and their attachments. It lets you build standards-based e-mail clients that employ various Internet mail protocols, including SMTP, POP, IMAP, and MIME, as well as related protocols such as NNTP, S/MIME, and others. The API divides naturally into two parts. The first focuses on sending, receiving, and managing messages independent of the protocol used, whereas the second focuses on specific use of the protocols. The purpose of this tutorial was to show how to use the first part of the API, without attempting to deal with protocol providers. The core JavaMail API consists of seven classes --Session, Message, Address, Authenticator, Transport, Store, and Folder --all of which are found in javax.mail, the top-level package for the JavaMail API. We used these classes to work through a number of common e-mail-related tasks, including sending messages, retrieving messages, deleting messages, authenticating, replying to messages, forwarding messages, managing attachments, processing HTML-based messages, and searching or filtering mail lists. Finally, we provided a number of step-by-step exercises to help illustrate the concepts presented. Hopefully, this will help you add e-mail functionality to your platform-independent Java applications. Resources You can do much more with the JavaMail API than what's found here. The lessons and exercises found here can be supplemented by the following resources: * Download the JavaMail 1.2 API from the JavaMail API home page . * The JavaBeans Activation Framework is required for versions 1.2 and 1.1.3 of the JavaMail API. * The JavaMail-interest mailing list is a Sun-hosted discussion forum for developers. * Sun's JavaMail FAQ addresses the use of JavaMail in applets and servlets, as well as prototol-specific questions. * Tutorial author John Zukowski maintains jGuru's JavaMail FAQ . * Want to see how others are using JavaMail? Check out Sun's list of third-party products. * If you want more detail about JavaMail, read Rick Grehan's "How JavaMail keeps it simple" (Lotus Developer Network, June 2000). * Benoit Marchal shows how to use Java and XML to produce plain text and HTML newsletters in this two-part series, "Managing e-zines with JavaMail and XSLT" Part 1 (developerWorks, March 2001) and Part 2 (developerWorks, April 2001). * "Linking Applications with E-mail" (Lotus Developer Network, May 2000) discusses how groupware can facilitate communication, collaboration, and coordination among applications. Fundamentals of the JavaMail API Page 32 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Feedback Please let us know whether this tutorial was helpful to you and how we could make it better. We'd also like to hear about other tutorial topics you'd like to see covered. Thanks! For questions about the content of this tutorial, contact the author John Zukowski ( jaz@zukowski.net ) Colophon This tutorial was written entirely in XML, using the developerWorks Toot-O-Matic tutorial generator. The Toot-O-Matic tool is a short Java program that uses XSLT stylesheets to convert the XML source into a number of HTML pages, a zip file, JPEG heading graphics, and PDF files. Our ability to generate multiple text and binary formats from a single source file illustrates the power and flexibility of XML. Fundamentals of the JavaMail API Page 33

81,091

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧