Home
Sun Java System Web Server 70 Developer`s Guide to Java Web
Contents
1. ssssssssseeeeee 37 Sec ring a Web Service cose co biete c adis vs eg de RR Rd UR NL D MR and addas 39 Admin Console Tasks for Message Security sse 40 Y To Createa Message Security Provider i see e teet teet ie iin tees 40 V To Delete a Message Security Provider c scesssssessessesseeseesscsessseeesssesesseesessseseesssesnsseeseees 42 Deploying WebServices voted evt UR OON DURO UR ONUS 43 Testing Web Services i ase tarsi eredi e ibd dio ee d idein nie cenas 43 VW To Invoke a Web Service Client siisii siivin ire eemper tpe ie iae cepere 43 Web Services Samples itd dere ret rea dtd un eie eate e ee dee e e ea 44 Developing Servlets About Servlets D Servlet Data FLOW 4 ere rri o D UR Fe OT E E HOO T E He odit 46 Servlet TypeSsoudiota t nts E E sede tan oai edited 46 Creating Servlets sraoin a rao gene terere PO ee ede e TN 47 Creating the Class Declatation uehementer 47 Overriding Methods Ovyerriding InLt iisocioneio nere tom EG Qao OR GEO UR EG QE ONERE ED QE OR He EE Overriding Destroy resurge d neitetiattentadaiisi entendida deerit 48 Overriding Service Get and POSE i secte dee odia rei d eer eed edid 49 Accessing Parameters and Storing Data cccessssssesssesessseseeseessessesesseeseessesesssesessseneneeseesees 50 Handling Sessions and Security ice icd eciam ht E a deti i ice delta gae Handling Threading Issues Delivering Client Results
2. 78 ma size Optional The size ofthe inputbox The default is 50 maxlength Optional The maxlength of the inputbox The default is 50 cssClass Optional The CSS class Usage slws queryBox size 30 gt This example creates an inputbox with default name qt and size 30 submitButton Tag This tag creates a submit button Attributes The submitButton tag uses the following attributes name Optional The name ofthe button The default is sb default Optional The default value ofthe button which will be search cssClass Optional The CSS class name style The CSS style image The optional image for the button Usage slws submitButton cssClass navBar style padding 0px margin 0px width 5Qpx gt This example creates a submit button with default name sb formAction Tag This tag performs the following sections This tag handles form action It retrieves all elements on the search form Validates that there is at least one collection is selected and the query is not empty and passes the values on to search and results tags as parents or through the page context Attributes The formAction tag uses the following attributes formld Specifies the name ofthe form If not specified the default form searchForm will be used Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications JSP Search Tags ElemColl Optional The name ofthe Collection ele
3. Caching Servlet Results 56 Sun Java System Web Server 7 0 can cache the results of invoking a servlet a JSP page or any URL pattern to make subsequent invocations of the same servlet JSP page or URL pattern faster The Sun Java System Web Server 7 0 caches the request results for a specific amount of time In this way if another data call occurs the Sun Java System Web Server 7 0 can return the cached data instead of performing the operation again For example if your servlet returns a stock quote that updates every 5 minutes you set the cache to expire after 300 seconds If caching is enabled Sun Java System Web Server 7 0 can cache the results produced by the servlet javax servlet RequestDispatcher include or javax servlet RequestDispatcher forward In Sun ONE releases the result generated by aresource for which caching was enabled was never cached if that resource was the target ofa javax servlet RequestDispatcher include or javax servlet RequestDispatcher forward This result cached only ifthe resource was the target ofthe initial request lt sun web app gt lt cache enable true gt lt cache mapping gt lt servlet name gt TestServlet lt servlet name gt lt dispatcher gt REQUEST lt dispatcher gt lt dispatcher gt FORWARD lt dispatcher gt lt cahce mapping gt lt cache gt lt sun web app gt Whether to cache results and how to cache them depends on the data involved For example you do not need to
4. Once this security is established Web Services security will be applied to all Web Services applications deployed on the Web Server Chapter3 WebServices Overview 39 Securing Web Services 40 Configuring Application Specific Web Services Security Configure application specific web services during application assembly by defining message security binding elements in the applications Sun deployment descriptors Use these message security binding elements to associate a specific provider or message protection policy with a web services endpoint or service reference You can also qualify these elements so that they apply to a specific port or method ofthe corresponding endpoint or referenced service Admin Console Tasks for Message Security All the steps for setting up the Web Server for using message security can be accomplished using the Admin Console or the wadm command line tool For more information on message security see Sun Java System Web Server 7 0 Administrators Guide Support for message layer security is integrated into the Web Server in the form of pluggable authentication modules By default message layer security is disabled on the Web Server The tasks in this section provide the details for enabling creating editing and deleting message security configurations and providers Tocreate a message security provider To enable providers for message security To delete a message security provider To enable
5. JAX WS 2 0 JSR 224 The Java API for XML based JAX WS 2 0 is the key specification for component based web service development and governs the standard mappings between WSDL XML schema and the Java platform It is the next generation of JAX RPC JAXB 2 0 The Java architecture for XML Binding 2 0 JAXB defines an extensible mapping between the Java and XML schema type models and facilitates XML serialization of Java objects JAXP 1 3 1 The Java API for XML Processing 1 3 1 JAXP provides a standard framework for parsing and transforming XML documents and streams using the Simple API for XML SAX the Document Object Model DOM and Extensible Stylesheets Language Transformations XSLT SOAP 1 2 SOAP is a means for encoding remote procedure calls RPCs and document style information as XML WSDL 1 1 WSDL is an XML based standard for describing the external interface to a web service SAAJ 1 3 SOAP with Attachments API for Java SAAJ defines a simple object model for creating manipulating and sending SOAP messages XWSS XML Web Services Security XWSS provides a framework within which a Web service developer can secure applications For more information see http java sun com webservices xwss Fast Infoset The Fast Infoset specification ITU T Rec X 891 ISO IEC 24824 1 describes an open standards based binary XML format that is based on the XML Information Set It is an efficient alternative to XML For more info
6. The following table describes attributes for the constraint field element TABLEA 41 constraint field Attributes Attribute Default Value Description name none Specifies the input parameter name scope request parameter Optional Specifies the scope in which the input parameter can be present Allowed values are context attribute request header request parameter request cookie session id and session attribute cache on match true Optional If true caches the response if matching succeeds Overrides the same attribute in a value subelement Appendix A Deployment Descriptor Files 185 Elements in the sun web xml File TABLE A 41 constraint field Attributes Continued Attribute Default Value Description cache on match failure false Optional If true caches the response if matching fails Overrides the same attribute in a value subelement value Element This element specifies the value ofthe entity Subelements none Attributes none Classloader Element The Classloader element is named class loader class loader Element on page 186 class loader Element This element configures the classloader for the web application Subelements none Attributes The following table describes attributes for the class loader element TABLE A 42 class loader Attributes Attribute Default Value Description extra class path null Optional S
7. request policy auth recipient before content request policy auth recipient before content msgsecurity provider Chapter3 Web Services Overview 41 Securing Web Services 42 Example 3 2 Add the required property server config bin wadm set soap auth provider prop port 8989 user admin password file tmp admin passwd config test provider msgsecurity provider request policy auth source sender List the provider properties bin wadm get soap auth provider prop port 8989 user admin password file tmp admin passwd config test provider msgsecurity provider For more information about wadm commands and properties see Sun Java System Web Server 7 0 Administrators Configuration File Reference Enabling Providers for Message Security You can enable the message security Web Services endpoints by specifying the default provider on the server side or by specifying in the message binding element in sun web xml If you enable a default provider for message security you also need an appropriate message security on the client side Note You cannot specify a default provider using the Admin Console You have to specify the default provider through the wadm command line interface bin wadm set config prop port 8989 user admin password file tmp admin passwd config test default soap auth provider namesmsgsecurity provider To Delete a Message Security Provider Login to the Admin Console Selec
8. A cache element can contain max capacity timeout and enabled attributes The REQUIRED label means that a value must be supplied The IMPLIED label means that the attribute is optional and that Sun Java System Web Server 7 0 generates a default value Wherever possible explicit defaults for optional attributes such as t rue are listed Attribute declarations specify the type ofthe attribute For example CDATA means character data and boolean is a predefined enumeration Elements in the sun web xml File 156 This section describes the XML elements in the sun web xml file Elements are grouped as follows General Elements on page 157 Security Elements on page 161 Session Elements on page 163 Reference Elements on page 169 Caching Elements on page 177 Classloader Element on page 186 JSP Element on page 187 Internationalization Elements on page 189 This section also includes an alphabetical list of the elements for quick reference See Alphabetical List of sun web xml Elements on page 193 Note Subelements must be defined in the order in which they are listed in each section unless otherwise noted Each sun web xml file must begin with the following DOCTYPE header lt DOCTYPE sun web app PUBLIC Sun Microsystems Inc DTD Application Server 8 1 Servlet 2 4 EN http www sun com software appserver dtds sun web app 2 4 1 dtd gt Sun Java System Web Server 7 0
9. classpath path Overrides the java class path system property xpoweredBy Add the X Powered By response header trimSpaces Trims spaces in text templates between actions and directives smap Generates SMAP info for JSR 45 debugging dumpsmap Dumps SMAP info for JSR45 debugging into a file compilerSourceVWM release Provides source compatibility with specified JDK release compilerTargetVMrelease Generates class files for specified VM version For example this command compiles the hel lo JSP file and writes the compiled JSP under hellodir jspc d hellodir genclass hello jsp This command compiles all of the JSP files in the web application under webappdir into class files under jspclassdir jspc d jspclassdir genclass webapp webappdir To use either of these precompiled JSPs in a web application put the classes under hellodir or jspclassdir into a JAR file place the JAR file under WEB INF 1ib and set the reload interval property to 1in the sun web xml file Package Names Generated by the JSP Compiler When a JSP is compiled a package is created for it The package name starts with j spc For example the generated package name for SOURCE JSP myjsps hello jsp is precompiled as jspc webapp SOURCE d test1 test2 test3 The generated servlet is located in testl test2 test3 org apache jsp JSP myjsps hello jsp java and defined in org apache jsp JSP myjsps The path for hello jsp is derived from the directory in
10. if session null amp amp session getAttribute clearCache null gt mypfx flush lt gt JSP Search Tags Sun Java System Web Server 7 0 includes a set of JSP tags that can be used to customize the search query and search results pages in the search interface This section describes the tags and how they are used The search tag library is packaged into the install dir Vib webserv rt jar file which is always on the server classpath The sun web search tld tag description file can be found in the install dir Vib tlds directory you can copy this file into the WEB INF directory of your web application The search tags are as follows searchForm Tag on page 74 CollElem Tag on page 75 collection Tag on page 76 collltem Tag on page 77 queryBox Tag on page 77 submitButton Tag on page 78 formAction Tag on page 78 formSubmission Tag on page 79 formActionMsg Tag on page 79 search Tag on page 80 resultIteration Tag on page 80 Item Tag on page 81 resultStat Tag on page 81 resultNav Tag on page 81 Note The Sun Java System Web Server 7 0 search feature is compliant for internalization and supports multiple character encoding schemes in the same collection Custom JSPs that expose search can be in any encoding searchFormTag This tag constructs an HTML form that contains default hidden form elements such as the current search resul
11. 157 security role 162 servlet name 162 session timeout 93 98 168 web xml file 135 creating 135 example 196 more information about 113 webserv rt jar 70 74 97 204 Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications
12. Creating the Class Declaration on page 47 Overriding Methods on page 47 Overriding init on page 48 Overriding Destroy on page 48 Overriding Service Get and Post on page 49 Accessing Parameters and Storing Data on page 50 Handling Sessions and Security on page 50 Handling Threading Issues on page 50 Delivering Client Results on page 52 Creating the Class Declaration To create a servlet write a public Java class that includes basic I O support as well as the package javax servlet The class must extend either GenericServlet or HttpServlet Because Sun Java System Web Server 7 0 servlets exist in an HTTP environment the latter class is recommended If the servlet is part of a package you must also declare the package name so the class loader can properly locate it The following example header shows the HTTP servlet declaration called MyServlet import java io import javax servlet import javax servlet http public class myServlet extends HttpServlet servlet methods Overriding Methods Next override one or more methods to provide the servlet with instructions to perform its intended task All processing by a servlet is done on a request by request basis and happens in Chapter 4 Developing Servlets 47 Creating Servlets 48 the service methods either service for generic servlets or one of the doOperation methods for HTTP servlets This method accept
13. Enabling Web Applications on page 139 Dynamic Reloading of Web Applications on page 139 Classloaders on page 141 Web Application Structure Web applications have a directory structure which is fully accessible from a mapping to the application s document root for example hello The document root contains JSP files HTMI files and static files such as image files A WAR file web archive file contains a complete web application in compressed form A special directory under the document root WEB INF contains everything related to the application that is not in the public document tree ofthe application No file contained in WEB INF can be served directly to the client The contents of WEB INF include WEB INF classes The directory for servlet and other classes WEB INF web xml and WEB INF sun web xml XML based deployment descriptors that specify the web application configuration including mappings initialization parameters and security constraints 131 Deployment Tools The web application directory structure follows the structure outlined in the Java EE specification The following example shows a sample directory structure of a simple web application hello index jsp META INF MANIFEST MF WEB INF web xml sun web xml Deployment Tools 132 Using Sun Java Studio Enterprise 8 1 Sun Java System Web Server 7 0 supports Sun Java Studio Enterprise 8 1
14. Fetching the Client Certificate Using Web Services Message S curity n cecinere itii REE 118 Configuring the Web Server for Message Security see 118 Using Message Security Provider in an Application see 125 Programmatic Login asusin eei i ee e LECHE AERE Ra a oca eae E india Precautions 25e delsdiuitare datar A deen UR S a ie tI PERS IRR PN Reque ab Granting Programmatic Login Permission ProgrammaticLogin Class 2 2 2 decente in re e ta gogo o PESE Ted Ya eL o CER Contents 10 Enabling the Java Security Manager eene eret ios be tos iPt te totes pesa eot irn 128 The serverzpoticyFile crimen ie op D RU I Ra e D OR D UR de 128 Default Pertnissions 2 op eet e RERO RR ARA SRRIR SANA UE Pa dp ER REN SERES 129 Changing Permissions for an Application sse 129 Related Information ioo ced diede teen pH nne MENU TO DIY E 130 Deploying Web Applications sse tnnt entrent 131 Web Application Structure oi quaerere EE rae HERO eei qua ER D esee apta 131 Deployment Eools 2 5 trm t pet vete aper R dn OW we rn Ta dees 132 Using Sun Java Studio Enterprise 8 1 eee tee teinte ENANA 132 Using NetBeans IDE 5 5 ce dites etum iet T ROT RD aaeeei derse UR OE Mna ds 133 Y Tolmstall NetBeans IDE 5 5 2 4 trie tte inet eei dede ie ie Rorate 133 V To Register Web Server 7 0 in the NetBeans IDE 5 5 sse 133 V Deploying Web Applications sisian tdeo t
15. as follows listener listener class com sun appserv web taglibs cache CacheSessionListener listener class lt listener gt To use a cache with the application scope a web application does not need to specify any listener The com sun appserv web taglibs cache CacheContextListener is already specified in the sun web cache tld file The JSP cache tags are as follows cache Tag on page 71 flush Tag on page 73 cache Tag The cache tag enables you to cache fragments of your JSP pages It caches the body between the beginning and ending tags according to the attributes specified The first time the tag is encountered the body content is executed and cached Each subsequent time is run the cached content is checked to see whether it needs to be refreshed If so it is executed again and the cached data is refreshed Otherwise the cached data is served Attributes The following table describes attributes for the cache tag Chapter 5 Developing JavaServer Pages 71 JSP Cache Tags TABLE 5 3 cache Attributes Attribute Default Description key servletPath_suffix Optional The name used by the container to access the cached entry The cache key is added to the servlet path to generate a key to access the cached entry Ifno key is specified a number is generated according to the position of the tag in the page timeout 60s Optional The time in seconds after which the body of the tag
16. isset eain n EE En HER EH HS isni diessa anassa 83 Introducing SESSIONS anco hides eine tienne eese tesis Sessions and Cookies Sessions and URL Rewtiting iicet eie e Geb sei s aan 84 Sessions and SecuElty sitet rere a ire v ere rore dc eredi crece dete 84 Using DC 85 Creating or Accessing a Session sse aiie ne nennen 85 Examining Session Properties c cccssssssseesessseesssessesesnesseseesssneseesssneseesssnssnsseessansseensansseeseess 86 Binding Data t a Session wise cen opinan in ere udi aderit aae t e ida 87 Invalidating a Session S ssion Mana Gers aeneae ied petecip iege eee sev eee pet fent AE 89 memory ODtOT o o ea Se oic ee ed E QI GP Ne Eae LOIRE NE SEHE IER GeV eA ceddssvaaccvel osisbeedbadves 89 fileSession Manager ciiin iiie ee HER Ha Fe ert a et eer sete ha etse pod 90 I EDUNRESTRRBCENEIIS M 91 MMap Session Manager UNIX Only seeeeeeeeseetee tente tenttenttettnntentis nennt 97 Developing Lifecycle Listeners sseeeereern ertet nnne nennen 101 Server Lifecycle Events os iind eund diaeta aide E e dai da divo TERN 101 The LifecyctelListener Interface aeneae edet e i ave y ated nd d cde a 102 Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Contents Th tLifecyelleEvent Class 4 eniro t nen in De dO i OD edis 102 The Server Lifecycle Event Context sse tette tn
17. 0 Developer s Guide to Java Web Applications The server policy File Default Permissions Internal server code is granted all permissions by the AllPermission grant blocks to various parts of the server infrastructure code Do not modify these entries Application permissions are granted in the default grant block These permissions apply to all code not part of the internal server code listed previously A few permissions above the minimal set are also granted in the default server policy file These permissions are necessary due to various internal dependencies of the server implementation Java EE application developers should not rely on these additional permissions Changing Permissions for an Application The default policy for each instance limits the permissions of Java EE deployed applications to the minimal set of permissions required for these applications to operate correctly If you develop applications that require more than this default set of permissions you can edit the server policy file to add the custom permissions that your applications need You should add the extra permissions only to the applications that require them not to all applications deployed to a server instance Do not add extra permissions to the default set which is the grant block with no codebase which applies to all code Instead add a new grant block with a codebase specific to the application requiring the extra permissions and only add the
18. ACCORDEE Y COMPRIS DES GARANTIES CONCERNANT LA VALEUR MARCHANDE L APTITUDE DE LA PUBLICATION A REPONDRE A UNE UTILISATION PARTICULIERE OU LEFAIT QU ELLE NE SOIT PAS CONTREFAISANTE DE PRODUIT DE TIERS CE DENI DE GARANTIE NE S APPLIQUERAIT PAS DANS LA MESURE OU IL SERAIT TENU JURIDIQUEMENT NUL ET NON AVENU 0707260018135 Contents dL e 11 Web Server Technologies Overview eee 19 Technologies and Enhancements in Web Server 7 0 scsssssssesssssesssesessseseesseseessseesssesesssesnsseesetsneees 19 Supported Standards Protocols and Technologies ses 20 IERI P 22 Litecycle Listeners and Modules eee tite in dip ii an te ERI DRE ERE dede 23 Session Replication 43 80 0 UREROR UAE RU diu aiia eti dO RR OI E 23 API Changes from Web Server 61 to Web Server 7 0 sse 23 Web Applications Overview essent nennen tenentes 25 Java Web Applications pte ede UID TTL ISI HU d ie e OE IEEE 25 Developing and Deploying Web Applications eene 25 Creating Web Applications eese neni eee ern b er eripiet intente 26 About Securing Web Applications siiente ian tentent nentes 26 About Deploying Applications iere iter tr i endet been eet 27 About Virtual Servers 22e tamea tape ahi an o ce pae diode kant sete 27 About Default Web Applications eese tette tentent ter
19. Element on page 170 Zero or more Specifies runtime settings for a web service reference cache Element on page 177 Zero or one Configures caching for web application components class loader Element on page 186 Zero or one Specifies classloader configuration information Appendix A Deployment Descriptor Files 157 Elements in the sun web xml File TABLE A 2 sun web app Subelements Continued Element Required Description jsp config Element on Zero or one Specifies JSP configuration information page 187 Locale charset info zero or one Specifies internationalization settings Element on page 190 property Element on zero or more Specifies a property which has a name and a value page 160 message destination name zeroormore Specifies a logical message destination Element on page 192 webservice description Zero or more Specifies a web service description Element on page 192 Attributes none Properties The following table describes the properties for the sun web app element TABLEA 3 sun web app Properties Property Name Default Value Description crossContextAllowed true If true allows this web application to access the contexts of other web applications using the ServletContext getContext method encodeCookies true If true Sun Java System Web Server 7 0 URL encodes cookies before sending them to the client If you
20. SOAP layer message security providers installed with the Web Server to employ username password and X 509 certificate security tokens to authenticate and encrypt SOAP Web Services messages Username Tokens The Web Server uses username tokens in the SOAP messages to establish the authentication identity of the message sender The recipient of a message containing a Username token within an embedded password validates that the message sender is authorized to act as the user identified in the token by confirming that the sender knows the users secret password When using a Username token a valid user database must be configured on the Web Server Digital Signatures The Web Server uses XML Digital signatures to bind an authentication identity to the message content Clients use digital signatures to establish their caller identity analogous to basic authentication or SSL client certificate authentication Digital signatures are verified by the message receiver to authenticate the source of the message content which might be different from the sender ofthe message When using digital signatures valid keystore and truststore files must be configured on the Web Server Encryption The purpose of encryption is to modify the data such that it can only be understood by its intended audience This modification is accomplished by substituting an encrypted element for the original content When predicated on public key cryptography encryption estab
21. Standard Edition You can use Sun Java Studio to assemble and deploy web applications Sun Java Studio Enterprise 8 1 is based on NetBeans software and integrated with the Sun Java platform Sun Java Studio Enterprise 8 1 also supports NetBeans 5 5 Sun Java Studio support is available on all platforms supported by Sun Java Studio Enterprise 8 1 The plug in for the Web Server is obtained in the following ways From the Companion CD in the Sun Java Studio Enterprise 8 1 Media Kit Byusing the AutoUpdate feature of Sun Java Studio From the download center for Sun Java System Web Server 7 0 at http www sun com software download index jsp Note The Sun Java Studio Enterprise 8 1 for Sun Java System Web Server 7 0 works only with a local Web Server that is with the IDE and the Web Server on the same machine For information about using the web application features in Sun Java Studio Enterprise 8 1 explore the resources at http developers sun com prodtech javatools jsstandard reference docs index html The behavior ofthe Sun Java Studio Enterprise 8 1 plug in for Sun Java System Web Server 7 0 is the same as that for Sun Java System Application Server 8 If you re using the Web Application Tutorial at the site listed above for instance you would set the Sun Java System Web Server 7 0 instance as the default and then take the same actions described in the tutorial Sun Java System Web Server 7 0 Developer s Guide to Java Web Ap
22. Sun Java System Web Server 7 0 Troubleshooting Guide Troubleshooting Web Server Related Books The URL for all documentation about Sun Java Enterprise System Java ES and its components is http docs sun com app docs prod entsys 06g4 Default Paths and File Names The following table describes the default paths and file names that are used in this book Preface TABLEP 2 Default Paths and File Names Placeholder Description install dir Represents the base installation directory for Sun Java Default Value Sun Java Enterprise System Java ES installations on the Solaris platform opt SUNWwbsvr7 Java ES installations on the Linux and HP UX platform opt sun webserver Java ES installations on the Windows platform System Drive Program Files Sun JavaES5 WebServer7 Other Solaris Linux and HP UX installations non root user user s home directory sun webserver7 Other Solaris Linux and HP UX installations root user sun webserver7 Windows all installations System Drive Program Files Sun WebServer7 instance_dir Directory that contains the instance specific subdirectories For Java ES installations the default location for instances on Solaris var opt SUNWwbsvr7 For Java ES installations the default location for instances on Linux and HP UX var opt sun webserver7 For Java ES installations the default location for instance on Windows System Drive Program F
23. System Classloader loads the core Sun Java System Web Server 7 0 classes It is created based on the class path prefix server class path and class path suffix attributes of the jvm element in the server xml file The environment classpath is included if env cLasspath ignored false is set in the lt jvm gt element Only one instance of this classloader exists in the entire server If any changes are made to these attributes or classes the server must be restarted for the changes to take effect For more information about the lt j vm element in server xml see the Sun Java System Web Server 7 0 Administrators Configuration File Reference The Common Classloader loads classes in the instance dir lib classes directory followed by JAR and ZIP files in the instance dir lib directory The directories are optional If they don t exist the Common Classloader is not created If any changes are made to these classes restart the server Web Application The Web Application Classloader loads the servlets and other classes in a specific web application from WEB INF lib and WEB INF classes and from any additional classpaths specified in the extra class path attribute of the class loader element in sun web xml For more information see Classloader Element on page 186 An instance of this classloader is created for each web application If dynamic reloading has been enabled any changes made to these attributes or classes are r
24. Template data is anything not in the JSP specification including text and HTML tags For example minimal JSP file requires no processing by the JSP engine and is a static HTML page 65 Creating JSPs Sun Java System Web Server 7 0 compiles JSPs into HTTP servlets the first time they are called or they can be precompiled for better performance This processing makes them available to the application environment as standard objects and enables them to be called from a client using a URL JSPs run inside the Sun Java System Web Server 7 0 JSP engine which is responsible for interpreting tags that are specific to JSP and performing the actions they specify in order to generate dynamic content This content along with any template data surrounding it is assembled into an output page and is returned to the caller Creating JSPs 66 You can create JSPs basically the same way you create HTML files You can use an HTML editor to create pages and edit the page layout You make a page a JSP by inserting tags that are specific to JSP into the raw source code where needed and by giving the file a jsp extension In JSP 2 0 web application resources with an extension of j spx are interpreted as JSP documents JSPs specification distinguishes between two types classic syntax which is defined by the JSP specification itself and XML syntax also referred to as JSP documents For a summary of the JSP tags you can use see JSP Tag Libraries
25. Web Server 7 0 Developer s Guide to Java Web Applications Elements in the sun web xml File res ref name Element on page 175 resource env ref Element on page 169 resource env ref name Element on page 170 resource ref Element on page 175 role name Element on page 162 security role mapping Element on page 161 servlet Element on page 161 servlet name Element on page 162 service ref Element on page 170 session config Element on page 163 session manager Element on page 164 session properties Element on page 167 store properties Element on page 166 sun web app Element on page 157 timeout Element on page 183 url pattern Element on page 182 value Element on page 186 webservice description Element on page 192 webservice description name Element on page 193 webservice endpoint Element on page 120 Note For a list of sun web xmt elements by category see Elements in the sun web xml File on page 156 AppendixA Deployment Descriptor Files 195 Sample Web Application XML Files Sample Web Application XML Files 196 This section includes sample web xml and sun web xml files Sample web xml File on page 196 Sample sun web xml File on page 197 Sample web xml File The following is the sample web xml file web app xmlnsz http java sun com xml ns j2ee xmlns xsiz http www w3 0rg 2001 XMLSchema instance xsi schemaLocation http java sun com xml
26. a search in col1 and col2 using Java Web Service as the query string The search results are saved in pageContext with a session scope resultIteration Tag This tag retrieves the search results from either the parent search tag or the page context The tag iterates through the results and passing the searchitems to the item tags Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications JSP Search Tags Attributes The resultIteration tag uses the following attributes formId Specifies the name ofthe form associated with the search results The default form is used if the attribute is left empty If this tag is used without a form this attribute must be set as areference to the search tag m start Specifies an integer representing the starting position in the search results The default is 0 The value is retrieved from the parent formAction tag or pageContext or the parameter value numShown Specifies an integer indicating the number of results to be shown in one page The default is 20 The value is retrieved from the parent formAction tag or pageContext ItemTag This tag retrieves a searchitem from the Results parent tag and outputs its properties as specified by the property attribute Attributes Property Specifies a case sensitive string representing field names ina search item suchas title number score filename URL size and date resultStat Tag This tag returns numbers indicatin
27. a virtual server might replace the server wide default web xml with its own In that case a virtual server s default web xml is shared by all web application deployed on the virtual server Sun Java System Web Server Descriptors This section describes the Web Server descriptors The sun web app 2 4 1 dtd File 154 The sun web app_2_4 1 dtd file defines the structure of the sun web xml file including the elements it can contain and the subelements and attributes these elements can have The sun web app_2_4 1 dtd file is located in the install_dir lib dtds directory Note Do not edit the sun web app_2_4 1 dtd file Its contents change only with new versions of Sun Java System Web Server 7 0 For general information about DTD files and XML see the XML specification at http www w3 org TR 2004 REC xml 20040204 Each element defined in a DTD file which might be present in the corresponding XML file can contain subelements and attributes described in the following sections Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications The sun web app 2 4 1 dtdFile Subelements on page 155 Data on page 155 Attributes on page 156 Subelements Elements can contain subelements For example the following file fragment defines the cache element lt ELEMENT cache cache helper default helper property cache mapping gt The ELEMENT tag specifies thata cache element can contain cac
28. an error page Chapter6 Session Managers 85 Using Sessions Note The getSession method should be called before anything is written to the response stream For more information about getSession see the Java Servlet 2 4 specification Examining Session Properties Once a session ID has been established use the methods in the HttpSession interface to examine session properties Use the methods in the HttpServletRequest interface to examine request properties that relate to the session The following table shows the methods used to examine session properties TABLE6 1 HttpSession Methods HttpSession Method Description getCreationTime Returns the session time in milliseconds since January 1 1970 00 00 00 GMT getId Returns the assigned session identifier An HTTP session s identifier is a unique string that is created and maintained by the server getLastAccessedTime Returns the last time the client sent a request carrying the assigned session identifier or 1fora new session in milliseconds since January 1 1970 00 00 00 GMT isNew Returns a Boolean value indicating that the session is new A new session is one that the server has created and the client has not sent a request to it This state means the client has not acknowledged or joined the session and may not return the correct session identification information when making its next request For example String mySessionID mySe
29. auth source auth recipient Defines a requirement for message layer sender authentication for example username and password or content authentication for example digital signature Defines a requirement for message layer authentication of the receiver of a message to its sender for example by XML encryption The before content attribute value indicates that recipient authentication occurs before any content authentication with respect to the target of the containing auth policy sender or content before content or after content Implied Implied java method Element The syntax for the java method element is as follows lt ELEMENT java method method name method params gt TABLE8 9 java method Element Element name Occurrences Description Value method name 1 Name of the service method PCDATA method params Oorl List of the fully qualified Java type names of the method parameters Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Table 8 10 Using Web Services Message Security method params Element The syntax for method params method param element is as follows TABLE8 10 Attributes ofthe method params Element Element name Occurrences Description Value method params 0 or more Fully qualified Javatype PCDATA name of a method parameter message layer Entity The message layer entity
30. cache the results of a quiz submission because the input to the servlet is different each time However you could cache a high level report showing demographic data taken from quiz results that is updated once an hour You can define how a Sun Java System Web Server 7 0 web application handles response caching by editing specific fields in the sun web xml file In this way you can create programmatically standard servlets that still take advantage of this feature For more information about JSP caching see JSP Cache Tags on page 70 Features of Caching Sun Java System Web Server 7 0 has the following web application response caching capabilities Caching is configurable based on the servlet name or the URI Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Caching Servlet Results When caching is based on the URI the URI can include user specified parameters in the query string For example a response from garden catalog category roses is different from a response from garden catalog category lilies These responses are stored under different keys in the cache Cache size entry timeout and other caching behaviors are configurable Entry timeout is measured from the time an entry is created or refreshed You can override this timeout for an individual cache mapping by specifying the cache mapping element timeout You can determine caching criteria programmatically by writing a cache helpe
31. context root Element This element contains the web context root of the application or web applications This overrides the corresponding element in the web xml file Subelements none Attributes none Appendix A Deployment Descriptor Files 159 Elements in the sun web xml File 160 property Element Specifies a property that has a name and a value A property adds configuration information to its parent element that is optional with respect to Sun Java System Web Server 7 0 but Needed by a system or object that Sun Java System Web Server 7 0 doesn t have knowledge of such as an LDAP server ora Java class For example a manager properties element can include property subelements lt manager properties gt property name reapIntervalSeconds value 20 gt lt manager properties gt The properties that manager properties element uses depends on the value of the parent session manager element persistence type attribute For details see the description ofthe session manager element Subelement The following table describes subelement for the property element TABLEA 4 property Subelement Element Required Description description Element on zero or one Contains a text description of this element page 160 Attributes The following table describes attributes for the property element TABLEA 5 property Attributes Attribute Default Description name none Specifie
32. defines standardized locations and syntax by which security tokens such as X 509 certificates and Kerberos tickets can be carried within SOAP Headers in order to secure the contents of the SOAP message exchanges WS Security leverages the existing XML Digital Signature and XML Encryption specifications for capturing the results of signing and encryption operations in XML syntax In essence WS Security standardizes the XML Signature and XML Encryption data blocks that are carried with a SOAP message Sun Java System Web Server 7 0 supports the integrated WS Security standard In addition this release supports JSR 196 as applicable to Web Services Web Server provides the ability to bind SOAP layer message security providers and message protection policies to the container This binding allows the container to enforce the security on behalf of the applications 33 Technologies Supported in Web Server 7 0 Technologies Supported in Web Server 7 0 34 This section describes the technologies supported by Web Server 7 0 For more information see http java sun com webservices docs 2 0 tutorial doc index html This section contains the following topics Java Web Services Developer Pack 2 0 Technologies on page 34 Message Security JSR 196 on page 35 Java Web Services Developer Pack 2 0 Technologies Java Web Services Developer Pack provides an integrated development and test environment The technologies included with Web Server are
33. defines the value of the value of the auth layer attribute The syntax for message layer entity is lt Entity smessage layer SOAP Using Message Security Provider in an Application The following sub web xml example shows how to use the server xml message security provider providerlina web application lt xml versionz 1 0 encoding UTF 8 gles Copyright 2006 2007 Sun Microsystems Inc All rights reserved Use is subject to license terms lt DOCTYPE sun web app PUBLIC Sun Microsystems Inc DTD Application Server 8 1 Servlet 2 4 EN http www sun com software appserver dtds sun web app 2 4 1 dtd gt lt sun web app gt lt context root gt jaxws fromwsdl soap12 lt context root gt lt servlet gt lt servlet name gt f romwsdl lt servlet name gt lt webservices endpoint gt lt port component name gt f romwsdl soap12 lt port component name gt lt message security binding auth layer SOAP lt provider id gt providerl lt provider id gt lt message security binding gt lt webservices endpoint gt lt servlet gt lt sun web app gt Chapter 8 Securing Web Applications 125 Programmatic Login Note The port component name element should be the same as the name attribute in the endpoint element in sun jaxws xml If the provider id element is not specified in sun web xml then the default soap auth provider name configured in server xml is be used as the provider De
34. don t want cookies to be encoded add the following setting to sun web xmldirectly under the sun web app tag property name encodeCookies value false gt Do not embed this setting in any other tag 158 Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Elements in the sun web xml File TABLEA 3 sun web app Properties Continued Property Name Default Value Description tempdir instance dirlgenerated Specifies a temporary directory singleThreadedServletPoolSize for use by this web application This value is used to construct the value ofthe javax servlet context tempdir context attribute Compiled JSPs are also placed in this directory Specifies the maximum number of servlet instances allocated for each SingleThreadModel servlet in the web application reuseSessionID false Iftrue this property causes the web application to reuse the JSESSIONID value if present in the request header as the session ID when creating sessions The default behavior of web applications is not to reuse session IDs Instead applications generate cryptographically random session IDs for new sessions relativeRedirectAllowed false If true allows the web application to send a relative URL to the client using the HttpServletResponse sendRedirect API that is it suppresses the container from translating a relative URL to a fully qualified URL
35. ee dia a e Creating Web Deployment Descriptors i sscisscsscesssccssotsssesccosctsacsussveocsccousnvsscncsevensscvessnsseseotssnnsseseys Deploying Web Applications crt triente ere etie erede rea be teen Y To Deploy Using Admin Console irn iterare torn ere ota oaa ea do ER e Deploying Using Wadm aheede dedos end enmt iedosd E edo Rc tei iedibsnrts Deploying Using JSR 88 5 anb adanetacneitn n aant iu Ano tid eda Ad ada ai e ds Managing Web Applications V To Enable or Disable a Deployed Web Application Enabling Web Applications eet rrr arre Pr A V To Remove a Deployed Web Application esent Dynamic Reloading of Web Applications V To Set Dynamic Reloading of Web Application V To Load a New Servlet or Reload a Deployment Descriptor sss 140 Classloadetsu iu epar uev eC Qd eiae tae eio QU HE HO Ud PU OR UO HR iE 141 Debugging Web Applications sese tnnt enne Enabling Debugging susuris n nde ppm emisse V To Enable Debugging Through Admin Console WV To Enable Debugging by Editing server xml sess JPDA OptOS 5nd REPRE REOR OE DEBE SHOE OUS URN e ENS Using Developer Tools for Debugging ertet erede T Y To Debug using NetBeans 5 5 2 dnce asse i ee s rie istis Da rie idee pen eed 147 Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Contents Deb gging ISPS enera O aE de
36. example PrintWriter output response getWriter output println Hello World n For binary output write to the output stream directly by creating a ServletOutputStream object and then write to it using print for example ServletOutputStream output response getOutputStream output print binary data 52 Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Creating Servlets Creating a JSP Response Page Servlets can invoke JSP files in two ways the include method and the forward method The include method in the RequestDispatcher interface calls a JSP file and waits for it to return before continuing to process the interaction The include method can be called multiple times within a given servlet This example shows a JSP file using include RequestDispatcher dispatcher getServletContext getRequestDispatcher JSP URI dispatcher include request response processing continues The forward method in the RequestDispatcher interface handles the JSP interaction control The servlet is no longer involved with the current interactions output after invoking forward therefore only one call to the forward method can be made in a particular servlet Note You cannot use the forward method if you have already defined a PrintWriter or ServletOutputSt ream object This example shows a JSP page using forward RequestDispatcher dispatcher getServletContext
37. helper This element allows you to change the properties of the built in default cache helper class Subelement The following table describes the property subelements for the default helper element TABLEA 34 default helperSubelements Element Required Description property Element on Zero or more Specifies a property which has a name and a value page 160 Attributes none Property The following table describes the cacheKeyGeneratorAttrName properties for the default helper element Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Elements in the sun web xml File TABLE A 35 default helper Properties Property Name cacheKeyGeneratorAttrName Default Value Uses the built in default cache helper key generation which concatenates the servlet path with key field values if any Description The caching engine looks in the ServletContext for an attribute with a name equal to the value specified for this property to determine whether a customized CacheKeyGenerator implementation is used An application provide a customized key generator rather than using the default helper See CacheKeyGenerator Interface on page 60 cache mapping Element This element maps a URL pattern or a servlet name to its cacheability constraints Subelements The following table describes subelements for the cache mapping element TABLE A 36 cache mappingSubelement
38. is necessary All classes to be used must be in the WEB INF classes directory or in a jar file in the WEB INF lib directory ofthe web application The servlet name element appears between the dots in the servlets properties file The code translates to the servlet class IntArgs translate to init params This entry will translate to the following entry lt servlet gt lt servlet name gt BuyNowServlet servlet name lt servlet class gt BuyNowlA lt servlet class gt lt init param gt lt param value gt argl lt param name gt lt param value gt 45 lt pram value gt lt init param gt lt init param gt lt param name gt arg2 lt param name gt lt param value gt online lt param value gt lt init param gt lt init param gt lt param name gt arg3 lt param name gt lt param value gt quick shopping lt param value gt lt init param gt lt servlet gt The rules properties entries translate to servlet mapping elements This entry translates to the following entry servlet mapping lt servlet name gt BuyNowServlet servlet name lt url pattern gt buynow lt url pattern gt servlet mapping Some other entries in the servlet properties file map to the web xml file This includes the following information m Servlets startup This servlet should contain the load on startup element Servlets config reloadInterval This setting translates to the dynamicreloadinterval attribute of
39. message security for stand alone clients In most cases you need to restart or reconfigure the Web Server after performing these tasks especially to apply the change to applications already deployed on Web Server To Create a Message Security Provider You can add or edit or modify the message protection policy The provider type implementation class and provider specific configuration properties should be modified Login to the Admin Console Select the configuration you want to modify and click Edit Configuration Click the Java tab Click the Authentication tab and scroll down to the SOAP Authentication To modify an existing provider select the provider name and edit the values Click New to add a provider Add the new provider information In this page following information is available for modification Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Securing Web Services Example 3 1 Note Only Name and class Name are required Ifthese two fields are not specified no authentication is applied to request or response messages All other values are optional Name Identifier for this provider You can use this identifier name to specify the default provider when using wadm Class Name The Java implementation class of the provider Server side providers must implement the com sun enterprise security jauth ServerAuthModule interface The request policy defines the authentication
40. minimally necessary permissions in that block Note Do not add java security AllPermission to the server policy file for application code Doing so completely defeats the purpose of the Security Manager yet you still get the performance overhead associated with it As noted in the Java EE specification an application should provide documentation of the additional permissions it needs If an application requires extra permissions but does not document the set it needs contact the application author for details As a last resort you can iteratively determine the permission set an application needs by observing AccessControlException occurrences in the server log If this information is not sufficient you can add the Djava security debug all JVM option to the server instance For details see the Sun Java System Web Server 7 0 Administrators Guide You can use the Java SE standard policy tool or any text editor to edit the server policy file For more information see http java sun com docs books tutorial securityl 2 tour2 index html Chapter 8 Securing Web Applications 129 Related Information For detailed information about the permissions you can set in the server policy file see http java sun com j2se 1 4 2 docs guide security permissions html For the Javadoc for the Permission class is see http java sun com j2se 1 4 2 docs api java security Permission html Related Information The following table descri
41. more if cache helper ref is not used Contains an HTTP method that is eligible for caching key field Element on page 184 zero or more if cache helper ref is not used Specifies a component ofthe key used to look up and extract cache entries constraint field Element on page 185 zero or more if cache helper ref is not used Specifies a cacheability constraint for the given url pattern or servlet name Attributes none url pattern Element This element contains data that specifies a servlet URL pattern for which caching is enabled See the Java Servlet 2 4 specification Subelements none Attributes none cache helper ref Element This element contains data that specifies the name of the cache helper used by the parent cache mapping element Subelements none Attributes none Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Elements in the sun web xml File timeout Element Contains data that specifies the cache mapping specific maximum amount of time in seconds that an entry can remain in the cache after it is created or refreshed If not specified the default is the value of the timeout attribute of the cache element Subelements none Attributes The following table describes attributes for the timeout element TABLEA 37 timeout Attributes Attribute Default Value Description name none Specifies the timeout input par
42. more information about this element see parameter encoding Element on page 190 3 The character encoding specified in the default charset attribute of the parameter encoding element in the sun web xml file For more information about this element see parameter encoding Element on page 190 Servlet Response When processing a servlet response the server uses the following order of precedence first to last to determine the response character encoding 1 The ServletResponse setContentType method or the ServletResponse setLocale method 2 The default encoding which is ISO 8859 1 To specify the character encoding that should be set in the Content type header of the response if the response locale is set using the ServletResponse setLocale method use the locale charset map under the locale charset info element in the sun web xml file For more information about this element see Locale charset info Element on page 190 Migrating Legacy Servlets 62 Netscape Enterprise Server iPlanet Web Server versions 4 0 and 4 1 supported the Java Servlet 2 1 specification This specification did not include web applications A deployment scheme was developed to make servlet deployment simpler With the advent of Java web applications WAR files and their deployment descriptors maintaining a proprietary deployment system is no longer necessary iPlanet Web Server 6 0 supported both types of deployment schemes but
43. ns j2ee http java sun com xml ns j2ee web app 2 4 xsd version 2 4 gt lt Copyright 2006 Sun Microsystems Inc All rights reserved web app lt display name gt webapps caching lt display name gt lt servlet gt lt servlet name gt ServCache lt servlet name gt lt servlet class gt samples webapps caching ServCache lt servlet class gt lt load on startup gt 0 lt load on startup gt lt servlet gt servlet mapping lt servlet name gt ServCache lt servlet name gt lt url pattern gt ServCache lt url pattern gt servlet mapping session config lt session timeout gt 30 lt session timeout gt lt session config gt lt taglib gt lt taglib uri gt com sun web taglibs cache lt taglib uri gt lt taglib location gt WEB INF sun web cache tld lt taglib location gt lt taglib gt web app Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Sample Web Application XML Files Sample sun web xml File The following example shows a sample sun web xml file lt DOCTYPE sun web app PUBLIC Sun Microsystems Inc DTD Application Server 8 1 Servlet 2 4 EN http www sun com software appserver dtds sun web app 2 4 1 dtd gt Lc Copyright 2006 Sun Microsystems Inc All rights reserved sun web app lt session config gt lt session manager gt lt session config gt cache enabled true timeout in seconds 300 gt lt ca
44. objects to sessions to make them available across multiple user interactions The following table shows the HttpSession methods that provide support for binding objects to the session object TABLE6 3 HttpSession Methods HttpSession Method Description getAttribute Returns the object bound to a given name in the session or null ifthere is no such binding getAttributeNames Returns an array of names of all attributes bound to the session Chapter6 Session Managers 87 Using Sessions 88 TABLE6 3 HttpSession Methods Continued HttpSession Method Description setAttribute Binds the specified object into the session with the given name Any existing binding with the same name is overwritten For an object bound into the session to be distributed it must implement the serializable interface removeAttribute Unbinds an object in the session with the given name If there is no object bound to the given name this method does nothing Binding Notification with HttpSessionBindingListener Some objects require you to know when they are placed in or removed from a session To obtain this information implement the HttpSessionBindingListener interface in those objects When your application stores or removes data with the session the servlet engine checks whether the object being bound or unbound implements HttpSessionBindingListener If it does the Sun Java System Web Server 7 0 notifies the obj
45. only ifthe session data store parameter is set to the JdbcStore class timeOutColumn TimeOut The name ofthe column that holds the session timeout in minutes The SQL type is NUMERIC 9 Applicable only ifthe session data store parameter is set to the JdbcStore class sessionIdColumn SessionID The name ofthe column that holds the session ID The SQL type is VARCHAR 100 Applicable only ifthe session data store parameter is set to the JdbcStore class valueColumn Value The name ofthe column that holds the session object The SQL type is VARBINARY 4096 This column must be large enough to accommodate all of your session data Applicable only ifthe session data store parameter is set to the JdbcStore class Chapter6 Session Managers 95 Session Managers TABLE6 6 manager properties for IWS60 Continued Property Name Default Value Description lookupPool 4 The number of dedicated connections that perform lookup operations on the database For higher performance use a precompiled SQL statement for each of these connections Applicable only if the session data store parameter is set to the JdbcStore class insertPool The number of dedicated connections that perform insert operations on the database Each ofthese connections would have a precompiled SQL statement for higher performance Applicable only if the session data store parameter is set to
46. or by editing server xml Sun Java System Web Server debugging is based on the JPDA Java Platform Debugger Architecture software For more information see JPDA Options on page 146 v ToEnable Debugging Through Admin Console 1 Accessthe Admin Console 2 Click the Edit Java Settings tab in the home page 3 Click the JVM Settings tab 145 JPDA Options Select the Enable Debug option to enable debugging For more information about debug options see JPDA Options on page 146 Click Save To Enable Debugging by Editing server xml Set the following attributes of the j vm element in the server xml file Set debug true to turn on debugging Add any desired JPDA debugging options in the debugoptions attribute See PDA Options on page 146 To specify the port to use when attaching the JVM to a debugger Specify address port_number in the debugoptions attribute For details about the server xml file see the Sun Java System Web Server 7 0 Administrator s Configuration File Reference JPDA Options 146 The default JPDA options are as follows Xdebug Xrunjdwp transport dt_socket server y Suspend n If you change the value of suspend y the JVM starts in suspended mode and stays suspended until a debugger attaches to it Use this option if you want to start debugging as soon as the JVM starts To specify the port to use when attaching the JVM to a debugger specify address port_number You can also use
47. page 131 Create the deployment descriptor files For more information see Creating Web Deployment Descriptors on page 135 Optional Package the web application in a war file For example jar cvf module_name war Deploy the web application For more information see Deploying Web Applications on page 135 You can create a web application manually or you can use Java System Enterprise Studio For more information about developing web applications in Sun Java Enterprise Studio see http developers sun com prodtech javatools jscreator learning tutorials 2 helloweb html About Securing Web Applications You can write secure web applications for the Sun Java System Web Server with components that perform user authentication and access authorization You can build security into web applications using the following mechanisms User authentication by servlets User authentication for single sign on User authorization by servlets Requesting the client certificate Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Developing and Deploying Web Applications For detailed information about these mechanisms see Chapter 8 Securing Web Applications About Deploying Applications A web application is a collection of servlets JSP HTML documents and other web resources that might include image files compressed archives and other data A web application can be packaged into a Web ARchive file
48. per page named ns with a value from the ns parameter or default 20 CollElem Tag This tag creates a hidden inputbox or select box or multiple checkboxes depending on the attribute input If only one collection exists the tag will create a hidden inputbox by default Attributes The CollElem tag uses the following attributes Name Specifies the name of the form element created The default is c Items Optional A comma delimited string representing search collections available The tag retrieves all collections available on the server if the attribute is empty Chapter 5 Developing JavaServer Pages 75 JSP Search Tags 76 Type Optional The type of form element used for displaying collections Valid options are hidden select and checkbox The default value is hidden if one collection exists and checkbox if there are multiple collections Rows Optional Represents size if the type is select or the number of rows The default behavior is to satisfy the Cols attribute first That is the collections will be listed in columns as specified by the Cols attribute Cols Represents number of columns and is only required if type is checkbox If Cols and Rows are not specified the collections will be listed horizontally Defaults Specifies a comma delimited string containing 1s or 0s indicating the selection status of the search collections An item is selected if the setting is 1 and not selected if the
49. platform specific liabilities of CGI programs Servlets supported by the Sun Java System Web Server 7 0 are based on the Java Servlet 2 4 specification Servlets are created compiled and packed into a Java web application archive WAR file and then deployed to the Web Server and managed at runtime by the servlet engine Basic characteristics of servlets include the following Operate on input data that is encapsulated in a request object Respond to a query with data encapsulated in a response object 45 About Servlets 46 Provide user session information persistence between interactions Allow dynamic reloading while the server is running Can be addressed with URLs For examples buttons on an application s pages often point to servlets Can call other servlets and or JSP pages Servlet Data Flow When a user clicks a Submit button information entered in a display page is sent to a servlet The servlet processes the incoming data and responds to generate content Once the content is generated the servlet creates a response page usually by forwarding the content to a JSP The response is sent back to the client which sets up the next user interaction Information flows to and from the servlet according to the following high level process 1 The servlet processes the client request 2 The servlet generates content 3 The servlet creates a response and either sends back directly to the client or dispatches the t
50. policy requirements associated with request processing performed by the authentication provider Type the policies in message sender order For example a requirement that encryption occur after content means that the message receiver expects to decrypt the message before validating the signature Request Authentication Source Possible values are sender Message layer sender authentication such as username and password content Content authentication for example digital signature null Source authentication of the request is not required Clickthe Add Property button to add additional properties The provider shipped with the Web Server requires the server config property If other providers are used refer to their documentation for more information on properties and valid values server config The directory and file name of an XML file that contains the server configuration information This file is in the following location install dir samples java webapps webservices security etc wss server config 2 0 xml Click OK To set the response policy replace the word request in the following commands with response Create a message security provider msgsecurity provider bin wadm create soap auth provider port 8989 user admin password file tmp admin passwd config test class com sun xml wss provider ServerSecurityAuthModule request policy auth source content request policy auth recipient before content
51. processes Look at the PPID parent process ID column and identify which of the two processes is the parent process and which is the child process Note the PID process ID of the child process ID Send a SIGQUIT signal signal 3 to the child process kill QUIT child PID Run the stopserv script from another window to stop the Web Server stopserv Stopping the server writes an HPROF stack dump to the file you specified using the file HPROF option For general information about using a stack dump see Generating a Stack Trace for Debugging on page 147 Using the Optimizeit Profiler Information about Optimizeit is available at http www borland com optimizeit Once Optimizeit is installed its libraries are loaded into the server process To enable remote profiling with Optimizeit do one ofthe following Goto the Common Tasks page in the Admin Console click the Edit Java Settings tab click the Profiler link and edit the following fields before selecting OK Profiler Enable Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Using Profiling for Debugging Classpath Optimizeit dir Vib optit jar Native Lib Path Optimizeit dir lib JVM Option For each of these options type the option in the JVM Option field select Add then check its box in the JVM Options list DOPTITHOME Optimizeit dir m Xrunoii m Xbootclasspath a Optimizeit_dir lib oibcp jar or Enable
52. request cacheable param request incoming lt code gt HttpServletRequest lt code gt object returns lt code gt true lt code gt if the response could be cached or lt code gt false lt code gt if the results of this request must not be cached public boolean isCacheable HttpServletRequest request isRefreshNeeded is the response to given request to be refreshed param request incoming lt code gt HttpServletRequest lt code gt object returns lt code gt true lt code gt if the response needs to be refreshed or return lt code gt false lt code gt if the results of this request dont need to be refreshed A public boolean isRefreshNeeded HttpServletRequest request get timeout for the cached response param request incoming lt code gt HttpServletRequest lt code gt object returns the timeout in seconds for the cached response a return value of 1 means the response never expires and a value of 2 indicates helper cannot determine the timeout container assigns default timeout public int getTimeout HttpServletRequest request Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Caching Servlet Results Stop the helper from active use exception Exception if an error occurs A public void destroy throws Exception Caching Example The following example cache element in the sun web xml file cache max capacity 8192 timeout 60 gt cache he
53. rtt rette toti teo oet een hen rote ceo rsen Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Contents Invoking Servlets esien oaaae atlas R O E et ri e ec dete eeblg 54 Calling a Servlet Withia URL teretes rte rt ciet ik et gei eere oen 54 Calling a Servlet Programmatically trt ntt etnies tenitetie 55 Servlet Output siirus QM 55 caching Servlet Results uero ete t he ORAT Peter ie eed Features of Caching Default Cache Configuration CacheHelper Interface ceecssssssscscscsesescsssscscscscscssssssscsscsescssscssssssesesesesesescsesseseseseseseseseseeseseseaes 58 Caching Example reete eee ih ein nd ern ied e e si aaa 59 CacheKeyGenerator Interface eese eene eN s SETE as 60 Maximizing Servlet Performance n rdiet a sete etit ee rit d dd ee Sene cie 61 Servlet Internationalization Issues aet hee the tn eene he i len dg itoe 61 Servlet Request 1 ottenere e cr dct ce e er e te ert 61 Servlet Response ie cea ne ODIO ORO IO ORO UU RO GRO OR RE OUR NE Gr OP EHE 62 Migrating Legacy Servlets i acd ea etre tees d a eiie ee e eee d Sie Ger eed 62 JSP file Dy D qst M 63 Servlet by Extension of Servlet by Directory seen 63 Registering Servlete noted oeun o adiit detinet tun dtr efenidiind 63 Developing JavaServer Pages essent entente tenente 65 Introducing SP
54. servlet is based on a call to request getMethod which provides the HTTP transfer method Override the service method for generic servlets or the doGet or doPost methods for HTTP servlets to perform tasks needed to answer the request Very often these tasks collate the needed information in the request object or in a JDBC result set object and then passing the newly generated content to a JSP for formatting and delivery back to the client Most operations that involve forms use either a GET or a POST operation so for most servlets you override either doGet or doPost Implement both methods to provide for both input types or pass the request object to a central processing method as shown in the following example public void doGet HttpServletRequest request HttpServletResponse response throws ServletException IOException doPost request response All request by request traffic in an HTTP servlet is handled in the appropriate doOperation method including session management user authentication JSP pages and accessing Sun Java System Web Server 7 0 features Ifa servlet calls the RequestDispatcher method include or forward the request information is no longer sent as HTTP POST and GET In other words if a servlet overrides doPost it may not process other servlets if the calling servlet happens to receive its data through HTTP GET For this reason be sure to implement routines for all possible in
55. the shared memory transport dt_shmem on the Win32 platform For more information on list of JPDA debugging options see http java sun com products jpda doc conninv html Invocation Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Generating a StackTrace for Debugging Using Developer Tools for Debugging Sun Java Studio Enterprise 8 1 technology can be used for remote debugging if you want to manually attach the IDE to a remote Web Server started in debug mode v ToDebugusing NetBeans 5 5 Pressmouse button the Web project name in the IDE Choose Debug Project from the context menu Web Server will then start in debug mode and the IDE will pause executing the program at the breakpoint you have set in your application Debugging JSPs When you use Sun Java Studio Enterprise 8 1 to debug JSPs you can set breakpoints in either the JSP code or the generated servlet code You can switch between them and see the same breakpoints in both the JSP code and the servlet code To set up debugging in Sun Java Studio Enterprise 8 1 see Using Developer Tools for Debugging on page 147 Generating a StackTrace for Debugging For information about how to generate a Java stack trace for debugging see http developer java sun com developer technicalArticles Programming Stacktrace If the Xrs flag is set for reduced signal usage in the server xml file under jvm comment it out before generating the
56. when deploying a web application archive that has precompiled JSP without the corresponding jsp source files To do this set the reload interval property to 1in the jsp config element of the sun web xml file For more information see JSP Element on page 187 The jspc command line tool is located under install_dir bin The format of the j spc command is as follows jspc options file specifier The following table shows what file_specifier can contain in the jspc command Chapter 5 Developing JavaServer Pages 67 Compiling JSPs Using the Command Line Compiler 68 TABLE5 1 FileSpecifiersfor the jspc Command File Specifier Description files One or more JSP files to be compiled webapp dir A directory containing a web application All JSPs in the directory and its subdirectories are compiled You cannot specify a WAR JAR or ZIP file You must first extract such files to an open directory structure The following table shows the basic options for the j spc command TABLE 5 2 Basic jspc Options Option Description help Enables quiet mode same as v0 Only fatal error messages are displayed v Verbose mode d dir Specifies the output directory for the compiled JSPs Package directories are automatically generated based on the directories containing the uncompiled JSPs The default top level directory is the directory from which jspc is invoked l Specifies the name
57. 1 command To Load a New Servlet or Reload a Deployment Descriptor Create an empty file named reload at the root ofthe deployed module For example instance dir webapps vs id uri reload where vs idis the virtual server ID in which the web application is deployed and uri is the value ofthe uri attribute of the webapp element Type touch reloadto explicitly update the reload file s timestamp each time you make the above changes For JSPs changes are reloaded automatically at a frequency set in the reload interval property ofthe jsp config element in the sun web xml file To disable dynamic reloading of JSPs set the reLoad interval property to 1 Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Classloaders Classloaders Sun Java System Web Server 7 0 classloaders help you determine where and how you can position supporting JAR and resource files of your modules and applications Ina Java Virtual Machine JVM the classloaders dynamically load a specific Java class file needed for resolving a dependency For example when an instance of java util Enumeration needs to be created one ofthe classloaders loads the relevant class into the environment Classloaders in the Sun Java System Web Server 7 0 runtime follow the hierarchy shown in the following figure Chapter9 Deploying Web Applications 141 Classloaders 142 Bootstrap Classloader System Classloader Common Clas
58. Administrators Configuration File Reference JSP Element The JSP elements is j sp config jsp config Element on page 187 jsp config Element This element specifies JSP configuration information that enables web application to customize the compilation and execution of its JSP files Subelement The following table describes the name subelement for the j sp config element Appendix A Deployment Descriptor Files 187 Elements in the sun web xml File 188 TABLE A 43 jsp configSubelements Element Required Description name Element on page 176 zero or more Specifies a property Attributes none Properties The following table describes properties for the jsp config element TABLE A 44 jsp config Properties Property Name Default Value Description ieClassId clsid 8AD9C840 044E 11D1 B3E9 00805F499D93 The Java Plug in COM class ID for Internet Explorer Used by the lt j sp plugin gt tags javaCompilerPlugin internal JDK compiler javac This property is deprecated in this release By this we mean this is supported in 7 0 but will NOT be supported in future release If JSP Pages import classes from unnamed packages the default JDK compiler will throw a compile time error when JSP generated servlets are compiled To compile JSP generated servlets set the javaCompilerPlugin property to org apache jasper compiler SunJavaCompiler Note The jspc command li
59. Authentication is the process of confirming an identity Authorization means granting access to arestricted resource to an identity Access control mechanisms enforce these restrictions Authentication and authorization can be enforced by a number of security models and services Sun Java System Web Server 7 0 provides authentication and authorization support through the following mechanisms which are discussed in this section ACL based authentication and authorization Java EE Servlet based authentication and authorization Whether performed by the ACL subsystem or the Java EE Servlet authentication subsystem authentication and authorization are still the two fundamental operations that define secure web content ACL Based Authentication and Authorization ACL based access control is described at length in the Configuring Access Control in Sun Java System Web Server 7 0 Administrators Guide This section provides a brief overview of the key concepts Sun Java System Web Server 7 0 supports authentication and authorization through the use of locally stored ACLs which describe what access rights a user has for a resource For example an entry in an ACL can grant a user named John read permission to a particular folder named misc acl path export user 990628 1 docs misc authenticate user group database default method basic deny all user John allow read 110 Sun Java System Web Server 7 0 D
60. Developer s Guide to Java Web Applications Elements in the sun web xml File For an alphabetical list of elements in sun web xml see Alphabetical List ofsun web xml Elements on page 193 General Elements General elements are as follows sun web app Element on page 157 property Element on page 160 description Element on page 160 sun web app Element This element Sun Java System Web Server 7 0 specific configuration for a web application This element is the root element The sun web xml file contain only one sun web app Subelements The following table describes subelements for the sun web app element TABLEA 2 sun web app Subelements Element Required Description context root Element on page 159 Zero or more Contains the web context roots for the web application servlet Element on page 161 Zero or more Specifies a principal name for a servlet which is used for the run as role defined in web xml session config Element on page 163 Zero or one Specifies the session manager session cookie and other session related information resource env ref Element on page 169 zero or more Maps the absolute JNDI name to the resource env ref in the corresponding Java EE XML file resource ref Element on page 175 zero or more Maps the absolute JNDI name to the resource ref in the corresponding Java EE XML file service ref
61. P results to make subsequent calls to the same servlet or JSP page faster For more information about response caching as it pertains to servlets see Caching Servlet Results on page 56 Chapter 2 Web Applications Overview 27 Developing and Deploying Web Applications 28 JSP Cache Tags JSP cache tags enable you to cache JSP page fragments within the Java engine Each can be cached using different cache criteria For example if you have page fragments to view stock quotes and weather information you can cache the stock quote fragment for 15 minutes and the weather report fragment for 25 minutes For more information about JSP caching see JSP Cache Tags on page 70 Database Connection Pooling Database connection pooling enhances the performance of servlet or JSP database interactions For more information about the Java DataBase Connectivity JDBC software see Configuring JDBC Resources in Sun Java System Web Server 7 0 Administrator s Guide The simplest connection pool can be configured by using the given In this example the connection pool is assigned to use the ORACLE JDBC driver To Configure a Simple Connection Pool In this example procedure the connection pool uses the ORACLE JDBC driver Start wadm bin wadm user admin Please enter admin user password gt user admin password Sun Java System Web Server 7 0 B01 02 2006 14 22 wadm gt Verify the list of available configurations wa
62. S Jac bre ere pr o MO RERO RR NR EYE RHENUS d 65 Creating JSPs Designing for Ease of Maintenance Lec e eae rnnt lite rne avers d Deni duin 66 Designing for Portability s assets taceo ci uin uia d neci od ceti tuts i DRE 67 Ha ndling EXGeptlOBS tdeo ode idee ett ite etit ee te e eia ROS 67 Compiling JSPs Using the Command Line Compiler eene 67 Package Names Generated by the JSP Compiler sse 69 Other JSP Configuration Parameters Debugging SDSra amens e a dnce tnde itte JSP Tag Libraries and Standard Portable Tags seen 70 JSPGCACHE TAGS E M 70 REI MED 71 SEDI EL E E E T JSP Search Tags searchForm Tag Contents COU UE eimi TAG ucarana e aa AEE OR RUE NM UTR OILS RATS UN RAS CIO GATA INN IG 75 Collection Pag xenon dan ex dera ad tete da nei iit hee do ere ano decia dd 76 colIItem Tag D 77 CSNY BOX E cis caves E 77 submi tButton Tag sesioen a re HO RERO e DP ananassae 78 formAction Tag POFMSUDMIUSS LON LAG E E E A O O TT 79 FOLMACELOMMS GUL AS em e RR 79 e E E E O casesvsscvueadeueasess 80 resultIteration Tag sopesar an ite D EVA E DO a 80 LEem DB TE E E A A E O OE eres 81 WES UNAS Tea a A E E T E dun 81 resultNav Tag JSP Internationalization Issues siiis onc n oi RAE E R E TERRE EN 82 JSP Character Encoding acu ranae E ENA AN E ETA 82 Session Managers
63. Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications S S microsystems Sun Microsystems Inc 4150 Network Circle Santa Clara CA 95054 U S A Part No 819 2634 Copyright 2007 Sun Microsystems Inc 4150 Network Circle Santa Clara CA 95054 U S A All rights reserved This product or document is protected by copyright and distributed under licenses restricting its use copying distribution and decompilation No part of this product or document may be reproduced in any form by any means without prior written authorization of Sun and its licensors if any Third party software including font technology is copyrighted and licensed from Sun suppliers Parts ofthe product may be derived from Berkeley BSD systems licensed from the University of California UNIX is a registered trademark in the U S and other countries exclusively licensed through X Open Company Ltd Sun Sun Microsystems the Sun logo docs sun com AnswerBook AnswerBook2 and Solaris are trademarks or registered trademarks of Sun Microsystems Inc in the U S and other countries All SPARC trademarks are used under license and are trademarks or registered trademarks of SPARC International Inc in the U S and other countries Products bearing SPARC trademarks are based upon an architecture developed by Sun Microsystems Inc The OPEN LOOK and Sun Graphical User Interface was developed by Sun Microsystems Inc for its users and licensees Su
64. TP sessions to another server instance of the same cluster This feature covers most usage scenarios For more information see Configuring Session Replication in Sun Java System Web Server 7 0 Administrators Guide API Changes from Web Server 61 to Web Server 7 0 Sun Java System Web Server has the following core components Web container implements the JSP 2 0 Servlet 2 4 and JSTL 1 1 specification which are part of Java EE 1 4 Monitoring and configuring interfaces For more information about non Java APIs and programming technologies see the Sun Java System Web Server 7 0 Developers Guide and the Sun Java System Web Server 7 0 Update 1 NSAPI Developers Guide Chapter 1 Web Server Technologies Overview 23 24 gt CHAPTER 2 Web Applications Overview This chapter provides a basic overview of how web applications are supported in Sun Java System Web Server 7 0 This chapter includes the following sections Java Web Applications on page 25 Developing and Deploying Web Applications on page 25 Sample Applications in Web Server 7 0 on page 29 Java Web Applications Sun Java System Web Server 7 0 supports the Java Servlet 2 4 API specification and the JavaServer Pages JSP 2 0 specification which allows servlets and JSPs to be included in web applications A web application is a collection of servlets JavaServer Pages HTML documents and other web resources that include image files c
65. This tag displays the message query text not specified ifa query is not submitted The message is printed from the form action where the tag is placed search Tag This tag executes a search query and returns search results The search tag retrieves a query string and collections from either a form parent tag or the query and collection attributes The search results are saved in the page context with a page or session scope Attributes The search tag uses the following attributes formld Specifies the name of the form used for the search The default form is used if the attribute is left empty If this tag is used without a form this attribute must be set to provide an identifier for the resultIterate tag collection Optional A comma delimited string representing collections used for a search If form action exists this attribute is ignored and the values are retrieved by requesting the collection element query Optional Specifies the query text If not provided the text is retrieved from the query element scope Specifies an integer indicating the scope of the search results The value 1 which is the default indicates page scope 2 indicates session scope Usage slws search This search tag uses the default parameters and executes a search The search results are saved in pageContext with a page scope slws search Collection col1 col2 Query Java Web Service scope 2 This search tag executes
66. URL For example the part number of this book is 819 2634 18 gt CHAPTER 1 Web Server Technologies Overview This chapter provides a basic overview on various technologies that are supported in the Sun Java System Web Server 7 0 Technologies and Enhancements in Web Server 7 0 Sun Java System Web Server 7 0 is a major new release with significant enhancements in the administration infrastructure This release is the first 64 bit version of Web Server supported on both the Solaris SPARC and AMD64 platforms Web Server 7 0 provides Comprehensive command line interface support Consolidated configuration Enhanced security Web based Distributed Authoring and Versioning WDAV Access control lists ACL URL rewriting Clustering support This product also comes with a robust built in migration tool that helps migrate applications and configurations from Web Server 6 0 and 6 1 to Sun Java System Web Server 7 0 Sun Java System Web Server 7 0 introduces the following new features Management infrastructure Java Web Services Developer Pack 2 0 support Session replication support Extensive real time monitoring support Integrated reverse proxy plug in and FastCGI plug in support For more features and information see What s New in This Release in Sun Java Enterprise System 2005Q4 Release Notes Technologies and Enhancements in Web Server 7 0 20 Supported Standards Protocols and Technologies Servle
67. Web Applications gt CHAPTER 8 Securing Web Applications This chapter describes the basic goals and features of Sun Java System Web Server 7 0 security features related to the Java Servlet Container It also describes how to write secure Java web applications containing components that perform user authentication and access authorization tasks This chapter has the following sections Supported Security Features on page 107 Common Security Terminology on page 108 Security Features Specific to the Web Server on page 109 Container Security on page 112 User Authentication by Servlets on page 113 User Authentication for Single Sign On on page 115 User Authorization by Servlets on page 116 Fetching the Client Certificate on page 117 Using Web Services Message Security on page 118 Programmatic Login on page 126 Enabling the Java Security Manager on page 128 The server policy File on page 128 Related Information on page 130 Supported Security Features Sun Java System Web Server 7 0 provides highly secure interoperable and distributed component computing based on the Java EE security model The security goals for Sun Java System Web Server 7 0 include the following Full compliance with the Java Servlet 2 4 security model including role based authorization For more information see the Security chapter in the Java Servlet 2 4 specification at htt
68. a WAR file or exist in an open directory structure For more information see Chapter 9 Deploying Web Applications About Virtual Servers A virtual server is a virtual web server that uses a unique combination of IP address port number and host name to identify it You might have several virtual servers all of which use the same IP address and port number but are distinguished by their unique host names When you first install Sun Java System Web Server 7 0 a default virtual server is created You can also assign a default virtual server to each new HTTP listener you create For details see Sun Java System Web Server 7 0 Administrators Guide About Default Web Applications A web application that is deployed in a virtual server at a URL becomes the default web application for that virtual server To access the default web application for a virtual server type the URL for the virtual server but do not supply a context root For example http myvirtualserver 3184 If none of the web applications under a virtual server are deployed at the URI the virtual server serves HTML or JSP content from its document root which is usually instance dir docs To access this HTML or JSP content point your browser to the URL for the virtual server specify the target file rather than a context root For example http myvirtualserver 3184 hellothere jsp Servlet Result Caching The Sun Java System Web Server 7 0 can cache servlet or JS
69. ameter whose value is interpreted in seconds The field s type must be java lang Long or java lang Integer scope context attribute Optional Specifies the scope in which the input parameter can be present Allowed values are context attribute request header request parameter request cookie session id and session attribute refresh field Element This element specifies a field that gives the application component a programmatic way to refresh a cached entry Subelements none Attributes The following table describes attributes for the ref resh field element Appendix A Deployment Descriptor Files 183 Elements in the sun web xml File 184 TABLEA 38 refresh field Attributes Attribute Default Value Description name none Specifies the input parameter name If the parameter is present in the specified scope and its value is t rue the cache will be refreshed scope request parameter Optional Specifies the scope in which the input parameter can be present Allowed values are context attribute request header request parameter request cookie session id and session attribute http method Element This element contains data that specifies an HTTP method that is eligible for caching The default is GET Subelements none Attributes none key field Element Specifies a component of the key used to look up and extract cache entries The web container
70. and Standard Portable Tags on page 70 JSPs are compiled into servlets so servlet design considerations also apply to JSPs JSPs and servlets can perform the same tasks but each excels at one task at the expense of the other Servlets are strong in processing and adaptability However performing HTML output from servlet requires you to write several cumbersome println statements Conversely although JSPs excel at layout tasks because they can be created with HTML editors performing complex computational or processing tasks with them is awkward For information about servlets see Chapter 4 Developing Servlets Additional JSP design tips are described in the following sections Designing for Ease of Maintenance on page 66 Designing for Portability on page 67 Handling Exceptions on page 67 Designing for Ease of Maintenance Each JSP can call or include any other JSP For example you can create a generic corporate banner a standard navigation bar and a left side column table of contents where each element is in a separate JSP and is included for each page built The page can be constructed with a JSP functioning as a frameset dynamically determining the pages to load into each subframe A JSP can also be included when it is compiled into a servlet or when a request arrives Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Compiling JSPs Using the Command Line Compiler Des
71. aper thread sleeps before calling the reaper method again maxLocks 1 The number of cross process locks to use for synchronizing access to individual sessions across processes The default value is used if the value 0 is specified This parameter is ignored in single process mode 98 Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Session Managers Note MMap can only store objects that implement java io Serializable Chapter6 Session Managers 99 100 gt CHAPTER 7 Developing Lifecycle Listeners This chapter provides a basic overview and a description of various features of lifecycle listeners in Sun Java System Web Server 7 0 It includes the following sections Server Lifecycle Events on page 101 The LifecycleListener Interface on page 102 The LifecycleEvent Class on page 102 The Server Lifecycle Event Context on page 102 Deploying a Lifecycle Module on page 103 Considerations for Lifecycle Modules on page 104 Sample Lifecycle Configuration on page 105 Server Lifecycle Events Sun Java System Web Server 7 0 goes through different events in its lifecycle init This event includes reading configuration initializing built in subsystems naming security and logging services and creating the web container m startup loading and initializing deployed applications service The server is ready to service requests shut dow
72. ask to JSP or to another servlet The servlet remains in memory available to process another request Servlet Types The two main servlet types are generic and HTTP Generic servlets Extend javax servlet GenericServlet Contain no inherent HTTP support or any other transport protocol so that protocol is independent m HTTP servlets m Extend javax servlet HttpServlet Contain built in HTTP protocol support and are more useful in a Sun Java System Web Server 7 0 environment For both servlet types you must implement the initializer method init to allocate and initialize the servlet and the destructor method destroy to deallocate resources All servlets must implement a service method which is responsible for handling servlet requests For generic servlets override the service method to provide routines for handling requests HTTP servlets provide a service method that automatically routes the request to Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Creating Servlets another method in the servlet based on which HTTP transfer method is used For HTTP servlets override doPost to process POST requests doGet to process GET requests and so on Creating Servlets To create a servlet create a class that extends either GenericServlet or HttpServlet overriding the appropriate methods so that the servlet handles request This section discusses the following topics
73. ault host is Localhost port Specify the port number ofthe administration server The default non SSL port is 8800 and the default SSL port is 8989 no ssl Specify this option to usea plain text connection to communicate with the administration server The default connection is SSL Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Deploying Web Applications TABLE9 1 Command Parameters Continued Parameter Description rcfile Specify the name ofthe rcfile that has to be loaded while starting the wadm utility rcfile can contain environment commands like set and unset ora JACL script that needs to be run while starting wadm The default file is wadmrc no prompt If you specify this option wadm will prompt you for password while executing this command Use this option if you have defined all passwords in a password file and specified the file using the password file option When you execute the wadm command two things happen A web application with the given uri path and directory gets added to the server xml file The WAR file is extracted in the target directory The following shows a sample command wadm add webapp user admin password file admin pwd host serverhost port 8989 config configl vs configl vs 1 uri testapp abc sample war After you have deployed an application you can access it from a browser as follows http vs urlhost vs por
74. ber of seconds between checks for expired sessions Setting this value lower than the frequency at which session data changes is recommended For example this value should be as low as possible 1 second for a hit counter servlet on a frequently accessed web site or you could lose the last few hits each time you restart the server maxSessions 1 Specifies the maximum number of active sessions or 1 the default for no limit IWS60 Session Manager The IWS60 session manager ensures backward compatibility with any 6 0 session managers that you may have created IWS60 works in both single process and multi process mode It can be used for sharing session information across multiple processes possibly running on different machines Note The MaxProcs directive in the magnus conf file determines whether the server is running in single process or multi process mode If the value of MaxProcs is higher than 1 and no session manager is configured then by default the session manager used is the IWS60 with file based persistence The Maxprocs is deprecated in Web Server 7 0 For session persistence IWS60 can use a database or a distributed file system DFS path that is accessible from all servers in a server farm Each session is serialized to the database or distributed file system You can also create your own persistence mechanism If Sun Java System Web Server 7 0 is running in single process mode then by default no sess
75. bes where you can find more information about security and security configuration topics in the Sun Java System Web Server 7 0 documentation 130 TABLE8 11 More Information on Security related Issues Subject Location Configuring Java security and realm based authentication The chapter Securing Your Web Server in the Sun Java System Web Server 7 0 Administrators Guide Certificates and public key cryptography The chapter Using Certificates and Keys in the Sun Java System Web Server 7 0 Administrators Guide ACL based security The chapter Controlling Access to Your Server in the Sun Java System Web Server 7 0 Administrators Guide Configuring authentication services in the server xml files The chapter Controlling Access to Your Server in the Sun Java System Web Server 7 0 Administrators Guide and Sun Java System Web Server 7 0 Administrators Configuration File Reference Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications gt CHAPTER 9 Deploying Web Applications This chapter describes how web applications are assembled and deployed in Sun Java System Web Server 7 0 The chapter has the following sections m Web Application Structure on page 131 Deployment Tools on page 132 Creating Web Deployment Descriptors on page 135 Deploying Web Applications on page 135 Deploying Using JSR 88 on page 138 Managing Web Applications on page 138
76. bute name Description Type Default auth layer Layer at which the Entity This attribute is required security should be message layer enforced provider id Identifies the CDATA Ifa value is not specified then the provider config that default provider is used If no default should be used provider exists at the layer the authentication requirements defined in the message security binding are not enforced message security Element The syntax for the message security element is as follows lt ELEMENT message security message request protection response protection gt TABLE8 5 message security Element Element name Occurrences Description Type message 1 or more Describes the methods or operations to which the security requirements apply Table 8 6 request protection Oorl Describes the authentication requirements applicable to a request Table 8 7 response protection Oorl Describes the authentication requirements applicable to a response Table 8 8 message Element The syntax for the message element is as follows lt ELEMENT java method operation name gt Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Using Web Services Message Security TABLE8 6 messageelement Element name occurrences Description Type java method Oorl Java methods on which Table 8 9 the security shou
77. cation You can no longer copy a servlet in the class file into the document tree and have it run asa servlet or have all ofthe contents ofa directory run asa servlet The web application treats only class files as servlets Registering Servlets The legacy servlet system used a two step process of registering servlets servlet properties and mapping them to a URL rules properties In Sun Java System Web Server 7 0 the servlets must be moved into a web application These settings will be maintained in the web xml file of that web application A registered servlet has entries in both the servlet properties and rules properties files The following example uses a servlet file called BuyNow1A class which responds to buynow It is assumed that the web application is deployed at The servlet properties file containing EXAMPLE4 1 RegisteringServlets Example servlet BuyNowServlet classpathzD Netscape server4 docs servlet buy D Netscape server4 docs myclasses servlet BuyNowServlet code BuyNow1A servlet BuyNowServlet initArgs argl 45 arg2 online arg3 quick shopping The rules properties file has buynow BuyNowServlet These settings must be translated to a web xml setting The servlet properties setting translates into the servlet element Chapter4 Developing Servlets 63 Migrating Legacy Servlets 64 EXAMPLE4 1 Registering Servlets Example Continued The classpath is automated so no classpath setting
78. certs 0 if clientCert null Get the Distinguised Name for the user java security Principal userDN clientCert getSubjectDN The userDn is the fully qualified distinguished name for the user Chapter 8 Securing Web Applications 117 Using Web Services Message Security Using Web Services Message Security 118 In message security security information is inserted into messages that travel through the networking layers and reaches the message destinations Setting up wadm Configuring Message Security Provider Message Security Provider in Application Configuring the Web Server for Message Security This section describes the following topics Actions of Request and Response Policy Configurations To configure other security facilities Security Enhancements to server xml Security Enhancements to sun web xml Actions of Request and Response Policy Configurations The following table shows message protection policy configuration and the resulting message security operations performed by the WS Security SOAP message security providers for that configuration TABLE8 1 Message Protection Policy Configuration Message Protection Policy Resulting WS Security SOAP Message Protection Operation auth source sender The message contains the wase security header that contains a wsse UsernameToken with password auth source content The content of the SOAP message body is signed The messag
79. che mapping gt lt servlet name gt ServCache lt servlet name gt lt key field name inputtext scope request parameter gt lt constraint field name inputtext scope request parameter gt lt value gt one lt value gt lt value gt two lt value gt constraint field cache mapping cache sun web app Appendix A Deployment Descriptor Files 197 198 Index A about JSPs 65 66 servlets 45 47 sessions 83 84 web applications 25 accessing a session 85 86 Administration Console more information about 12 Administration Console using to use Optimizeit profiler 150 Administration interface using to enable or disable web applications 139 AllPermission 129 application permissions 128 130 default 129 application role mapping 109 ATTLIST tags 156 auth constraint 117 authentication 108 110 ACL based 110 111 byservlets 113 114 forsinglesign on 115 116 HTTP basic 114 Java EE Servlet based 111 112 secure web applications 112 SSL mutual 114 authorization 108 110 ACL based 110 111 byservlets 116 117 client certificate 117 constraints 117 Java EE Servlet based 111 112 authorization Continued secure web applications 112 B binding objects to sessions 87 88 Bootstrap Classloader 143 C cache class names 179 cache element 177 179 cache helper 179 180 cache helper ref 182 cache mapping 181 182 cachetags 70 74 cacheClassName property 179 CacheHelpe
80. cle interface methods public class LifecycleListenerImpl implements LifecycleListener receive a server lifecycle event param event associated event throws lt code gt ServerLifecycleException lt code gt for exception condition EA public void handleEvent LifecycleEvent event throws ServerLifecycleException LifecycleEventContex ctx event getLifecycleEventContext ctx log level INFO got event event getEventType event data event getData Properties props Chapter7 Developing Lifecycle Listeners 105 Sample Lifecycle Configuration if Lifecycleevent INIT EVENT event getEventType System out println Lifecyclelistener INIT EVENT props Properties event getData handle INIT EVENT return if LifecycleEvent STARTUP EVENT event getEventType System out println Lifecyclelistener START EVENT handle STARTUP EVENT return if LifecycleEvent READY_EVENT event getEventType System out println LifecycleListener READY EVENT handle READY EVENT return if LifecycleEvent SHUTDOWN EVENT event getEventType System out println Lifecyclelistener SHUTDOWN EVENT handle SHUTDOWN EVENT return if LifecycleEven TERMINATION EVENT event getEventType System out println LifecycleListener TERMINATION EVENT handle TERMINATION EVENT return H 106 Sun Java System Web Server 7 0 Developer s Guide to Java
81. copyright et licenci par des fournisseurs de Sun Des parties de ce produit pourront tre d riv es du syst me Berkeley BSD licenci s par l Universit de Californie UNIX est une marque d pos e aux Etats Unis et dans d autres pays et licenci e exclusivement par X Open Company Ltd Sun Sun Microsystems le logo Sun docs sun com AnswerBook AnswerBook2 et Solaris sont des marques de fabrique ou des marques d pos es de Sun Microsystems Inc aux Etats Unis et dans d autres pays Toutes les marques SPARC sont utilis es sous licence et sont des marques de fabrique ou des marques d pos es de SPARC International Inc aux Etats Unis et dans d autres pays Les produits portantles marques SPARC sont bas s sur une architecture d velopp e par Sun Microsystems Inc L interface d utilisation graphique OPEN LOOK et Sun a t d velopp e par Sun Microsystems Inc pour ses utilisateurs et licenci s Sun reconnait les efforts de pionniers de Xerox pour la recherche et le d veloppement du concept des interfaces d utilisation visuelle ou graphique pour l industrie de l informatique Sun d tient une licence non exclusive de Xerox sur l interface d utilisation graphique Xerox cette licence couvrant galement les licenci s de Sun qui mettent en place l interface d utilisation graphique OPEN LOOK et qui en outre se conforment aux licences crites de Sun CETTE PUBLICATION EST FOURNIE EN L ETAT ET AUCUNE GARANTIE EXPRESSE OU IMPLICITE N EST
82. d for maintaining user specific state including persistent objects such as handles to database result sets and authenticated user identities among many interactions For example a session can be used to track a validated user login followed by a series of directed activities for a particular user The session itself resides in the server For each request the client transmits the session ID ina cookie or if the browser does not allow cookies the server automatically writes the session ID into the URL The Sun Java System Web Server 7 0 supports the servlet standard session interface called HttpSession for all session activities This section includes the following topics Sessions and Cookies on page 84 Sessions and URL Rewriting on page 84 Sessions and Security on page 84 83 Introducing Sessions 84 Note As of Sun Java System Web Server 7 0 form Login sessions are no longer supported You can use single sign on sessions instead Sessions and Cookies A cookie is a small collection of information that can be transmitted to a calling browser which retrieves it on each subsequent call from the browser so that the server can recognize calls from the same client A cookie is returned with each call to the site that created it unless it expires Sessions are maintained automatically by a session cookie that is sent to the client when the session is first created The session cookie contains the session ID
83. d in this section Enabling and Disabling Using the Admin Console To enable or disable a deployed web application using the Admin Console perform the following steps To Remove a Deployed Web Application Access the Admin Console Selectthe server instance and click the edit Virtual Server tab Click the Web applications tab In the Web Applications table select the web application or applications you want to remove and click Remove Tip To remove a deployed web application through the command line interface use the remove webapp command For more information see the remove webapp 1 man page In the dialog box that appears click OK Dynamic Reloading of Web Applications To set dynamic reloading of web application you must do the following Chapter9 Deploying Web Applications 139 Dynamic Reloading of Web Applications v ToSetDynamicReloading of Web Application 1 140 Access the Admin Console Select the server instances and click the Edit Configuration tab Click the Java tab Click the Servlet Container tab In the Dynamic Reload Interval field type an integer that specifies the interval in seconds after which a deployed application will be checked for modifications and reloaded if necessary To enable dynamic reloading you must specify a value greater than 0 To disable dynamic reloading set the field to 1 Click Save Tip To configure through the CLI use the set servlet container prop
84. dm list configs Create the jdbc resource configuration For more information about all possible elements see Sun Java System Web Server 7 0 Administrator s Configuration File Reference wadm gt create jdbc resource config test datasource class oracle jdbc pool OracleDataSource jdbc MyPool Add properties to jdbc resource Properties are primarily used to configure the driver s vendor specific properties In the following example the values for the properties url user and password are added to jdbc resource wadm list jdbc resource userprops config test jndi name jdbc MyPool password mypassword user myuser url jdbcZ oracle thin Qhostname 1421MYSID Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Sample Applications in Web Server 7 0 5 Enable the connection validation wadm gt set jdbc resource prop config test jndi name jdbc MyPool connection validation table name test connection validation table CLI201 Command set jdbc resource prop ran successfully 6 Change the pool setting In this example the maximum number of connections is set to 100 wadm gt set jdbc resource prop config test jndi name jdbc MyPool max connections 100 CLI201 Command set jdbc resource prop ran successfully 7 Deploy the configuration wadm gt deploy config test CLI201 Command deploy config ran successfully You can install a JDBC driver with Java Archive JAR files in one ofthe following way
85. e xenc EncryptedKey contains the key used to encrypt the SOAP message body The key is encrypted in the public key ofthe recipient auth recipient before content OR auth recipient after content The content of the SOAP message body is encrypted and replaced with the resulting xend EncryptedData The message contains a wsse Security header that contains an xenc EncryptedKey The xenc EncryptedKey contains the key used to encrypt the SOAP message body The key is encrypted in the public key ofthe recipient No policy specified No security operations are performed by the modules Y ToConfigure Other Security Facilities The Web Server implements message security using message security providers integrated in its SOAP processing layer The message security providers depend on other security facilities of Web Server If using a username token configure a user database if necessary When using a username and password token an appropriate realm must be configured and an appropriate user database must be configured for the realm Manage certificates and private keys if necessary After configuring the Web Server facilities for use by message security providers as described in Managing Certificates in Sun Java System Web Server 7 0 Administrator s Guide Chapter8 Securing Web Applications 119 Using Web Services Message Security 120 Security Enhancements to server xml The server element in server x
86. e 166 session properties Element on page 167 cookie properties Element on page 168 Note The session manager interface is unstable An unstable interface might be experimental or transitional This interface therefore change change incompatibly be removed or be replaced by a more stable interface in the next release session configElement This element specifies session configuration information Subelements The following table describes subelements for the session config element Appendix A Deployment Descriptor Files 163 Elements in the sun web xml File 164 TABLEA 8 session configSubelements Element Required Description 3 session manager Element zero or one Specifies session manager configuration on page 164 information session properties zero or one Specifies session properties Element on page 167 cookie properties Element zero or one Specifies session cookie properties on page 168 Attributes none session manager Element Specifies session manager information Note As of Sun Java System Web Server 7 0 you cannot define a session manager either for a single sign on session or for a virtual server You must define session managers at the level of web applications Subelements The following table describes subelements for the session manager element TABLEA 9 session manager Subelements Element Required Description manager proper
87. e Java web applications A typical Java EE based web application consists of the following parts access to any or all of which can be restricted Servlets JavaServer Pages JSP components HTML documents Miscellaneous resources such as image files and compressed archives The Java EE servlet based access control infrastructure relies on the use of security realms When a user tries to access the main page of an application through a web browser the web container prompts for the user s credential information The container then passes the information for verification to the realm that is currently active in the security service A realm represents a set of known users along with optional group membership information The main implementation also encapsulates a mechanism for performing authentication against the data set Chapter8 Securing Web Applications 111 Container Security The main features of the Java EE Servlet based access control model are described below a Java EE Servlet based authentication uses the following configuration files The web application deployment descriptor files web xml and sun web xml install dir config server xml Authentication is performed by Java security realms that are configured through auth realm entries in the server xml file Authorization is performed by access control rules in the deployment descriptor file web xml in case any such rules have been set Web Applica
88. e contains a wsse Security header that contains the message body signature represented as a ds Signature auth source sender The content of the SOAP message body is encrypted auth recipient before content OR and replaced with the resulting xend EncryptedData auth recipient after content The message contains a wsse Security header that contains a wsse UsernameToken with password and an xenc EncryptedKey The xenc EncryptedKey contains the key used to encrypt the SOAP message body The key is encrypted in the public key of the recipient Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Using Web Services Message Security TABLE8 1 Message Protection Policy Configuration Continued auth source content auth recipient before content The content of the SOAP message body is encrypted and replaced with the resulting xend EncryptedData The xenc EncryptedData is signed The message contains a wsse Security header that contains an xenc EncryptedKey and a ds Signature The xenc EncryptedKey contains the key used to encrypt the SOAP message body The key is encrypted in the public key ofthe recipient auth source content auth recipient after content The content of the SOAP message body is signed then encrypted and then replaced with the resulting xend EncryptedData The message contains a wsse Security header that contains an xenc EncryptedKey and a ds Signature Th
89. e following syntax in the search field search term site docs sun com For example to search for Web Server type the following Web Server site docs sun com To include other Sun web sites in your search for example java sun com www sun com and developers sun com use sun com in place of docs sun com in the search field 16 Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Preface Third Party Web Site References Third party URLs are referenced in this document and provide additional related information Note Sun is not responsible for the availability ofthird party web sites mentioned in this document Sun does not endorse and is not responsible or liable for any content advertising products or other materials that are available on or through such sites or resources Sun will not be responsible or liable for any actual or alleged damage or loss caused or alleged to be caused by or in connection with use ofor reliance on any such content goods or services that are available on or through such sites or resources Sun Welcomes Your Comments Sun is interested in improving its documentation and welcomes your comments and suggestions To share your comments go to http docs sun comand click Send Comments In theonline form provide the full document title and part number The part number is a 7 digit or 9 digit number that can be found on the book s title page or in the document s
90. e helper ref Element on page 182 timeout Element on page 183 refresh field Element on page 183 http method Element on page 184 key field Element on page 184 constraint field Element on page 185 value Element on page 186 cache Element This element configures caching for web application components Subelements The following table describes subelements for the cache element Appendix A Deployment Descriptor Files 177 Elements in the sun web xml File 178 TABLEA 28 cacheSubelements Element Required Description cache helper Element on Zero or more Specifies a custom class that implements the page 179 CacheHelper interface default helper on page 180 Zero or one Allows you to change the properties ofthe default built in cache helper class property Element on Zero or more Specifies a cache property which has a name and a page 160 value cache mapping Element on zero or more Maps a URL pattern or a servlet name to its page 181 cacheability constraints Attributes The following table describes attributes for the cache element TABLEA 29 cache Attributes Attribute Default Value Description max entries 4096 Optional Specifies the maximum number of entries the cache can contain Must be a positive integer timeout in seconds 30 Optional Specifies the maximum amount of time in seconds that an entry can remain in the cache after it is created
91. e starting point for defining your own session managers and session objects IWSSessionManager extends IWSHttpSessionManager The class file for IWSHttpSessionManager is in the JAR file webserv rt jar in the directory install dir Vib The IWS60 implements all of the methods in IWSHttpSessionManager that need to be implemented so you can use IWSSessionManager as an example of how to extend IWSHttpSessionManager When compiling your subclass of IWSSessionManager or IWSHttpSessionManager be sure that the JAR file webserv rt jarisin your compiler s classpath The JdbcStore javaand FileStore java source files and the source file for the parent class SessionDataStore java are provided so you can modify the session persistence mechanism of IWS60 These files are also located in the install dir 1ib directory Note The session timeout parameter specified in web xml will not be effective when IWS60 is used MMap Session Manager UNIX Only MMap is a persistent memory map mmap file based session manager that works in both single process and multi process mode Note The MaxProcs directive in the magnus conf file determines whether the server is running in single process or multi process mode The Maxprocs is deprecated in Web Server 7 0 Enabling MMap You can enable MMap to change its default parameters You can also enable MMap for a particular context if the server is running in single process mode To do so edit the sun web xml fi
92. eb Applications Sample Applications in Web Server 7 0 TABLE2 1 Sample Directories Continued Directory Contents Security Examples demonstrating how to secure Java EE web applications through standard authentication mechanisms and access controls Security examples are included in the following directories m basic auth Demonstrates how to develop configure and exercise basic authentication m client cert Demonstrates how to develop configure and exercise client certificate authentication form auth Demonstrates how to develop configure and exercise form based authentication jdbcrealm Demonstrates how to develop configure and exercise JDBC realm authentication Servlet and JSP example Servlet 2 4 and JSP 2 0 examples combined into a single web application WS I 1 1 Web Services interoperability 1 1 samples websecurity Web Services security samples Building the Samples An ANT based build system is used to build the individual sample application The build xml file has target to compile the sources to clean and to build the war file It also has targets to deploy and undeploy the application using the corresponding CLI commands provided by the Web Server Register application resources in the deployment target Documentation for the Samples Documentation is installed along with the samples during the installation The index html in the document root of t
93. eb cache LruCache A bounded cache with an LRU least recently used cache replacement policy com sun appserv web cache BaseCache An unbounded cache suitable if the maximum number of entries is known com sun appserv web cache MultiLruCache A cache suitable for a large number of entries 24096 Uses the MultiLRUSegmentSize property com sun appserv web cache BoundedMultiLruCache A cache suitable for limiting the cache size by memory rather than number of entries Uses the MaxSize property cache helper Element This element specifies a class that implements the CacheHelper interface For details see CacheHelper Interface on page 58 Subelement The following table describes the property subelements for the cache helper element Appendix A Deployment Descriptor Files 179 Elements in the sun web xml File 180 TABLEA 32 cache helperSubelement Element Required Description property Element on Zero or more Specifies a property which has a name and a value page 160 Attributes The following table describes attributes for the cache helper element TABLEA 33 cache helper Attributes Attribute Default Value Description name default Specifies a unique name for the helper class which is referenced in the cache mapping element class name none Specifies the fully qualified class name ofthe cache helper which must implement the com sun appserv web CacheHelper interface default
94. ect under consideration through the HttpSessionBindingListener interface that it is being bound into or unbound from the session Invalidating a Session Direct the session to invalidate itself automatically after being inactive for a defined time period Alternatively invalidate the session manually with the HttpSession method invalidate Invalidating a Session Manually To invalidate a session manually call the following method session invalidate All objects bound to the session are removed Setting a Session Timeout Session timeout is set using the session timeout element in the web xml deployment descriptor file For more information see the Java Servlet 2 4 specification Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Session Managers Session Managers Sun Java System Web Server 7 0 provides the following session management options which are described in this section memory the default session manager file aprovided manager that store sessions on the file system m IWS60 a provided session manager that allows backward compatibility with any custom session managers you may have created using Sun Java System Web Server 7 0 m MMAP UNIX Only a provided persistent memory map mmap file based session manager that works in both single process and multi process mode memory Option The memory is the default memory based session manager Enabling memory You can specif
95. ection The same wsdl port value must not appear in more than one port info element within the same service ref Ifa service endpoint interface is using container managed port selection its value must not appear in more than one port info element within the same service ref Subelements The following table describes subelements for the port info element TABLEA 21 port infoSubelements Element Required Description service endpoint interface Zero or one Specifies the web service reference Element on page 172 name relative to java comp env wsdl port Element on pagel72 zero or one Specifies the WSDL port Appendix A Deployment Descriptor Files 171 Elements in the sun web xml File 172 TABLEA 21 port infoSubelements Continued stub property Element on zero or one Specifies JAX RPC property values page 173 that are set on thejavax xml rpc Stub object before it is returned to the web service client call property Element on zero or one Specifies JAX RPC property values page 173 that are set on thejavax xml rpc Stub object before it is returned to the web service client message security binding zero or one Specifies a custom authentication Element on page 121 provider binding service endpoint interface Element This element specifies the web service reference name relative to java comp env Subelements none Attributes none wsdl port Element Spec
96. ehalf of applications Web Server can protect any web service application without requiring changes to the implementation of the application The Web Server achieves this effect by providing facilities to bind SOAP layer message security providers and message protection policies to container and to applications deployed in container Assigning Message Security Roles In the Web Server the system administrator and application deployer roles are expected to take primary responsibility for configuring message security In some situations the application developer also contribute although in the typical case either ofthe roles might secure an existing application without changing its implementation and therefore without involving the developer The responsibilities ofthe various roles are defined in the following sections System Administrator Tasks The system administrator is responsible for the following tasks Configuring message security providers on the Web Server Managing user databases Managing the keystore and truststore files Deploying the samples program f romwsdl soap12 which demonstrates the message layer web services security A system administrator uses the Admin Console to manage server security settings Web Server stores certificates and private keys in an NSS database the administrator can manage them using certutil Foran overview of message security tasks see Configuring the Web Server for Message Security on pa
97. eloaded by the server without the need for a restart For more information see Dynamic Reloading of Web Applications on page 139 JSP The JSP Classloader loads the compiled JSP classes of JSPs An instance of this classloader is created for each JSP file Any changes made to a JSP are automatically detected and reloaded by the server unless dynamic reloading of JSPs has been disabled by setting the reload interval property to 1 in the jsp config element of the sun web xml file For more information see jsp config Element on page 187 Chapter9 Deploying Web Applications 143 144 gt CHAPTER 10 Debugging Web Applications This chapter provides guidelines for debugging web applications in Sun Java System Web Server 7 0 The chapter includes the following sections Enabling Debugging on page 145 JPDA Options on page 146 Using Developer Tools for Debugging on page 147 Debugging JSPs on page 147 Generating a Stack Trace for Debugging on page 147 Using Logging for Debugging on page 148 Using Profiling for Debugging on page 148 Debugging applications requires you to edit the server xml file as described in this chapter For more general information see Sun Java System Web Server 7 0 Administrators Configuration File Reference Enabling Debugging When you enable debugging you enable both local and remote debugging You can enable debugging through Admin Console
98. en declarative security alone is insufficient to meet the application s security model The Java EE 1 4 specification defines programmatic security with respect to servlets as consisting of two methods of the servlet Ht tpServletRequest interface Sun Java System Web Server 7 0 supports these interfaces as defined in the specification Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications User Authentication by Servlets In addition to the programmatic security defined in the Java EE specifications Sun Java System Web Server 7 0 also supports programmatic login For more information see Programmatic Login on page 126 Declarative Security Declarative security means that the security mechanism for an application is declared and handled externally to the application Deployment descriptors describe the Java EE application s security structure including security roles access control and authentication requirements Sun Java System Web Server 7 0 supports the DTDs specified by the Java EE 1 4 specification and has additional security elements included in its own deployment descriptors Declarative security is the application deployers responsibility User Authentication by Servlets Web Server supports the web based login mechanisms required by the Java EE 1 4 specification HTTP Basic Authentication on page 114 SSL Mutual Authentication on page 114 Form Based Login on page 114 The login con
99. enticate to each application individually When the user logs out of one web application for example by invalidating or timing out the corresponding session if form based login is used the user s sessions in all web applications are invalidated Any subsequent attempt to access a protected resource in any application requires the users authorization The single sign on feature uses HTTP cookies to transmit a token that associates each request with the saved user identity so it can only be used in client environments that support cookies To configure single sign on set the following properties in the single sign on element of the server xml file enabled If false single sign on is disabled for this virtual server and users must authenticate separately to every application on the virtual server The default is false m idle timeout Specifies the time after which a users single sign on record becomes eligible for purging if no client activity is received Because single sign on applies across several applications on the same virtual server access to any of the applications keeps the single Chapter8 Securing Web Applications 115 User Authorization by Servlets sign on record active The default value is 5 minutes 300 seconds Higher values provide longer single sign on persistence for the users at the expense of more memory use on the server To configure single sign on through CLI see the enable single signon 1 and d
100. erties The following table describes properties for the manager properties element Appendix A Deployment Descriptor Files 165 Elements in the sun web xml File 166 TABLEA 12 manager properties Properties Property Name Default Value Description reapIntervalSeconds 60 Specifies the number of seconds between checks for expired sessions Set this value lower than the frequency at which session data changes For example this value should beaslow as possible 1 second for a hit counter servlet on a frequently accessed web site or you could lose the last few hits each time you restart the server maxSessions 1 Specifies the maximum number of active sessions or 1 the default for no limit sessionFilename none state is not preserved across restarts Specifies the absolute or relative path name ofthe file in which the session state is preserved between application restarts if preserving the state is possible A relative path name is relative to the temporary directory for this web application Applicable only if the persistence type attribute of the session manager Element on page 164 element is memory store properties Element Specifies session persistence storage properties Subelement The following table describes the property subelement for the store properties element TABLEA 13 store properties Subelement Element Required Description property Eleme
101. es deployed on the Web Server are secured by binding SOAP layer message security providers and message protection policies to the container in which the applications are deployed or to web service endpoints served by the applications When the Web Server is installed SOAP layer message security providers are configured in the server side container of the Web Server The container or individual applications in the container can bind to them or to individual applications in the container During installation the providers are configured with a simple message protection policy that if bound to a container or to an application would cause the source of the content in all request and response messages to be authenticated by an XML digital signature Use the Admin Console and CLI to perform the following tasks To bind the existing providers for use by the server side containers of the Web Server To modify the message protection policies enforced by the providers To create new provider configurations with alternative message protection policies By default message layer security is disabled on the Web Server For more information about how to configure message layer security for the Web Server see Configuring the Web Server for Message Security on page 118 For more information about how to use Web Services security to protect all Web Services applications deployed on the Web Server see Enabling Providers for Message Security on page 42
102. esh lt reload gt timeout 10m gt 72 Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications JSP CacheTags oe String page request getParameter page if page equals frontPage get headlines from database else mypfx cache mypfx cache timeout 1h gt h2 Local News h2 o get the headline news and cache them oe V mypfx cache flushTag This tag forces the cache to be flushed If a key is specified only the entry with that key is flushed If no key is specified the entire cache is flushed Attributes The following table describes attributes for the f Lush tag The left column lists the attribute name the middle column indicates the default value and the right column describes what the attribute does TABLE5 4 flush Attributes Attribute Default Description key servletPath suffix Optional The name used by the container to access the cached entry The cache key is added to the servlet path to generate a key to access the cached entry If no key is specified a number is generated according to the position of the tag in the page Scope application Specifies the scope ofthe cache Valid values are request session and application Examples To flush the entry with key foobar mypfx flush key foobar gt To flush the entire cache Chapter5 Developing JavaServer Pages 73 JSP Search Tags lt
103. et nent 27 Serylet Result Caching cecus ie tete tnde iret rude A E 27 PSP Cache PASS sc ona iieri qu vers eiuied feret ios epus tipest cesi el aset rase ver ese aepo orden 28 Database Connection Pooling J 2 dea teda cet e ed ed on aee us 28 V To Configure a Simple Connection Pool seen 28 Sample Applications in Web Servet 7 0 nasirin n ede ce it tpe er te eerte dog 29 Sample Directories nta aceite ten e ot ORENSE THE QR RENE e ERG 29 B ilding the Sain ples ats sg etia eet Breite ete d aciei De Ee ie leas iet dies 31 Documentation for the Samples suistichean entente ennt 31 Contents 3 WebServices Overview riscio ienr ceti ead rani da decia Hd ib OD e a ati e deat 33 Introducing Web Services 2 1 a attic ite tede eiii dede ce is chair d o eerie 33 Technologies Supported in Web Server 7 0 seen 34 Java Web Services Developer Pack 2 0 Technologies sse 34 Message Security JSR 196 Creating Web Services Web Services Tools WV To Create Web Services from a Java Source w cececscsssssssesesssesssscessssscsesescsesesecececsescsescseseeceeecsees 35 W To Create Web Services from Java Classes c ccccsssssssssescscsssssscscscscscssecscssesescscscececsesesseseseseeeesees 36 V To Create Web Services from a WSDL file sees 36 Securing WebServices use d a eet ticee eia re ite e d d sete Ce Ted e Nene Rl ea eene 36 Understanding Message Security in the Web Server
104. eveloper s Guide to Java Web Applications Security Features Specific to the Web Server The core ACLs in Sun Java System Web Server 7 0 support three types of authentication basic certificate and digest Basic authentication relies On lists of user names and passwords passed as cleartext a Certificates bind a name to a public key Digest authentication uses encryption techniques to encrypt the user s credentials The ACL based access control model includes the following features ACL based authentication uses the following configuration files w install dir config acl files install dir config server xml Authentication is performed by auth db modules that are configured in the server xml file Authorization is performed by access control rules set in the install dir config act files if ACLs are configured In addition the Sun Java System Web Server 7 0 SSL engine supports external crypto hardware to offload SSL processing and to provide optional tamper resistant key storage For more information about ACL based access control and the use of external crypto hardware see the Sun Java System Web Server 7 0 Administrators Guide Java EE Servlet Based Authentication and Authorization In addition to providing ACL based authentication Sun Java System Web Server 7 0 also implements the security model defined in the Java EE 1 4 specification to provide several features that help you develop and deploy secur
105. eyGenerator gt lt default helper gt Caching engine looks up the specified attribute in the servlet context the result of the lookup must be an implementation of the CacheKeyGenerator interface public interface CacheKeyGenerator getCacheKey generate the key to be used to cache the response param context the web application context param request incoming lt code gt HttpServletRequest lt code gt returns key string used to access the cache entry if the return value is null a default key is used Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Servlet Internationalization Issues public String getCacheKey ServletContext context HttpServletRequest request Maximizing Servlet Performance Consider the following guidelines for improving servlet performance Increase the Java heap size to help garbage collection The Java heap size can be adjusted by adjusting the values specified to the Xms and Xmx jvm options in server xml For example j vm options Xms128m Xmx256m jvm options sets the minimum Java heap size to 128 MB and 256 MB For more information see Sun Java System Web Server 7 0 Administrators Guide Set the stack space if applications use deep recursion or in any cases where very complex JSP pages are used You can set the stack space using set thread pool prop wadm command For example wadm set thread pool prop other args s
106. f Java SE 5 It programmatically processes the annotations and generates the JAX WS portable artifacts from an annotated Java source file wsgen The wsgen tool reads a service endpoint implementation class and generates all of the portable artifacts for a JAX WS web service wsimport The wsimport tool reads a WSDL and generates all the required artifacts for web service development deployment and invocation Note After using the tools the web xml sun jaxws xml the implementation class and the portable JAX WS artifacts must be bundled into a WAR that can be deployed onto a container The following procedures describes how to use these methods v ToCreate Web Services from a Java Source 1 Use apt to generate Java artifacts such as the WSDL file andschema documents Chapter3 Web Services Overview 35 Securing Web Services Package the web xml sun jaxws xml service endpoint interface and implementation class value types and generated classes if any into a WAR file Deploy the WAR file to Web Server To Create Web Services from Java Classes Use wsgen to generate portable artifacts Package the web xml sun jaxws xml service endpoint interface and implementation class value types and generated classes if any into a WAR file Deploy the WAR file to Web Server To Create Web Services from a WSDL file Use wsimport to generate portable artifacts Implement the service endpoint Package
107. fecycle Continued Data type and Configurable element attribute Units Range of values Remarks lifecycle module class path String Optional Points to the user specified classpath for the listener class lifecycle module description Element Optional Describes the lifecycle module property name String Optional User specified parameter name Part ofthe property element property value String Optional User specified parameter value Part ofthe property element property description String Optional User specified description Part of the property element Considerations for Lifecycle Modules When using keep the following points in mind oflifecycle module 104 The server lifecycle listener classes are called synchronously from the main server thread Therefore take extra precautions must be taken to ensure that the listener classes don t block the server Thelistener classes may create threads if appropriate The threads must be stopped during the shutdown and termination phases The resources allocated during initialization or startup events should be cleared The listener classes are loaded in the context of server s root class loader which loads server wide resources as well Therefore all the support classes needed by these server lifecycle event listener must be available at this class loader or its parent the system class loader As a consequence you must ensure that t
108. fic load and any new requests must wait for a free instance in order to proceed However with distributed load balanced applications the load automatically shifts to a less busy process Chapter 4 Developing Servlets 51 Creating Servlets For example the following servlet is completely single threaded import java io import javax servlet import javax servlet http public class myServlet extends HttpServlet implements SingleThreadModel servlet methods Note If a servlet is specifically written as a single thread the servlet engine creates a pool of servlet instances to be used for incoming requests Ifa request arrives when all instances are busy the request is queued until an instance becomes available Delivering Client Results The final user interaction activity is to provide a response page to the client The response page can be delivered by creating a servlet response page or JSP response page Creating a Servlet Response Page on page 52 Creating a JSP Response Page on page 53 Creating a Servlet Response Page Generate the output page within a servlet by writing to the output stream The recommended generation method depends on the output type Always specify the output MIME type using setContentType before any output commences as follows response setContentType text html For textual output such as plain HTML create a PrintWriter object and then write to it using println for
109. fig element in the web xml deployment descriptor file describes the authentication method used the application s realm name displayed by the HTTP basic authentication and the form login mechanisms attributes The togin config element syntax is as follows lt ELEMENT login config auth method realm name form login config Note The auth method subelement of login config is optional However but if it is not included the server defaults to HTTP Basic Authentication which is not very secure For more information about web xml elements see the Java Servlet 2 4 specification at http java sun com products servlet download html For more information on sun web xml elements see Chapter 9 Deploying Web Applications Chapter8 Securing Web Applications 113 User Authentication by Servlets 114 HTTP Basic Authentication HTTP basic authentication RFC 2617 is supported by Sun Java System Web Server 7 0 Because passwords are sent with base64 encoding this authentication type is not very secure Use SSL or another equivalent transport encryption to protect the password during transmission SSL Mutual Authentication SSL 3 0 and the means to perform mutual client server certificate based authentication is a Java EE 1 4 specification requirement This security mechanism provides user authentication using HTTPS HTTP over SSL For more information see Creating a Configuration in Sun Java System Web Server 7 0 Adm
110. g Authentication Realms in Sun Java System Web Server 7 0 Administrators Guide Authorization Authorization permits a user to perform desired operations after being authenticated For example a human resources application might authorize managers to view personal employee information for all employees but allow employees to view only their own personal information Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Security Features Specific to the Web Server Realms A realm also called a security policy domain or a security domain in the Java EE specification is a scope over which a common security policy is defined and enforced by the security administrator of the security service Supported realms in Sun Java System Web Server 7 0 are file ldap certificate solaris custom and native Java EE Application Role Mapping In the Java EE Servlet security model a client may be defined in terms ofa security role For example a company might use its employee database to generate both a company wide phone book application and payroll information obviously While all employees might have access to phone numbers and email addresses only some employees would have access to the salary information Employees with the right to view or change salaries might be defined as having a special security role A role is different from a user group in that a role defines a function in an application while a group is a se
111. g number of records returned and the range currently displayed Attributes The resultStat tag uses the following attributes formld Specifies the name of the form associated The default form is used if the attribute is left empty If this tag is used without a form this attribute must be set as a reference to the search tag m type Specifies the type of statistics data Valid inputs are start end range for example 1 20 and total resultNav Tag This tag creates a navigation bar Chapter 5 Developing JavaServer Pages 81 JSP Internationalization Issues Attributes The resultNav tag uses the following attributes formId Specifies the name of the form associated with the navigation bar The default form is used if the attribute is left empty If this tag is used without a form this attribute must be set as a reference to the search tag m type Specifies the type of navigation bar Valid values are full previous and next A full navigation bar appears as follows previous 12345 6 7 8 9 10 next where 5 is currently selected The number of page number links is determined by the of fset attribute and the number of pages available a caption Only necessary if the type is previous or next and the default text is not needed caption can be any HTML file offset Specifies the number of page links around the selected page For example if of fset 2 the navigation bar would appear as follows previous 3 4 5 6 7
112. ge 118 Application Deployer Tasks The application deployer is responsible for the following tasks Specifying at application assembly any required application specific message protection policies if such policies have not already been specified by upstream roles the developer or assembler Modifying Sun deployment descriptors to specify application specific message protection policies information message security binding elements to a web service endpoint Chapter3 Web Services Overview 37 Securing Web Services 38 The application developer can setup message security but is not responsible for doing so The system administrator can set the message security so that all Web Services are secured The application deployer can set the message security when the provider or protection policy bound to the application must be different from that bound to the container Application Developer Tasks The application developer or assembler is responsible for the following tasks Determining whether an application specific message protection policy is required by the application If the policy is required the developer or assembler works with the application deployer and ensures that the required policy is specified during application assembly Security Tokens and Security Mechanisms The WS Security specification provides an extensible mechanism for using security tokens to authenticate and encrypt SOAP Web Services messages Use the
113. ge 175 service ref Element on page 170 res ref name Element on page 175 default resource principal Element on page 176 name Element on page 176 password Element on page 176 m jndi name Element on page 177 resource env ref Element This element maps the res ref name Element on page 175 in the corresponding Java EE web xml file resource env ref entry to the absolute jndi name of a resource Subelements The following table describes subelements for the resource env ref element Appendix A Deployment Descriptor Files 169 Elements in the sun web xml File 170 TABLEA 19 resource env ref Subelements Element Required Description resource env ref name only one Element on page 170 Specifies the res ref name in the corresponding Java EE web xml file resource env ref entry jndi name Element on only one page 177 Specifies the absolute jndi name ofa resource Attributes none resource env ref name Element Contains data that specifies the res ref name Element on page 175 in the corresponding Java EE web xml file resource env ref entry Subelements none Attributes none service ref Element This element specifies the runtime settings for a web service reference Runtime information is only needed in the following cases To define the port used to resolve a container managed port To define the default Stub Call property sett
114. getRequestDispatcher JSP URI dispatcher forward request response You identify which JSP noun to call by specifying a Universal Resource Identifier URI The path is a String describing a path within the ServletContext scope You can also use the getRequestDispatcher method in the request object that takes a String argument indicating a complete path Note Identify The getRequestDispatcher method is similar to the RequestDispatcher in the ServletContext The servlet container uses the information in the request object to transform the given relative path to a complete current servlet path for example RequestDispatcher dispatcher req getRequestDispatcher foo bar Chapter 4 Developing Servlets 53 Invoking Servlets Note In the previous example getRequestDispatcher does not start with In Web Server 6 1 this syntax resulted in a URI such as webapp foo bar In Sun Java System Web Server 7 0 the URI appears as webapp current servlet path foo bar For more information about JSP pages see Chapter 5 Developing JavaServer Pages Invoking Servlets 54 You can invoke a servlet by directly addressing it from a Web page with a URL or by calling it programmatically from an already running servlet Calling a Servlet With a URL on page 54 Calling a Servlet Programmatically on page 55 Calling a Servlet With a URL You can call servlets by using URLs embedded as links in HTML
115. gt Note Do not use the Xrs flag Here is an example of options you can use Xrunhprof file log txt thread y depth 3 The file option is important because it determines where the stack dump is written in step 6 The syntax of HPROF options is as follows Xrunhprof help option value option2 value2 Using help lists options that can be passed to HPROF The output is as follows Hprof usage Xrunhprof help lt option gt lt value gt Option Name and Value Description Default heap dump sites all heap profiling allcpu samples old CPU Chapter 10 Debugging Web Applications 149 Using Profiling for Debugging 150 10 11 12 usage offformat a b ascii or binary output afile lt file gt write data to file java hprof txt for ascii net lt host gt lt port gt send data over a socket write to filedepth lt size gt stack trace depth 4cutoff lt value gt output cutoff point 0 0001lineno y n line number in traces ythread y n thread in traces ndoe y n dump on exit y Change the PRODUCT BIN assignment in the install_dir instance_dir bin startserv file from PRODUCT _BIN webservd wdog to PRODUCT BIN webservd Start the server by running the startserv script As the server runs in the foreground the command prompt returns only after the server has been stopped Find the process ID of the server process in another window or terminal ps ef grep webservd This command lists two webservd
116. harset info TABLE A 47 locale charset info Attributes Attribute Value Default Value default locale none locale charset map Element This element maps a locale to a specific character encoding For encodings you can use see http java sun com j2se 1 4 2 docs guide intl encoding doc html Attributes The following table describes attributes for the Locale charset map element TABLEA 48 locale charset map Attributes Attribute Default Value Description locale none Specifies the locale name agent none Ignored in Sun Java System Web Server 7 0 charset none Specifies the character set for that locale The following table provides a Locale charset map example listing the locale and the corresponding charset Appendix A Deployment Descriptor Files 191 Elements in the sun web xml File 192 TABLE A 49 locale charset map Example Locale Charset ja EUC JP zh UTF 8 message destination Element This element specifies the name ofa logical message destination defined within an application The message destination name matches the corresponding message destination name in the corresponding Java EE deployment descriptor file Subelements The following table describes subelements for the message destination element TABLEA 50 message destinationSubelements Elements Required Description message destination name only one Specifies the name of a logical Elemen
117. he FastCGI plug in shipped with the Web Server 7 0 using PHP i18n A basic Java EE web application that demonstrates how to dynamically change the display language based on user preference Javamail A servlet that uses the Javamail API to send an email message JDBC Java DataBase Connectivity examples are included in the following directories m blob A servlet that accesses BLOBs through the JDBC API simple A basic servlet that accesses an RDBMS through the JDBC API m transactions A servlet that uses the transaction API with JDBC to control a local transaction JDBC rowset Example showing how to use JSR 114 JDBC rowset JNDI JSF 1 1 Java Naming and Directory Interface examples are in the following directories m custom Demonstrates how to use the custom resource m external Demonstrates how to use the external resource m readenv Demonstrates the environment entries specified in the web xml file url A servlet that uses the URL resource facility to access a resource Example showing how to use Java Server Faces components to quickly build web application user interfaces JSTL Basic examples that demonstrate usage of the JSP Standard Tag Library NSAPI plugins RMI IIOP NSAPI examples Basic example that demonstrates using a servlet to access a stateless EJB using RMI IIOP running in Sun Java System Web Server 7 0 30 Sun Java System Web Server 7 0 Developer s Guide to Java W
118. he Java security manager policy files are appropriately set up Otherwise a lifecycle listener class trying to perform a System exec may geta security access violation Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Sample Lifecycle Configuration Sample Lifecycle Configuration The following example shows a portion of the server xml that defines a lifecycle listener lifecycle module class name com sun ias server LifecyclelistenerImpl class name lt is failure fatal gt false lt is failure fatal gt lt description gt Sample lifecycle module lt description gt lt property gt lt name gt foo lt name gt lt value gt fooval lt value gt lt property gt lt lifecycle module gt The following example shows a sample LifecycleListener implementation PROPERITARY CONFIDENTIAL Use of this product is subject to license terms Copyright 2006 2007 by SunMicrosystems Inc 4150 Network Circle Santa Clara California 95054 U S A All rights reserved package com sun ias server import java util Properties import java util logging Level import com sun appserv server LifecycleEventContext import com sun appserv server ServerLifecycleException import com sun appserv server LifecycleEvent import com sun appserv server LifecycleListener LifecycleListenerImpl is a dummy implementation for the LifecycleListener interface This implementation stubs out various lifecy
119. he default Web Server instance contains links to the samples documentation In addition you can access the documentation HTML files directly in the samples directory Chapter 2 Web Applications Overview 31 32 gt CHAPTER 3 Web Services Overview This chapter focuses on web services tasks that are performed by developers For administrator tasks including configuration and management information see Appendix C Web Services in Sun Java System Web Server 7 0 Administrators Guide in Sun Java System Web Server 7 0 Administrator s Guide Introducing Web Services Web Services uses a Web Services Description Language WSDL file to describe the service and registry service to register and look up the services The Simple Object Access Protocol SOAP binding is the standard interoperable binding for accessing Web Services Several registry protocols available but UDDI Universal Description Discovery and Integration is probably the most recognizable based on Java Web Services Developer Pack Sun Java System Web Server 7 0 because it supports integrated Java Web Services runtime and tools and therefore supports portable Web Services implementations making it interoperable with NET clients and services using the WS I Basic Profile For more information on Web Services see http java sun com webservices docs 2 0 tutorial doc index html WS Security is an OASIS proposal for adding message layer security to SOAP messages It
120. he helper default helper property and cache mapping subelements The following table shows how optional suffix characters of subelements determine the requirement rules or number of allowed occurrences for the subelements TABLEA 1 Requirement Rules and Subelement Suffixes Subelement Suffix Requirement Rule element Can contain zero or more of this subelement element Can contain zero or one of this subelement element Must contain one or more of this subelement element no suffix Must contain only one of this subelement If an element cannot contain other elements EMPTY or PCDATA appears instead of a list of element names in parentheses Data Some elements contain character data instead of subelements These elements have definitions of the following format lt ELEMENT element name PCDATA gt For example lt ELEMENT description PCDATA gt In the sun web xml file white space is treated as part of the data in a data element Therefore no extra white space should appear before or after the data delimited by a data element For example Appendix A Deployment Descriptor Files 155 Elements in the sun web xml File lt description gt class name of session manager lt description gt Attributes Elements that have ATTLIST tags contain attributes name value pairs For example lt ATTLIST cachemax capacity CDATA 4096 timeout CDATA 30 enabled s5boolean false gt
121. his interface is the means by which these events are represented This class informs you of the kind of event that happened through the getEventType method and the data associated with the event through the getData method The Server Lifecycle Event Context 102 The LifecycleEventContext interface provides an access to the server runtime environment including the JNDI naming context and logging service The following methods are defined in this interface m public String getCmdLineArgs Returns the server command line arguments m public javax naming Context getNamingContext Returns the naming context m public String getInstallRoot Returns the installation root m public String getInstanceName Returns the server instance name m public void log java util logging Level level String message Logs the message to the server log with verbosity level m public void log java util logging Level level String message Throwable throwable Logs the message and the stack trace for throwable with verbosity level The following two methods are also used by this interface to keep backward compatibility with the 6 1 version of Web Server Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Deploying a Lifecycle Module m public void log String message Throwable throwable Logs the message and the stack trace for throwable with verbosity level m public javax naming Context getInitialContex
122. i name 177 JSP about 65 66 caching 70 74 classloader 143 command line compiler 67 70 creating 66 67 debugging 147 ease of maintenance 66 handling exceptions 67 package names 69 parameters 70 portability of 67 standard portable tags 70 tag libraries 70 using 65 82 jsp config 67 187 189 JSP tags 70 cache 70 74 library location 70 search 74 82 jspc command 67 basic options 68 example of 69 file specifiers 67 format of 67 jspc command line tool 67 K key field 184 L library location JSP tags 70 list of sun web xml elements 193 195 locale charset info 190 191 locale charset map 191 192 logging 148 login mechanisms form based 114 HTTP basic authentication 114 SSL mutual authentication 114 201 Index M manager properties 165 166 memory 89 90 enabling 89 90 manager properties 89 90 MMap 97 99 MMapSessionManager manager properties 98 99 nameelement 176 NetBeans using for debugging 147 0 Optimizeit profiler 150 151 overriding destroy 48 initialize 48 methods 47 48 service Get Post 49 P package names for JSPs 69 parameter encoding 190 password element 176 performance improving for servlets 61 permissions changing for an application 129 130 default 129 setting in server policy file 130 persistent session manager 97 99 portability 67 portable tags JSP 70 Post overriding 49 principal name 162 163 profiling 148 151 HPROF prof
123. ication restarts if preserving the state is possible A relative path name is relative to the temporary directory for this web application file Session Manager The file is another file system based session manager provided with Sun Java System Web Server 7 0 For session persistence file can usea file to which each session is serialized You can also create your own persistence mechanism Enabling the file Session Manager You can specify file explicitly to change its default parameters To do so edit the sun web xml file for the web application as in the following example Note that persistence type must be set to file lt sun web app gt lt session config gt session manager persistence type file gt lt manager properties gt property name reapIntervalSeconds value 20 gt lt manager properties gt lt store properties gt lt property name directory value sessions gt lt store properties gt lt session manager gt lt session config gt 90 Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Session Managers sun web app For more information about the sun web xml file see Chapter 9 Deploying Web Applications Manager Properties for f ile The following table describes manager properties properties for the file session manager TABLE6 5 manager properties for file Property Name Default Value Description reapIntervalSeconds 60 Specifies the num
124. ifies the WSDL port Subelements The following table describes subelements for the wsdl port element TABLEA 22 wsdl portSubelements Element Required Description namespaceURI Element on only one Specifies the namespace URI page 172 Localpart Element on page 173 only one Specifies the local part ofa QNAME namespaceURI Element This element specifies the namespace URI Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Elements in the sun web xml File Subelements none Attributes none localpart Element Specifies the local part ofa QNAME Subelements none Attributes none stub property Element This element specifies JAX RPC property values that are set on a javax xml rpc Stub object before it is returned to the web service client The property names can be any properties supported by the JAX RPC Stub implementation Subelements The following table describes subelements for the stub property element TABLEA 23 stub property subelements Element Required Description name Element on page 176 only one Specifies the name of the entity value Element on only one Specifies the value of the entity page 186 call property Element This element specifies JAX RPC property values that can be set on a javax xml rpc call object before it is returned to the web service client The property names can be any propertie
125. igning for Portability JSPs are completely portable between different applications and different servers This portability can be disadvantage because they have no particular application data knowledge Generic JSPs can be used for portable page elements such as navigation bars or corporate headers and footers which are meant to be included in other JSPs You can create a library of reusable generic page elements to use throughout an application or even among several applications For example the minimal generic JSP is a static HTML page with no JSP specific tag A slightly less minimal JSP contains some Java code that operates on generic data such as printing the date and time or that makes a change to the page s structure based on a standard value set in the request object Handling Exceptions If an uncaught exception occurs in a JSP file Sun Java System Web Server 7 0 generates an exception usually a 404 or 500 error To avoid this problem set the errorPage attribute ofthe page directive for example lt page other page directive attr list errorPage oops jsp gt Compiling JSPs Using the Command Line Compiler Sun Java System Web Server 7 0 provides the following ways of compiling JSP 2 0 compliant source files into servlets JSP are automatically compiled at runtime The jspc command line tool described in this section enables you to precompile JSPs at the command line You must disable dynamic reloading of JSP
126. iler 148 150 Optimizeit profiler 150 151 programmatic login 126 127 property element 160 R realms 109 reaper method 93 98 refresh field 183 184 reloading web applications 139 140 res ref name 175 resource env ref 169 170 resource env ref name 170 resource ref 175 response page 52 54 role mappings 116 role name 117 162 S search internationalizing 74 search tags 74 82 collection 76 77 CollElem 75 76 collitem 77 formAction 78 79 formActionMsg 79 80 formSubmission 79 Item 81 librarylocation 74 queryBox 77 78 resultiteration 80 81 resultNav 81 82 resultStat 81 Search 80 searchForm 74 75 submitButton 78 Secure Socket Layer SSL 114 117 security 107 130 andsessions 50 84 Java EE security model 107 108 terminology 108 109 web applications 107 130 Web Server features 109 112 Web Server goals 107 108 Web Server security model 109 112 Security Manager Java 128 security role mapping 116 161 server policy file 128 130 202 Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Index server xml editing for debugging 145 service overriding 49 servlet element 161 162 servlet name 162 servlets 45 64 about 45 47 accessing parameters 50 authorization by 116 117 authorization constraints 117 caching 57 59 60 caching results 56 61 calling programmatically 55 calling with a URL 54 55 creating 47 54 creating the class declaration 47 da
127. iles Sun JavaES5 WebServer7 For stand alone installations the default location for instance on Solaris Linux and HP UX lt install_dir gt For stand alone installations the default location for instance on Windows System Drive Program Files sun WebServer7 14 Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Preface Typographic Conventions The following table describes the typographic changes that are used in this book TABLEP 3 Typographic Conventions Typeface Meaning Example AaBbCc123 The names of commands files and directories and Edit your Login file onscreen computer output P P Use ls a to list all files machine names you have mail AaBbCc123 What you type contrasted with onscreen computer output machine names su Password AaBbCc123 A placeholder to be replaced with a real name or value The command to remove a file is rm filename AaBbCc123 Book titles new terms and terms to be emphasized note Read Chapter 6 in the User s Guide that hasized it bold onli dc LEM ME A cache is a copy that is stored locally Do not save the file Symbol Conventions The following table explains symbols that might be used in this book TABLEP 4 Symbol Conventions Symbol Description Example Meaning Contains optional argumentsand qs l The 1 option is not required command options Contains a set of choices fora d y n The d option requ
128. ings for Stub objects To define the URL ofa final WSDL document to be used instead of the one associated with service ref in the standard Java EE deployment descriptor TABLEA 20 service ref Subelements Element Required Description service ref name Element on only one Specifies the web service reference page 171 name relative to java comp env port info Element on page 171 zero or more Specifies information for a port within a web service reference Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Elements in the sun web xml File TABLEA 20 service ref Subelements Continued call property Element on Zero or more Specifies JAX RPC property values page 173 that can be set on a javax xml rpc Call object before it is returned to the web service client service impl class Element zero or more Specifies the name of the generated on page 174 service implementation class service qname Element on zero or one Specifies the WSDL service element page 174 that is being referenced service ref name Element This element specifies the web service reference name relative to java comp env Subelements none Attributes none port info Element Either a service endpoint interface or awsdl port or both ports must be specified If both ports are specified wsdl port specifies the port that the container chooses for container managed port sel
129. inistrators Guide Form Based Login The login screen s look and feel cannot be controlled with the HTTP browsers built in mechanisms Java EE can to package a standard HTML or servlet JSP based form for logging in The login form is associated with a web protection domain and is used to authenticate previously unauthenticated users Because passwords are sent unless protected by the underlying transport this authentication type is not very secure Use of SSL or another equivalent transport encryption to protect the password during transmission For the authentication to proceed appropriately the login form action must always be j security check For more information see Chapter 4 Developing Servlets The following HTML sample shows how to program the form in an HTML page form method POST action j security check lt input type text name j username lt input type password namez j password lt form gt You can specify the parameter encoding for the form For details see parameter encoding Element on page 190 Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications User Authentication for Single Sign On User Authentication for Single Sign On Single sign on across applications on the Sun Java System Web Server 7 0 is supported by the Sun Java System Web Server 7 0 servlets and JSPs This feature allows multiple applications that require the same user sign on information to sha
130. ion persistence mode is defined and therefore sessions are not persistent Chapter6 Session Managers 91 Session Managers If Sun Java System Web Server 7 0 is running in multi process mode sessions are persistent by default Ifa persistence mode is not defined IWS60 uses a DFS Multi process mode is supported only on UNIX platforms All multi process mode features of IWS60 are ignored on Windows Enabling IwS60 You can enable IWS60 to change its default parameters You can also enable IWS60 for a particular context if the server is running in single process mode To do so edit the sun web xml file for the web application as in the following example The persistence type must be set to s1ws60 lt sun web app gt lt session config gt session manager persistence type slws60 gt lt manager properties gt lt property name classname value com iplanet server http session IWSSessionManager gt other manager related properties lt manager properties gt lt session manager gt S enssdonseonties sjsun webapp gt In the case of persistent sessions lt sun web app gt lt session config gt lt session manager persistence type slws60 gt lt manager properties gt property name classname value com iplanet server http session IWSSessionManager other manager related properties lt manager properties gt lt store properties gt property name classname value com iplanet serve
131. ires that you use either the y required command option argument or the n argument Indicates a variable reference com sun javaRoot References the value of the com sun javaRoot variable Joins simultaneous multiple Control A Press the Control key while you press the A keystrokes key Joins consecutive multiple Ctrl A N Press the Control key release it and then press keystrokes the subsequent keys Preface TABLEP 4 Symbol Conventions Continued Symbol Description Example Meaning gt Indicates menu item selection ina File New Templates From the File menu choose New From the graphical user interface New submenu choose Templates Accessing Sun Resources Online The http docs sun com docs sun com web site enables you to access Sun technical documentation online You can browse the docs sun com archive or search for a specific book title or subject Books are available as online files in PDF and HTML formats Both formats are readable by assistive technologies for users with disabilities To access the following Sun resources go to http www sun com Training Research Searching Sun Product Documentation Downloads of Sun products Services and solutions Support including patches and updates Communities for example Sun Developer Network Besides searching Sun product documentation from the docs sun com web site you can use a search engine by typing th
132. is executed and the cache is refreshed By default this value is interpreted in seconds To specify a different unit of time adda suffix to the timeout value as follows s for seconds m for minutes h for hours and d for days For example 2h specifies two hours nocache false Optional If set to true the body content is executed and served as if no cache tag is active This offers a way to programmatically decide whether the cached response should be sent or whether the body must be executed even if the response is not cached refresh false Optional If set to true the body content is executed and the response is cached again This setting enables you to lets you programmatically refresh the cache immediately regardless of the timeout setting Scope application Specifies the scope ofthe cache Valid values are request session and application Example The following example represents a cached JSP page lt taglib prefix mypfx uri com sun web taglibs cache gt lt String cacheKey null if session null cacheKey String session getAttribute loginId check for nocache boolean noCache false String nc request getParameter nocache if nc null noCache true force reload boolean reload false String refresh request getParameter refresh if refresh null reload true gt mypfx cache key lt cacheKey gt nocache lt noCache gt refr
133. isable single signon l man pages The following example shows a configuration with all default values single sign on lt enabled gt 1 lt enabled gt lt idle timeout gt 300 lt idle timeout gt lt single sign on gt User Authorization by Servlets Servlets can be configured to permit access to users with the appropriate authorization level Defining Roles on page 116 Defining Servlet Authorization Constraints on page 117 Defining Roles Security roles define an application function made up ofa number of users groups or both users and groups The relationship between users and groups is determined by the specific realm implementation being used You can define roles in the Java EE deployment descriptor file web xml and the corresponding role mappings in the Sun Java System Web Server 7 0 deployment descriptor file sun web xml For more information about sun web xml see Chapter 9 Deploying Web Applications Each security role mapping element in the sun web xml file maps a role name permitted by the web application to principals and groups For example a sun web xml file for a deployed web application might contain the following lt sun web app gt lt security role mapping gt lt role name gt manager lt role name gt lt principal name gt jgarcia lt principal name gt lt principal name gt mwebster lt principal name gt lt group name gt team leads lt group name gt lt secu
134. l web app gt lt resource ref gt lt description gt JDBC Connection Pool lt description gt Chapter 1 Web Server Technologies Overview 21 Technologies and Enhancements in Web Server 7 0 22 res ref name jdbc myJdbc res ref name lt res type gt javax sql DataSource lt res type gt lt res auth gt Container lt res auth gt lt resource ref gt lt web app gt WEB INF sun web xml lt sun web app gt lt resource ref gt lt res ref name gt jdbc myJdbc lt res ref name gt lt jndi name gt jdbc MyPool lt jndi name gt lt resource ref gt sun web app In the above example jdbc myJdbc is the name by which the pool is referenced in the web application and j dbc MyPool is the JNDI name ofthe jdbc resources configuration The following is an example for using the pool in a web application Context initContext new InitialContext Context webContext Context initContext lookup java comp env DataSource ds DataSource webContext lookup jdbc myJdbc Connection dbCon ds getConnection Tools Support Web Server 7 0 provides support for the following tools Sun Java Studio Enterprise 8 1 Java Studio Enterprise 8 1 enables you create Java Web and EJB projects from existing code NetBeans IDE 5 5 NetBeans IDE 5 5 is an integrated development environment to create deploy the Java EE based web applications For more information see Using NetBeans IDE 5 5 on
135. ld be enforced operation name Oorl WSDL name ofan PCDATA operation of the web service Attributes of request protection Element The syntax for the request protection element is as follows lt ELEMENT request protection EMPTY gt lt ATTLIST request protection auth source sender content IMPLIED auth recipient before content after content IMPLIED TABLE8 7 request protection Element Attribute name Description Value Default auth source sender or content Defines a requirement for message layer sender authentication for example username and password or content authentication for example digital signature Implied auth recipient before content or after content Defines a requirement for message layer authentication of the receiver of a message to its sender for example by XML encryption A before content attribute value indicates that recipient authentication occurs before any content authentication Implied response protection Element The syntax for the respo Chapter 8 Securing Web Appl nse protection element is as follows ications 123 Using Web Services Message Security 124 lt lt ELEMENT response protection EMPTY gt lt ATTLIST response protection auth source sender content ZIMPLIED auth recipient before content after content IMPLIED TABLE 8 8 Attributes of the response protection Element Attribute name Description Value Default
136. ld be familiar with the system documentation at http docs sun com coll 1286 2 Preface Sun Java Documentation Set The Sun Java documentation set describes how to install and administer the Web Server The URL for Sun Java documentation is http docs sun com coll 1308 3 For an introduction to Sun Java refer to the books in the order in which they are listed in the following table TABLEP 1 Books in the Sun Java Documentation Set Documentation Title Contents Sun Java System Web Server 7 0 Documentation Center Web Server documentation topics organized by tasks and subject Sun Java System Web Server 7 0 Release Notes Late breaking information about the software and documentation Supported platforms and patch requirements for installing Web Server Sun Java System Web Server 7 0 Installation and Migration Guide Performing installation and migration tasks Installing Web Server and its various components m Migrating data from Sun ONE Web Server 6 0 or 6 1 to Sun Java System Web Server 7 0 Sun Java System Web Server 7 0 Administrators Guide Performing the following administration tasks Using the Administration and command line interfaces m Configuring server preferences m Using server instances Monitoring and logging server activity Using certificates and public key cryptography to secure the server m Configuring access control to secure the server Using JavaPlatfor
137. le for the web application as in the following example Note that persistence type must be set to mmap lt sun web app gt lt session config gt session manager persistence type mmap gt Chapter6 Session Managers 97 Session Managers lt session manager gt lt session config gt sun web app For more information about the sun web xml file see Chapter 9 Deploying Web Applications Manager Properties for MMap The following table describes manager properties properties for the MMap session manager TABLE6 7 manager properties Properties for MMap Property Name Default Value Description maxSessions 1000 The maximum number of sessions maintained by the session manager at any given time The session manager refuses to create any more new sessions if maxSessions number of sessions are already present at that time maxValuesPerSession 10 The maximum number of values or objects a session can hold maxValueSize 4096 The maximum size of each value or object that can be stored in the session timeOut 1800 The amount of time in seconds after a session is last accessed by the client before the session manager destroys it Those sessions that haven t been accessed for at least timeOut seconds are destroyed by the reaper method The session timeout parameter specified in web xml will not be effective when IWS60 is used reapInterval 600 The amount of time in seconds that the SessionRe
138. least recently used list is maintained to delete cache entries if the maximum cache size is exceeded Key generation concatenates the servlet path with key field values if any are specified Chapter 4 Developing Servlets 57 Caching Servlet Results 58 CacheHelper Interface The CacheHelper interface includes the following information package com sun appserv web cache import java util Map import javax servlet ServletContext import javax servlet http HttpServletRequest CacheHelper interface is an user extensible interface to customize a the key generation b whether to cache the response ul public interface CacheHelper name of request attributes public static final String ATTR CACHE MAPPED SERVLET NAME com sun appserv web cachedServletName public static final String ATTR CACHE MAPPED URL PATTERN com sun appserv web cachedURLPattern public static final int TIMEOUT VALUE NOT SET 2 initialize the helper param context the web application context this helper belongs to exception Exception if a startup error occurs public void init ServletContext context Map props throws Exception getCacheKey generate the key to be used to cache this request param request incoming lt code gt HttpServletRequest lt code gt object returns the generated key for this requested cacheable resource public String getCacheKey HttpServletRequest request isCacheable is the response to given
139. lishes the identity of the parties who can read the message Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Securing Web Services Message Protection Policies Message protection policies are defined for request message processing and response message processing These policies are expressed in terms of requirements for source or recipient authentication A source authentication policy requires that the identity ofthe entity that sent a message or that defined the content of a message be established in the message so that the message receiver can authenticate it A recipient authentication policy represents a requirement that the message be sent such that the identity of the entities that can receive the message can be established by the message sender The providers apply specific message security mechanisms so that the message protection policies are in SOAP Web Services messages Request and response message protection policies are defined when a provider is configured in a container You can also configure application specific message protection policies at the granularity of the web service port or operation within the Sun deployment descriptors of the application or application client Where message protection policies are defined the request and response message protection policies of the client must match the request and response message protection policies ofthe server Securing a Web Service Web Servic
140. located from memory For more information see the servlet API specification For example the destroy method could write a log message like the following example based on the example for Overriding init on page 48 out println myServlet was accessed thisMany times n Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Creating Servlets Overriding Service Get and Post When a request is made Sun Java System Web Server 7 0 sends incoming data to the servlet engine to process the request The request includes form data cookies session information and URL name value pairs all in a type HttpServletRequest object called the request object Client metadata is encapsulated as a type HttpServletResponse object called the response object The servlet engine passes both objects as the servlet s service method parameters The default service method in an HTTP servlet routes the request to another method based on the HTTP transfer method POST and GET For example HTTP POST requests are routed to the doPost method HTTP GET requests are routed to the doGet method This routing enables the servlet to perform different request data processing depending on the transfer method Because the routing takes place in service you do not need to override service in an HTTP servlet Instead override doGet anddoPost depending on the expected request type The automatic routing in an HTTP
141. looks for the named parameter or field in the specified scope If this element is not present the web container uses the Servlet Path the path section that corresponds to the servlet mapping that activated the current request See the Servlet 2 4 specification section SRV 4 4 for details on the Servlet Path Subelements none Attributes The following table describes attributes for the key field element Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Elements in the sun web xml File TABLEA 39 key field Attributes Attribute Default Value Description name none Specifies the input parameter name Scope request parameter Optional Specifies the scope in which the input parameter can be present Allowed values are context attribute request header request parameter request cookie session id and session attribute constraint field Element Specifies a cache ability constraint for the given url pattern or servlet name All constraint field constraints must pass for a response to be cached If value constraints are listed at least one of them must pass Subelement The following table describes the value subelements for the constraint field element TABLE A 40 constraint field Subelements Element Required Description value Element on page 186 zero or more Contains a value to be matched to the input parameter value Attributes
142. lper name myHelper class name MyCacheHelper gt lt cache mapping gt lt servlet name gt myservlet lt servlet name gt lt timeout name timefield gt 120 lt timeout gt lt http method gt GET lt http method gt lt http method gt POST lt http method gt lt cache mapping gt lt cache mapping gt lt url pattern gt catalog lt url pattern gt lt cache the best selling category cache the responses to this resource only when the given parameters exist Cache only when the catalog parameter has qliliesq or qrosesq but no other catalog varieties orchard catalogbest amp category lilies orchard catalogbest amp category roses but not the result of orchard catalog best amp category wild gt lt constraint field name best scope request parameter gt lt constraint field name category scope request parameter gt lt value gt roses lt value gt lt value gt lilies lt value gt lt constraint field gt lt Specify that a particular field is of given range but the field does not need to be present in all the requests gt constraint field name SKUnum scope request parameter gt value match expr qin range gt 1000 2000 lt value gt lt constraint field gt lt cache when the category matches with any value other than a specific value gt lt constraint field name category scope request parameter gt value match expr equals cache on match failure true gt bogus lt
143. m Enterprise Edition Java EE security features Deploying applications Managing virtual servers Defining server workload and sizing the system to meet performance needs Searching the contents and attributes of server documents and creating a text search interface m Configuring the server for content compression m Configuring the server for web publishing and content authoring using WebDAV 12 Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Preface TABLEP 1 Books in the Sun Java Documentation Set Continued Documentation Title Contents Sun Java System Web Server 7 0 Developer s Guide Using programming technologies and APIs to do the following m Extend and modify Sun Java System Web Server Dynamically generate content in response to client requests and modify the content of the server Sun Java System Web Server 7 0 Update 1 NSAPI Developer s Guide Creating custom Netscape Server Application Programmers Interface NSAPI plug ins Sun Java System Web Server 7 0 Developers Guide to Java Web Applications Implementing Java Servlets and JavaServer Pages JSP technology in Sun Java System Web Server Sun Java System Web Server 7 0 Administrators Configuration File Reference Sun Java System Web Server 7 0 Performance Tuning Sizing and Scaling Guide Editing configuration files Tuning Sun Java System Web Server to optimize performance
144. me period or invalidate it manually You can also bind objects to the session which store them for use by other components This section includes the following topics Creating or Accessing a Session on page 85 Examining Session Properties on page 86 Binding Data to a Session on page 87 Invalidating a Session on page 88 Creating or Accessing a Session To create a new session or gain access to an existing session use the HttpServletRequest method getSession as shown in the following example HttpSession mySession request getSession getSession returns the valid session object associated with the request identified in the session cookie that is encapsulated in the request object Calling the method with no arguments creates a session that is associated with the request if one does not already exist Additionally calling the method with a Boolean argument creates a session only if the argument is true The following example shows the doPost method from a servlet that only performs the servlet s main functions ifthe session is present Note that the false parameter to getSession prevents the servlet from creating a new session if one does not already exist public void doPost HttpServletRequest req HttpServletResponse res throws ServletException IOException 1 if HttpSession session req getSession false session retrieved continue with servlet operations else no session return
145. ment The default name c is used elemQuery Optional The name ofthe Start element The default name qt is used elemStart Optional The name ofthe Start element The default name si is used elemNumShown Optional The name of the numShown element The default name ns is used Usage slws formAction formSubmissionTag This tag tests whether the form submission is successful Attributes The formsubmission tag uses the following attributes formld Specifies the name ofthe form in question This name must the name assigned with lt formAction gt success Indicates if the form submission is successful The values true or yes represents successful action All other inputs are rendered as failure Usage slws formSubmission success true gt lt slws search gt lt slws formSubmission gt formActionMsg Tag This tag prints out an error message from formAction if any Attributes The formActionMsg tag uses the following attributes formld Optional Specifies the name of the form in question If not specified the default ID is searchForm elem optional Specifies the name of the element Valid inputs are query and collection When specified the tag returns an error message if any regarding the element Otherwise all of the error messages generated are printed out Chapter 5 Developing JavaServer Pages 79 JSP Search Tags 80 Usage FormActionMsg elem query gt
146. ments and configuration information ofa web application between application developers application assemblers and deployers For Java Servlets v 2 4 the deployment descriptor is defined in terms of an XML schema document Migration Issues Migration creates a detailed log in the user specified log file For every instance alog is created in the following syntax MIGRATION server instance name MMM DD YYYY HH MM_AM PM log If no log directory exists the log file is stored at install dir admin server logs 153 Java EE Standard Descriptors Java EE Standard Descriptors This section describes the Java EE descriptors Sun web xml You define roles in the deployment descriptor file web xml and the corresponding role mappings in the sun web xml deployment descriptor file for individually deployed web modules default web xml default web xml is a global web deployment descriptor file that is shared by deployed web applications It is used to configure the DefaultServlet and JspServtet servlets In addition it specifies MIME mappings based on extensions Welcome files Global filters and security constraints Individual web applications inherit and might override the configuration settings inherited from default web xml with their own web xml The default web xml for each server instance is shared by all web applications deployed on the server instance Depending on the configuration capabilities of the hosting application
147. ments in the sun web xml File 162 Subelements The following table describes subelements for the servlet element TABLEA 7 servlet Subelements Element Required Description servlet name Element on only one Contains the name of a servlet which is matched to page 162 a servlet name in web xml principal name Element on only one Contains a principal user name in the current page 162 realm Attributes none servlet name Element This element contains data that specifies the name ofa servlet which is matched toa servlet name in web xml This name must be present in web xml Subelements none Attributes none role name Element This element contains data that specifies the role name in the security role element of the web xml file Subelements none Attributes none principal name Element This element contains data that specifies a principal user name in the current realm Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Elements in the sun web xml File Subelements none Attributes none group name Element This element contains data that specifies a group name in the current realm Subelements none Attributes none Session Elements Session elements are as follows session config Element on page 163 session manager Element on page 164 manager properties Element on page 165 store properties Element on pag
148. ml contains one or more soap auth provider elements each of which contains a list of configured soap message security providers The server element also includes a default soap auth provider name for the default SOAP message level authentication provider See Chapter 3 Elements in server xml in Sun Java System Web Server 7 0 Administrators Configuration File Reference for more information Administration Command Line Interface CLI support is provided to add remove and list the soap auth provider element in server xml The CLI also supports adding a deafult soap auth provider name to server xml Security Enhancements to sun web xml Security related additions to sun web xml are described in detail in the following sections webservice endpoint Element The syntax for the webservice endpoint elementis as follows lt ELEMENT webservice endpoint port component name endpoint address uri login config message security binding transport guarantee service gname tie class servlet imp class gt TABLE8 2 webservice endpoint Element Element Name Occurrences Description Type port component name 1 Unique name of PCDATA a Web Service within a module This name should be the same as the endpoint name in sun jaxws xml endpoint address uri Oorl Unused for Web PCDATA Server login config Unused for Web Server Sun Java System Web Server 7 0 Developer s Guide to Java Web Application
149. must be very careful in making sure that authentication is established before accessing any restricted resources or methods The application developer must also verify the status of the login attempt and to alter the behavior of the application accordingly The programmatic login state does not necessarily persist in sessions or participate in single sign on Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Programmatic Login Lazy authentication is not supported for programmatic login If an access check is reached and the deployed application has not properly authenticated using the programmatic login method access is denied immediately and the application might fail if not properly coded to account for this occurrence Granting Programmatic Login Permission The ProgrammaticLoginPermission permission is required to invoke the programmatic login mechanism for an application This permission is not granted by default to deployed applications because it is not a standard Java EE mechanism To grant the required permission to the application add the following code to the instance dir config server policy file grant codeBase file jar file path permission com sun appserv security ProgrammaticLoginPermission login ic The jar file pathisthe path to the application s JAR file Note If the Security Manager is disabled it is not mandatory to grant permission For more information about the server
150. n stopping and destroying loaded applications The system is preparing to shut down terminating The container is being closed which terminates the built in subsystems and server runtime environment m reconfig A transient server state in which a server thread is dynamically reconfiguring while the rest ofthe server in the service state This state can occur several times during the life of the server 101 TheLifecycleListener Interface The LifecycleListener Interface Sun Java System Web Server 7 0 enables you to write classes and customize various phases of the server lifecycle For instance you may have a startup code that ensures a remote data source is available for the applications Such classes are notified by server lifecycle events The Sun Java System Web Server 7 0 defines a LifecycleListener interface that users can implement and register with the Server The syntax of this interface is as follows public void handleEvent LifecycleEvent event receives a lifecycle event In its event parameter the programmatic interface for LifecycleListener provides the following features to the implementation classes Access to initialization parameters Ahandler to the server run time environment for naming logging and accessing resources Exception handling mechanics The LifecycleEvent Class The LifecycleEventclass is an interface from the point of view to the developer even if programmatically it is a class T
151. n acknowledges the pioneering efforts of Xerox in researching and developing the concept of visual or graphical user interfaces for the computer industry Sun holds a non exclusive license from Xerox to the Xerox Graphical User Interface which license also covers Sun s licensees who implement OPEN LOOK GUIs and otherwise comply with Sun s written license agreements U S Government Rights Commercial software Government users are subject to the Sun Microsystems Inc standard license agreement and applicable provisions ofthe FAR and its supplements DOCUMENTATION IS PROVIDED ASIS AND ALL EXPRESS OR IMPLIED CONDITIONS REPRESENTATIONS AND WARRANTIES INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY FITNESS FOR A PARTICULAR PURPOSE OR NON INFRINGEMENT ARE DISCLAIMED EXCEPT TO THE EXTENT THAT SUCH DISCLAIMERS ARE HELD TO BE LEGALLY INVALID Copyright 2007 Sun Microsystems Inc 4150 Network Circle Santa Clara CA 95054 U S A Tous droits r serv s Ce produit ou document est prot g par un copyright et distribu avec des licences qui en restreignent l utilisation la copie la distribution etla d compilation Aucune partie de ce produit ou document ne peut tre reproduite sous aucune forme par quelque moyen que ce soit sans l autorisation pr alable et crite de Sun et de ses bailleurs de licence s il y en a Le logiciel d tenu par des tiers et qui comprend la technologie relative aux polices de caract res est prot g par un
152. n jdbc odbc JdbcOdbcDriver The JDBC driver For more information about the JDBC API see http java sun com products jdbc index jsp Applicable only if the session data store parameter is set to the JdbcStore class url jdbc odbc LocalServer Specifies the data source Applicable only ifthe session data store parameter is set to the JdbcStore class 94 Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Session Managers TABLE6 6 manager properties for IMS60 Continued Property Name Default Value Description table sessions Name of the SQL table that store sessions Applicable only ifthe session data store parameter is set to the JdbcStore class username none The login user name for the database Applicable only ifthe session data store parameter is set to the JdbcStore class password none The login password for the database Applicable only ifthe session data store parameter is set to the JdbcStore class reaperActive true When set to true the session manager runs session reaper to remove expired sessions from the database The default is true Only one server in the cluster should run the reaper Applicable only ifthe session data store parameter is set to the JdbcStore class accessTimeColumn AccessTime The name ofthe column that holds the last access time in minutes The SQL type is NUMERIC 9 Applicable
153. ne compiler for JSPs no longer supports javac option Since this property is deprecated you are strongly encouraged to modify JSPs so that the imported classes have a package name See also the deprecatedjavac switch of jspc described in Compiling JSPs Using the Command Line Compiler on page 67 Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Elements in the sun web xml File TABLE A 44 jsp config Properties Continued Property Name Default Value Description javaEncoding UTF8 Specifies the encoding for the generated Java servlet This encoding is passed to the Java compiler used to compile the servlet as well By default the web container tries to use UTF8 If that fails it tries to use the javaEncoding value For encodings you can use see http java sun com j2se 1 5 0 docs guide intl encoding doc html classdebuginfo false Specifies whether the generated Java servlets should be compiled with the debug option set g for javac keepgenerated true If set to true keeps the generated Java files If false deletes the Java files mappedfile false If set to true generates separate write calls for each HTML line and comments that describe the location ofeach line in the JSP file By default all adjacent write calls are combined and no location comments are generated scratchdir Default work directory The working directory created for storing all of the for the
154. next Only required for type full JSP Internationalization Issues This section covers internationalization as it applies to the JSPs JSP Character Encoding A JSP page uses a character encoding For valid encodings to use see http java sun com j2se 1 5 0 docs guide intl encoding doc html The encoding can be described explicitly using the pageEncoding attribute of the page directive The character encoding defaults to the encoding indicated in the contentType attribute ofthe page directive if it is given 82 Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications gt CHAPTER 6 Session Managers Session objects maintain state and user identity across multiple page requests over the normally stateless HTTP protocol A session persists for a specified period of time across more than one connection or page request from the user A session usually corresponds to one user who might visit a site many times The server can maintain a session either by using cookies or by rewriting URLs Servlets can access the session objects to retrieve state information about the session This chapter describes sessions and session managers and has the following sections Introducing Sessions on page 83 Using Sessions on page 85 Session Managers on page 89 Introducing Sessions The term user session refers to a series of user application interactions that are tracked by the server Sessions are use
155. ng Web Applications 135 Deploying Web Applications 9 136 Click Deploy The web application is deployed For more information about using the Administration Console see the Sun Java System Web Server 7 0 Administrators Guide Deploying Using wadm Note Before you can manually deploy a web application make sure that the server root bin directory is in your path You can use the wadm utility at the command line to deploy a WAR file into a virtual server web application environment as follows wadm user admin user password file admin pswd file host admin host port admin port no ssl rcfile rcfile no prompt commands file filename For more information about how to add enable and disable web applications see the add webapp 1 The following table describes the command parameters The left column lists the parameter and the right column describes the parameter TABLE9 1 Command Parameters Parameter Description user Specify the user name of the authorized Web Server administrator password file Specify the password file The password file contains the password to authenticate administrators to the administration server This file must contain the line adm password password If you do not specify this option you will be prompted for a password while executing this command host Specify the name ofthe machine where the administration server is running The def
156. nked library that interacts with the Java Virtual Machine Profiler Interface JVMPI and writes out profiling information either to a file or to a socket in ASCII or binary format This information can be further processed by a profiler front end tool such as HAT HPROF can present CPU usage heap allocation statistics and monitor contention profiles In addition it can also report complete heap dumps and states of all of the monitors and threads in the Java virtual machine For more details on the HPROF profiler see the JDK documentation at http java sun com j2se 1 4 2 docs guide jvmpi jvmpi html Once HPROF is installed its libraries are loaded into the server process Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Using Profiling for Debugging You can configure Sun Java System Web Server 7 0 To Install the HPROF Profiler Access the Admin Console Click the Edit Java Settings tab in the home page The JVM General Settings screen appears Click Profilers Click New The Create JVM Profiler popup appears Type the Name and select the JVM Profiler option to enable the profiler Leave the Class Path and Native Library Path fields blank Click New to configure the JVM options Click OK Edit the server xml file as appropriate hprof options gt profiler name hprof enabled true lt jvm options gt Xrunhprof file log txt options lt jvm options gt lt profiler
157. nt TABLEA 45 parameter encoding Attributes Attribute Default Value Description form hint field none The value ofthe hidden field in the form that specifies the parameter encoding default charset none This value is used for parameter encoding if neither request setCharacterEncoding is called nor form hint fieldisfoundin the request Subelements none Attributes none locale charset infoElement Specifies the mapping between the locale and the character encoding that should be set in the Content type header of the response ifa servlet or JSP sets the response locale using the ServletResponse setLocale method This setting overrides the web container s default locale to charset mapping Subelements The following table describes subelements for the Locale charset info element Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Elements in the sun web xml File TABLEA 46 locale charset info Subelements Element Required Description locale charset map one or more Maps a locale to a character set Element on page 191 parameter encoding Zero or one Deprecated Use the parameter encoding element Element on page 190 under sun web app instead This setting is supported only for backward compatibility with applications developed under Sun Java System Web Server 7 0 Attributes The following table describes the default Locale attributes for the Locale c
158. nt on Zero or more page 160 Specifies a property which has a name and a value Attributes none Properties The following table describes properties for the store properties element Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Elements in the sun web xml File TABLEA 14 store properties Properties Property Name reapIntervalSeconds Default Value 60 Description Specifies the number of seconds between checks for expired sessions for those sessions that are currently swapped out Set this value lower than the frequency at which session data changes is recommended For example this value should be as low as possible 1 second for a hit counter servlet on a frequently accessed web site or you could lose the last few hits each time you restart the server directory directory specified by javax servlet context tempdir context attribute Specifies the absolute or relative path name ofthe directory into which individual session files are written A relative path is relative to the temporary work directory for this web application session properties Element This element specifies session properties Subelements The following table describes the property subelement for the session properties element TABLEA 15 session propertiesSubelements Element Required Description property Element on page 160 Zero or more Specifies a
159. ntegrated Java Web Services runtime and tools and therefore supports portable Web Services implementations For more information see Chapter 3 Web Services Overview JNDI Naming Web Server 7 0 provides Java Naming and Directory Interface JNDI API support that enables web applications to look up for Java Enterprise Edition Java EE services such as Java DataBase Connectivity JDBC data sources All functional aspects of this JNDI implementation are essential However the web server s implementation does not support the CosNaming service required for remote objects as well as lookup of UserTransaction ORB JMS resources or the EJB references JDBC Connection Pooling In Sun Java System Web Server 7 0 JDBCRESOURCE and JDBCCONNECTIONPOOL elements in server xml have been merged into one element called jdbc resource to simplify JDBC configuration Many of the configuration parameters have been renamed For more information on the jdbc resource element see Chapter 3 Elements in server xml in Sun Java System Web Server 7 0 Administrators Configuration File Reference Using JNDI to Access the jdbc resource Within a Web Application UsingJNDL a web application can access a JDBC connection pool by looking up the jdbc resource that configures it The jdbc resources can access the name in its web descriptor The following web descriptors example refer to the connection pool created in the earlier example WEB INF web xm
160. o oU Ie be e RO e t COO S JSP Element accetti ettet tet eese tes esee ha Navstel eee es eee te eed cw bees Internationalization Blenients o ette etes b d eei etos pe ton Alphabetical List of sun web xml Elements Sample Web Application XML Files ueteris dde teet tue e Ee eee edis Sample we bis dtm File trem t tid eet Sample suri web xmUEile 2 5 2 reete d dte dece te an ead esos t ee dicus 10 Preface This guide is a starting point for developers who need information about using the various APIs and programming technologies that are supported by Sun Java System Web Server 7 0 The guide summarizes the APIs and provides information about configuring your server to work with server side HTML tags and CGI programs Who Should Use This Book The intended audience for this guide is the person who develops assembles and deploys web applications in a corporate enterprise This guide assumes you are familiar with the following topics HTML Java programming language Structured database query languages such as SQL Relational database concepts Software development processes Before You Read This Book The Sun Java software can be installed as a stand alone product or as a component of Sun Java Enterprise System Java ES a software infrastructure that supports enterprise applications distributed across a network or Internet environment If you are installing the Sun Java software asa component of Java ES you shou
161. of the JSP on failure S Specifies the name of the JSP on success p name Specifies the name of the target package for all specified JSPs overriding the default package generation performed by the d option c name Specifies the target class name of the first JSP compiled Subsequent JSPs are unaffected mapped Generates separate write calls for each HTML line in the JSP die Generates an error return code on fatal errors default 1 uribase dir Specifies the URI directory to which compilations are relative Applies only to explicitly declared JSP files This path is the location of each JSP file relative to the uriroot If this location cannot be determined the default is uriroot dir A directory containing a web application All JSPs in the directory and its subdirectories are compiled You cannot specify a WAR JAR or ZIP file You must first extract such files to an open directory structure compile Compiles the generated servlets genclass Generates class files in addition to Java files Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Compiling JSPs Using the Command Line Compiler TABLE5 2 Basic jspc Options Continued Option Description webinc file Creates a partial servlet mappings in the file web xml file Creates a complete web xml structure in the file ieplugin clsid Java Plug in classid for Internet Explorer
162. ompressed archives and other data A web application can be packaged into a web archive WAR file or exist in an open directory structure Web Server 7 0 also supports SHTML and CGI which are not Java Platform Enterprise Edition Java EE application components For more information about APIs and programming technologies see Sun Java System Web Server 7 0 Developers Guide Developing and Deploying Web Applications This section describes how to create secure and deploy web applications using Sun Java System Web Server 7 0 25 Developing and Deploying Web Applications 26 Creating Web Applications This section lists the general actions to create a web application and provides pointers to more information L 10 Create a directory for all ofthe web application s files This directory is the web application s document root Create any needed HTML files image files and other static content Place these files in the document root directory or a subdirectory where they can be accessed by other parts of the application Create any needed JSP files For more information see Chapter 5 Developing JavaServer Pages Create any needed servlets For more information see Chapter 4 Developing Servlets Compile the servlets For details about precompiling JSPs see Compiling JSPs Using the Command Line Compiler on page 67 Organize the web application as described in Web Application Structure on
163. onion i AERA tei dere ua EER 147 Generating Stack Trace for Debuggihg essien a aa 147 Using Logeing for Debugging itn i ur RHENO HOUR PERI ns ER T 148 Y To Changethe Log Settings iue esee notorie e rper er coe ti lobe Rois 148 Using Profiling for Debugging Using the HPROF Profiler V To Install the HPROE Profilet 3 ero tecta d apin ete aee ta eter 149 Using the Optimizeit Profiler 5 terrere teorie o rese hostes nho 150 Deployment Descriptor Files essent tnnt tenentes 153 About Deployment Descriptor Files sssseeeenete tette 153 Migration ISSUES o Gene ra UERITAS ER CLIE NOU AKER 153 Java BE Standard Descriptors 222 c a RU I E SUR RoHS DO ERROR 154 SUNWEB Xml 2 25 59 Goa mede hdi et het dit oed p en Oo MO nd 154 defaut web Xm ud e eed i ee e e n He ES ee EE EAR SIR IN NEUE EUR RINT ORI AT ARRIUS 154 Sun Java System Web Server DESCrIptOr Sarain a a A a 154 The sun web app 2 4 1 dtd File naipiga aara e Ea aR aE PANEER ES 154 Subelements oar aE E E O ENAA 155 DE e AA A A A LI E A A ATN 155 ubi d 156 Elements in the Sum wel xml File cere cote teer EE dbase tede ebd ebd 156 General Elements 1 225 roe ptos dr RE REDUX WR YR RIEN TU PARIGI WAT ENS SeCuirity ElEMERts D Session BLEMENtS Reference Elements Caching Blements siano eene sem at UE de duni de udis Classloader Element 5o acer aree pit ra
164. ons Creating Web Deployment Descriptors Sun Java System Web Server 7 0 web applications include two deployment descriptor files A Java EE standard file web xml described in the Java Servlet 2 4 specification You can find the specification at http java sun com products servlet download html An optional Sun Java System Web Server 7 0 specific file sun web xml described later in this chapter The easiest way to create the web xml and sun web xml files is to deploy a web application using Sun Java Studio Enterprise 8 1 For sample web xml and sun web xml files see Sample Web Application XML Files on page 196 Deploying Web Applications v Before You Begin 1 You can deploy a web application using either the Admin console or the command line interface To Deploy Using Admin Console Select the virtual server in which you need to deploy the web application Access the Admin Console Clickthe Add Web Application tab in the home page The Add Web Application screen appears Specify the location or package file path to upload to the Web Server Type the URI for your web application Specify the URI This URI is the application s context root and is relative to the server host Select JSP pre compilation Click OK The Web Application page appears Click Save Click the Deployment Pending link in the top right of the screen The Configuration Deployment screen displays Chapter9 Deployi
165. or JSP pages The format of these URLs is as follows http server port context roott se rvlet servlet name name value The following table describes each URL section TABLE4 1 URL Fields for Servlets Withina Web Application URL Element Description server port The IP address or host name and optional port number To access the default web application for a virtual server specify only this URL section You do not need to specify the context root or servlet name unless you also wish to specify name value parameters context root The context path without the leading at which the web application is installed servlet Only needed if no servlet mapping is defined in the web xml file servlet name The servlet name or servlet mapping if defined as configured in the web xml file name value Optional servlet name value parameters In this example example is the host name MortPages is the context root and calcMortgage is the servlet name Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Servlet Output http www example com MortPages servlet calcMortgage rate 8 amp per 360 amp bal 180000 Calling a Servlet Programmatically First identify which servlet to call by specifying a URI This URI is normally a path relative to the current application For example if your servlet is part of an application with a context root named Of ficeFrontEnd the URL to a
166. or refreshed Can be overridden by a timeout element enabled false Optional Determines whether servlet and JSP caching is enabled Legal values are on off yes no 1 0 true false Properties The following table describes properties for the cache element TABLEA 30 cache Properties Property Name Default Value Description cacheClassName com sun appserv web Specifies the fully qualified name of the class that implements the cache functionality For a list of valid values see Cache Class Names on page 179 cache LruCache Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Elements in the sun web xml File TABLEA 30 cache Properties Continued Property Name Default Value Description MultiLRUSegmentSize 4096 Specifies the number of entries in a segment of the cache table that should have its own LRU least recently used list Applicable only if cacheClassName is set to com Sun appserv web cache MultiLruCache MaxSize unlimited Long MAX VALUE Specifies an upper bound on the cache memory size in bytes KB or MB units Example values are 32 KB or 2 MB Applicable only if cacheClassName is set to com sun appserv web cache BoundedMultiLruCache Cache Class Names The following table lists possible values of the cacheClassName property TABLEA 31 cacheClassName Values Value Description com sun appserv w
167. ormation about the current session including the user s login name and any additional information to retain Application components can then query the session object to obtain user authentication A session object can store objects such as tabular data information about the application s current state and information about the current user Objects bound to a session are available to other components that use the same session For more information about session objects see Chapter 6 Session Managers Handling Threading Issues By default servlets are not thread safe The methods in a single servlet instance are usually executed numerous times simultaneously up to the available memory limit Each execution occurs in a different thread though only one servlet copy exists in the servlet engine This efficient system resource usage is dangerous because ofthe way the environment Java language manages memory Because variables belonging to the servlet class are passed by reference different threads can overwrite the same memory space as a side effect To make a servlet or a block within a servlet thread safe do one of the following Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Creating Servlets Synchronize write access to all instance variables as in public synchronized void method whole method or synchronized this block only Because synchronizing slows response time considerably synch
168. oss processes The default value is used if the value 0 is specified This parameter is ignored in single process mode Chapter6 Session Managers 93 Session Managers TABLE6 6 manager properties for IWS60 Continued Property Name Default Value Description session data store The name ofthe class that determines the means of session persistence The classes supplied with Sun Java System Web Server 7 0 are com iplanet server http session JdbcStore com iplanet server http session FileStore Ifyou do not specify the session data store parameter sessions are not persistent in single process mode and FileStore is the default in multi process mode The JdbcStore and FileStore classes are subclasses ofthe session data store class You can create your own class that implements session persistence by extending SessionDataStore session failover enabled Specifies whether sessions are reloaded from the persistent store for every request and always forced to true in multi process mode Applicable only if the session data store parameter is set to the JdbcStore or FileStore class session data dir The following text is single path server root server id SessionData virtual server id web app URI The directory in which session data for all servers and web applications is kept Applicable only if the session data store parameter is set to the FileStore class provider su
169. p java sun com products servlet download html 107 Common Security Terminology Support for single sign on across all Sun Java System Web Server 7 0 applications within a single security domain Support for several underlying authentication realms such as simple file and LDAP Certificate authentication is also supported for SSL client authentication Solaris OS platform authentication is also supported Support for declarative security through Sun Java System Web Server 7 0 specific XML based role mapping Support for Java Security Manager enforcement For more information about Java EE security see the Chapter 6 Certificates and Keys in Sun Java System Web Server 7 0 Administrator s Guide Common Security Terminology 108 This section provides an overview of the common security terminology The most common security processes are authentication authorization realm assignment and role mapping m Authentication on page 108 Authorization on page 108 Realms on page 109 Java EE Application Role Mapping on page 109 Authentication Authentication verifies the user For example when the user provides a user name and password in a web browser if those credentials match the permanent profile stored in the active realm the user is authenticated The user is associated with a security identity for the remainder of the session For more information on authentication realms see Managin
170. p12 sample application demonstrates how to use the WS Security functionality to secure an existing Web Services application The instructions helps you to enable the WS Security functionality of the Web Server so that it is used to secure the fromwsdl soap12 application The f romwsdl soap12 sample application is installed in the install dir samples java webapps webservices security fromwsdl soap12 directory Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications gt CHAPTER 4 Developing Servlets This chapter describes how to create servlets to control web application interactions running on a Sun Java System Web Server 7 0 In addition this chapter describes the Sun Java System Web Server 7 0 features used to augment the Java Servlet 2 4 standards This chapter has the following sections About Servlets on page 45 Creating Servlets on page 47 Invoking Servlets on page 54 Servlet Output on page 55 Caching Servlet Results on page 56 Maximizing Servlet Performance on page 61 Servlet Internationalization Issues on page 61 Migrating Legacy Servlets on page 62 About Servlets Servlets like applets are reusable Java applications Servlets however run on a web server rather than in a web browser Servlets provide a component based platform independent method for building web based applications without the performance overheads process limitations and
171. page 133 Sun Java Studio Enterprise 8 1 Web Server 7 0 supports Sun Java Studio Enterprise 8 1 Standard Edition You can use Sun Java Studio to assemble and deploy web applications For more information see Using Sun Java Studio Enterprise 8 1 on page 132 JSR 88 Support for Application Deployment You can write your own Java Specification Request JSR 88 client to deploy applications to the Web Server 7 0 For more information see http jcp org en jsr detail id 88 Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications API Changes from Web Server 61 to Web Server 7 0 Lifecycle Listeners and Modules Sun Java System Web Server 7 0 enables you to write customized classes for the various phases ofthe server lifecycle For instance a user may have a startup code that ensures that a remote data source is available for the applications Such classes are notified of server lifecycle events supporting Java based tasks within the Web Server environment These tasks automatically perform actions such as starting the server and sending notification if the server shuts down Youcan use this support to instantiate singletons RMI servers and so forth For more information see List of Elements in Sun Java System Web Server 7 0 Administrators Configuration File Reference Session Replication The intention of session replication is to provide sufficient session failover support through in memory backup of HT
172. pecification issues with Java EE applications All Java EE applications should be able to run with the Security Manager active and with only the default permissions Therefore the Security Manager should be turned on during development Applications that can easily be deployed in environments where the Security Manager is always active such as some versions of Sun Java System Application Server Running with the Security Manager also helps isolate applications and may catch inappropriate operations The main drawback of running with the Security Manager is that it negatively affects performance Depending on the application details and the deployment environment this impact could be minor or quite significant The server policy File 128 Each Sun Java System Web Server 7 0 instance has its own standard Java Platform Standard Edition Java SE platform policy file located in the instance_dir config directory The file is named server policy Sun Java System Web Server 7 0 is a Java EE 1 4 compliant web server As such it follows the recommendations and requirements of the Java EE specification including the optional presence of the Security Manager which is the Java component that enforces the policy and a limited permission set for Java EE application code This section includes the following topics Default Permissions on page 129 Changing Permissions for an Application on page 129 Sun Java System Web Server 7
173. pecifies a property which has a name and a value page 160 Attributes none Properties The following table describes properties for the cookie properties element Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Elements in the sun web xml File TABLEA 18 cookie properties Properties Property Name Default Value Description cookiePath Context path at which Specifies the path name that is set when the session the web application is tracking cookie is created The browser sends the installed cookie if the path name for the request contains this path name If set to root the browser sends cookies to all URLs served by the Sun Java System Web Server 7 0 You can set the path to a narrower mapping to limit the request URLs to which the browser sends cookies cookieMaxAgeSeconds 1 Specifies the expiration time in seconds after which the browser expires the cookie The default value of 1 indicates that the cookie never expires cookieDomain unset Specifies the domain for which the cookie is valid cookieComment Sun Java System Web Specifies the comment that identifies the session Server session tracking tracking cookie in the cookie file Applications can cookie provide a more specific comment for the cookie Reference elements are as follows resource env ref Element on page 169 resource env ref name Element on page 170 resource ref Element on pa
174. pecifies additional classpath settings for this web application If this path is not an absolute path it is treated as relative to web app path value 186 Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Elements in the sun web xml File TABLE A 42 class loader Attributes Continued Attribute Default Value Description delegate false Optional If t rue the web application follows the standard classloader delegation model and delegates to its parent classloader first before looking in the local classloader If false the web application follows the delegation model specified in the Servlet specification and looks in its classloader before looking in the parent classloader Fora web component ofa web service you must set this value to true Legal values are on off yes no 1 0 true false dynamic reload interval value ofthe dynamicreloadinterval attribute of the lt j vm element in server xml Optional Enables an application to override the dynamicreloadinterval setting in server xml Specifies the frequency in seconds at which a web application is checked for modifications and then reloaded if modifications have been made Setting this value to less than or equal to 0 disables dynamic reloading of the application If not specified the value from server xml is used For more information about server xml see Sun Java System Web Server 7 0
175. play all collections with checkboxes select name elementname gt lt slws collection gt option value lt slws collItem property name gt gt lt slws colleItem property display name gt lt slws collection gt lt select gt This function iterates through the available collections and passes each item to the collection item tag which in turn displays the name and display name of the item collItemTag This tag displays the name and label of one collection item This tag must be used inside the collection tag Attributes Property Specifies a keyword indicating which property the tag should output Valid inputs include name display name and description Default is name Usage lt select name elementname gt lt slws collection gt option value lt slws collItem property name gt gt lt slws collItem property display name gt lt slws collection gt lt select gt This function iterates through the available collections and passes each item to the collection item tag which in turn displays the name and display name of the item queryBox Tag This tag creates an input box Attributes The queryBox tag uses the following attributes name Optional The name of the inputbox The default is qt default Optional The default value for the query box If the form is submitted its value will be set using this setting Chapter 5 Developing JavaServer Pages 77 JSP Search Tags
176. plications Deployment Tools For more information about Sun Java Studio Enterprise 8 1 visit http www sun com software sundev jde Note For basic information about using Sun Java Studio Enterprise 8 1 to debug web applications see Using Developer Tools for Debugging on page 147 Using NetBeans IDE 5 5 NetBeans IDE 5 5 is an integrated development environment to create deploy and software Java EE web applications This section describes how to use the NetBeans IDE 5 5 to create and deploy the web applications for Sun Java System Web Server 7 0 To Install NetBeans IDE 5 5 Download NetBeans IDE 5 5 from webserver netbeans org and install it After installation launch the NetBeans IDE 5 5 Download the latest plug in Extract the org netbeans modules j2ee sun ws7 nbm file Select Update Center of NetBeans from the Tools menu Select Install Manually Downloaded Modules nbm Files and click Next Add the downloaded nbm files and click Next Select Sun Java System Web Server 7 0 and click Next Selectthe Include option and click Yes to install the plug in The Web Server 7 0 plug in is installed in the IDE To Register Web Server 7 0 in the NetBeans IDE 5 5 Start the NetBeans Select Server node in the Runtime tab Press mouse button and choose Add Server from the popup menu Selectthe Sun Java System Web Server 7 0 to register the Web Server and click Next Chapter9 Deploying Web Applications 133 De
177. ploy the sample web application f romwsdl soap12 war on to the Sun Java System Web Server 7 0 Programmatic Login 126 Programmatic login enables a deployed Java EE application to invoke a login method If the login is successful a SecurityContext is established as if the client had authenticated using any ofthe conventional Java EE mechanisms Programmatic login is useful for application with unique needs that cannot be accommodated by any of the Java EE standard authentication mechanisms This section discusses the following topics Precautions on page 126 Granting Programmatic Login Permission on page 127 ProgrammaticLogin Class on page 127 Precautions The Sun Java System Web Server 7 0 is not involved in how the login information user name and password is obtained by the deployed application The application developer must ensure that the resulting system meets security requirements If the application code reads the authentication information across the network the application must to determine whether to trust the user Programmatic login enables the application developer to bypass the Web Server supported authentication mechanisms and feed authentication data directly to the security service While flexible this capability should not be used without some understanding of security issues Because this mechanism bypasses the container managed authentication process and sequence the application developer
178. ployment Tools 134 4 Provide the details of the Sun Java System Web Server 7 0 installed on the local system or remote machine Note The plug in requires a local Web Server installation on the same machine even if you are registering a remote Web server The local installation is required for some of the Web Server jar files Optional If the Web Server contains multiple configuration select the configuration Select the Web Server node form the IDE drop down list Choose the configuration to use Note The drop down list contains configuration which have at least one virtual server and one instance Once the server is registered it is listed in the Server node of the Runtime tab Right click and choose Start You can expand the nodes and see all the web applications and resources Deploying Web Applications Start the NetBeans Select New Project from the File menu Select Web in the category list and in the projects list select web application Then click Next From the Server drop down list select Sun Java System Web Server 7 0 Click Next to complete the web project creation Once the project is created web project is displayed in the Projects tab You can find all basic files created in the Web Server specific sun web xml deployment descriptor The web application is now ready to compile deploy Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Deploying Web Applicati
179. policy file see The server policy File on page 128 ProgrammaticLogin Class The com sun appserv security ProgrammaticLogin class enables a user to log in programmatically Thelogin method for servlets or JSPs has the following signature public Boolean login String user String password javax servlet http HttpServletRequest request javax servlet http HttpServletResponse response This method performs the authentication It returns true if the login succeeded false if the login failed Chapter8 Securing Web Applications 127 Enabling the Java Security Manager Enabling the Java Security Manager Sun Java System Web Server 7 0 supports the Java Security Manager The Java Security Manager is disabled by default when you install the product which can improve performance significantly for some types of applications Enabling the Java Security Manager might improve security by restricting the rights granted to your Java EE web applications To enable the Java Security Manager add the following JVM options to the server xml file lt jvm options gt Djava security manager lt jvm options gt lt jvm options gt Djava security policy instance_dir config server policy lt jvm options gt where instance_dir is the path to the installation directory of this server instance Whether you should run with the Security manager depends on your application and deployment needs Running with the Security Manager helps catch some s
180. property which has a name and a value Attributes none Properties The following table describes properties for the session properties element Appendix A Deployment Descriptor Files 167 Elements in the sun web xml File 168 TABLEA 16 session properties Properties Property Name Default Value Description timeoutSeconds 600 Specifies the default maximum inactive interval in seconds for all sessions created in this web application If set to 0 or less sessions in this web application never expire If a session timeout element is specified in the web xml file the session timeout value overrides any timeoutSeconds value If neither session timeout nor timeoutSeconds is specified the timeoutSeconds default is used Note that the session timeout element in web xml is specified in minutes not seconds enableCookies true Uses cookies for session tracking if set to t rue enableURLRewriting true Enables URL rewriting This provides session tracking via URL rewriting when the browser does not accept cookies You must also use an encodeURL or encodeRedi rectURL call in the servlet or JSP cookie properties Element This element specifies session cookie properties Subelement The following table describes the property subelement for the cookie properties element TABLEA 17 cookie properties Subelement Element Required Description property Element on zero or more S
181. put types RequestDispatcher methods always call service For more information see Calling a Servlet Programmatically on page 55 Chapter 4 Developing Servlets 49 Creating Servlets 50 Accessing Parameters and Storing Data Incoming data is encapsulated in a request object For HTTP servlets the request object type is HttpServletRequest For generic servlets the request object type is ServletRequest The request object contains all request parameters including custom values called attributes To access all incoming request parameters use the getParameter method for example String username request getParameter username Set and retrieve values in a request object using setAttribute and getAttribute respectively for example request setAttribute favoriteDwarf Dwalin Handling Sessions and Security From a Web Server s perspective a web application is a series of unrelated server hits No automatic recognition occurs ifa user has visited the site before even if the last interaction was seconds before A session provides a context between multiple user interactions by remembering the application state Clients identify themselves during each interaction by a cookie or in the case ofa cookie less browser by placing the session identifier in the URL After a successful login you should direct a servlet to establish the user s identity in a standard object called a session object that holds inf
182. r class For example if a servlet only stores the time when a back end data source was last modified you can write a helper class to retrieve the last modified timestamp from the data source and decide whether to cache the response based on that timestamp See CacheHelper Interface on page 58 You can determine cache key generation programmatically by writing a cache key generator class See CacheKeyGenerator Interface on page 60 All non ASCII request parameter values specified in cache key elements must be URL encoded The caching subsystem attempts to match the raw parameter values in the request query string The newly updated classes affect data what gets cached The web container clears the cache during dynamic deployment or reloading of classes The following HttpServletRequest request attributes are m com sun appserv web cachedServletName the cached servlet target m com sun appserv web cachedURLPattern the URL pattern being cached Default Cache Configuration If you enable caching but do not provide any special configuration for a servlet or JSP page the default cache configuration is as follows The default cache timeout is 30 seconds Only the HTTP GET method is eligible for caching HTTP requests with cookies or sessions automatically disable caching No special consideration is given to Pragma Cache control or Vary headers The default key consists of the servlet path minus pathInfo and the query string A
183. r http session FileStore property name directory value directory name to store the persistant sessions other store related properties lt store properties gt lt session manager gt 92 Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Session Managers lt session config gt lt sun web app gt For more information about the sun web xml file see Chapter 9 Deploying Web Applications Manager Properties for 1WS60 The following table describes manager properties properties for the IWS60 session manager TABLE6 6 manager properties for IWS60 Property Name Default Value Description maxSessions 1000 The maximum number of sessions maintained by the session manager at any given time The session manager refuses to create any more new sessions if maxSessions are already number of sessions present at that time timeOut 1800 The amount of time in seconds after a session is accessed by the client before the session manager destroys it Those sessions that are not accessed for at least timeOut seconds are destroyed by the reaper method The session timeout parameter specified in web xml is not a effective when IWS60 is used reapInterval 600 The amount of time in seconds that the SessionReaper thread sleeps before calling the reaper method again maxLocks 10 The number of cross process locks to use for synchronizing access to individual sessions acr
184. r interface 58 59 CacheKeyGenerator interface 60 61 caching default cache configuration 57 example 59 60 JSP 70 74 servlet results 56 61 Sun Java System Web Server features 56 57 class declaration 47 class loader 143 186 187 classloaders 141 143 Bootstrap 143 Common 143 JSP 143 199 Index classloaders Continued runtime hierarchy 141 System 143 Web Application 142 143 client certificates 117 results 52 54 Common Classloader 143 compiling JSPs 67 70 configuring 148 servlet authorization constraints 117 constraint field 185 186 cookie properties 168 169 cookies 83 84 115 168 cookies encoding 158 creating JSPs 66 67 servlets 47 54 sessions 85 86 web deployment descriptors 135 customizing search 74 82 D debugging enabling 145 146 generating stack trace for 147 JPDA options 146 JSPs 147 using log files 148 using NetBeans 147 using profilers 148 151 web applications 145 151 default helper 180 181 default resource principal 176 defining security roles 116 117 servlet authorization constraints 117 deleting web applications 136 deploying web applications 131 143 deployment descriptor files sun web xml 135 description element 160 161 destroy overriding 48 disabling web applications 139 DTD files 154 attributes 156 data 155 156 subelements 155 sun web app_2_4 1 dtd 154 156 dynamic reload interval attribute 187 dynamic
185. re this information between them rather than having the user sign on separately for each application These applications are created to authenticate the user once When needed this authentication information is propagated to all other involved applications An example application using the single sign on scenario could be a consolidated airline booking service that searches all airlines and provides links to different airline web sites Once the user signs on to the consolidated booking service the user information can be used by each individual airline site without requiring another sign on Single sign on operates according to the following rules Single sign on applies to web applications configured for the same realm and virtual server The realm is defined by the realm name element in the web xml file For information about virtual servers see the Sun Java System Web Server 7 0 Administrators Guide Aslongas users access only unprotected resources in any of the web applications on a virtual server they are not challenged to authenticate themselves As soon users access a protected resource in any web application associated with a virtual server they are challenged to authenticate using the login method defined for the web application currently being accessed Once authenticated the roles associated with this user are used for access control decisions across all associated web applications without challenging the user to auth
186. reloading of web applications 139 140 dynamicreloadinterval 187 E editing server xml for debugging 145 to configure single sign on 115 elements in sun web xml 156 195 alphabetical list of 193 195 caching 177 186 classloader 186 187 general 157 161 internationalization 189 193 JSP 187 189 reference 169 177 security 161 163 session 163 169 enabling debugging 145 146 IWS60 92 93 memory 89 the Java Security Manager 128 web applications 139 encodeCookies 158 examples caching 59 60 sun web xml file 197 web xml file 196 exceptions in JSP files 67 F fetching client certificates 117 file manager properties 91 FileStore java 97 200 Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Index form basedlogin 114 G Get overriding 49 group name 163 H HPROF profiler 148 150 HTTP basicauthentication 114 http method 184 HTTPSauthentication 114 l improving servlet performance 61 internationalizing search 74 invalidating a session 88 invoking servlets 54 55 IWS60 91 97 enabling 92 93 manager properties 93 97 source code 97 IWSHttpSession 97 IWSHttpSession java 97 IWSSessionManager java 97 J Java class file loading 141 143 Java EE application role mapping 109 security model 107 108 Java Security Manager enabling 128 Java Servlet 2 4 security model 107 JDBC driver for session management 94 JdbcStore java 97 JDPA options 146 jnd
187. remote profiling by editing server xml file lt Optimizeit options gt lt profiler classpath Optimizeit dir lib optit jar nativelibrarypath Optimizeit dir lib enabled true gt lt jvm options gt DOPTIT HOME Optimizeit dir Xboundthreads Xrunoii Xbootclasspath a Optimizeit dir lib oibcp jar lt jvm options gt lt profiler gt In addition you might need to set the following in your server policy file grant codeBase file Optimizeit dir lib optit jar permission java security AllPermission F For more information about the server policy file see The server policy File on page 128 When the server starts up with this configuration you can attach the profiler Note If any ofthe configuration options are missing or incorrect the profiler might experience problems that affect the performance of the Sun Java System Web Server 7 0 Chapter 10 Debugging Web Applications 151 152 gt APPENDIX A Deployment Descriptor Files This chapter includes the following sections About Deployment Descriptor Files on page 153 Migration Issues on page 153 Java FE Standard Descriptors on page 154 Sun Java System Web Server Descriptors on page 154 The sun web app_2_4 1 dtd File on page 154 Elements in the sun web xml File on page 156 Sample Web Application XML Files on page 196 About Deployment Descriptor Files The deployment descriptor conveys the ele
188. rity role mapping gt lt security role mapping gt lt role name gt administrator lt role name gt lt principal name gt dsmith lt principal name gt 116 Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Fetching the Client Certificate security role mapping sun web app Note that the role name in this example must match the role name in the security role element of the corresponding web xml file For web applications the roles are always specified in the sun web xml file A role can be mapped to specific principals to groups or both principals and groups The principal or group names used must be valid principals or groups in the current realm Defining Servlet Authorization Constraints At the servlet level you can define access permissions using the auth constraint element of the web xml file The auth constraint element on the resource collection must be used to indicate the user roles permitted to the resource collection Refer to the Java Servlet specification for details on configuring servlet authorization constraints Fetching the Client Certificate When you enable SSL and require client certificate authorization your servlets have access to the client certificate as shown in the following example if request isSecure java security cert X509Certificate certs certs request getAttribute javax servlet request X509Certificate if certs null clientCert
189. rmation see http java sun com webservices docs 2 0 fastinfoset fastinfoset1 0 1 manual html Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Creating Web Services Message Security JSR 196 In message security security information is inserted into messages so that it travels through the networking layers and arrives with the message at the message destination Message security differs from transport layer security Message security can be used to decouple message protection from message transport so that the message remains protected after transmission For more information on security see http java sun com j2ee 1 4 docs tutorial doc Security2 html wp268799 JSR 196 as applicable to Web Services defines a standard service provider interface by which authentication mechanism providers may be integrated with containers Providers integrated through this interface establish the authentication identities used in container access decisions while servicing the request Creating Web Services Web Services is created in different ways depending on whether the starting point of development is a Java source file a Java class file ora WSDL file Web Services Tools Use different tools is used to generate JAX WS artifacts depending on whether the starting point of Web Services development is a Java source file a Java class file ora WSDL file apt The Annotation Processing Tool APT tool is part o
190. ronize only blocks or make sure that the blocks in the servlet do not need synchronization Note Web containers synchronize all access to their servlets only when javax servlet SingleThreadModel servlet is implemented javax servlet singleThreadModel is deprecated in Servlet 2 4 For example the following servlet has a thread safe block in doGet and a thread safe method called mySafeMethod import java io import javax servlet import javax servlet http public class myServlet extends HttpServlet public void doGet HttpServletRequest request HttpServletResponse response throws ServletException IOException pre processing synchronized this code in this block is thread safe other processing public synchronized int mySafeMethod HttpServletRequest request everything that happens in this method is thread safe UsetheSingleThreadModel class to create a single threaded servlet When a single threaded servlet is deployed to the Sun Java System Web Server 7 0 the servlet engine creates a servlet instance pool used for incoming requests multiple copies of the same servlet in memory You can change the number of servlet instances in the pool by setting the singleThreadedServletPoolSize property in the Sun Java System Web Server 7 0 Web application deployment descriptor For more information see Chapter 9 Deploying Web Applications Servlet performance becomes slower due to traf
191. ry preserving their location relative to the module specific WSDL directory META INF wsdl or WEB INF wsdl Subelements none Attributes none Alphabetical List of sun web xml Elements This section provides an alphabetical list for the easy lookup of sun web xml elements cache Element on page 177 cache helper Element on page 179 Appendix A Deployment Descriptor Files 193 Elements in the sun web xml File cache helper ref Element on page 182 cache mapping Element on page 181 class loader Element on page 186 constraint field Element on page 185 context root Element on page 159 cookie properties Element on page 168 default helper on page 180 default resource principal Element on page 176 description Element on page 160 group name Element on page 163 http method Element on page 184 jndi name Element on page 177 jsp config Element on page 187 key field Element on page 184 locale charset info Element on page 190 Locale charset map Element on page 191 manager properties Element on page 165 message destination Element on page 192 message destination name Element on page 192 message security binding Element on page 121 name Element on page 176 parameter encoding Element on page 190 password Element on page 176 principal name Element on page 162 property Element on page 160 refresh field Element on page 183 194 Sun Java System
192. s Copy the driver s JAR file into the server s instance library directory JAR files in the instance library directory will automatically load and available for server a Modify the JVM class path suffix to include JDBC drivers jar file The new value will overwrite the old value of the element For example wadm gt set jvm prop config test class path suffix export home lib classes12 jar Sample Applications in Web Server 7 0 Sun Java System Web Server 7 0 includes a set of sample applications which can be found in the install_dir samplesfollowing directory Sample Directories All of the sample applications are arranged in a specific and well defined directory structure In general the top level directory of asample application includes the following src A directory containing all the Java source files deployment descriptors JSPs and HTML files Samples that use a database provide a script to populate data in the database docs A directory containing all documentation for the application m WAR file The deployable W AR file for the sample application m build xml A file for the ANT system to build the sample application Chapter 2 Web Applications Overview 29 Sample Applications in Web Server 7 0 TABLE2 1 Sample Directories Directory Contents caching JSP and servlet examples that demonstrate how to cache results of JSP and servlet execution fastcgi A sample to demonstrate how to use t
193. s Element Required Description servlet name Element on page 162 requires one servlet name or url pattern Contains the name ofa servlet url pattern Element on page 182 requires one servlet name or url pattern Contains a servlet URL pattern for which caching is enabled cache helper ref Element on page 182 required if timeout refresh field http method key field and constraint field are not used Contains the name of the cache helper used by the parent cache mapping element cache mapping Element on page 181 zero or more Specifies the RequestDispatcher methods for which caching is to be enabled on the target resource Valid values are REQUEST FORWARD INCLUDE and ERROR default REQUEST timeout Element on page 183 zero or one if cache helper ref is not used Contains the cache mapping specific maximum amount of time in seconds that an entry can remain in the cache after it is created or refreshed Appendix A Deployment Descriptor Files 181 Elements in the sun web xml File 182 TABLE A 36 cache mapping Subelements Continued Element Required Description ref resh field Element on page 183 zero or one if cache helper ref is not used Specifies a field that gives the application component a programmatic way to refresh a cached entry http method Element on page 184 zero or
194. s Using Web Services Message Security TABLE8 2 webservice endpoint Element Continued message security binding Oorl Used to bind a Web Service endpoint or port to a specific security provider This element can also be used to provide a definition of message security requirements to be enforced by the security provider See Table 8 3 message security binding transport guarantee Oorl Unused for Web Server PCDATA service qname Oorl Unused for Web Server tie class Oorl Unused for Web Server PCDATA servlet impl class Oorl Unused for Web Server Class name message security binding Element The message security binding element is used to bind a web service endpoint or port to a specific security provider The syntax for this element is as follows lt ELEMENT message security binding message security gt lt ATLIST message security binding auth layer message layer REQUIRED provider id CDATA IMPLIED gt TABLE8 3 message security binding Element Element name Occurrences Description Type message security 0 or more Specifies the message security requirements of request and response for the endpoint or port See Table 8 5 Chapter 8 Securing Web Applications 121 Using Web Services Message Security 122 TABLE 8 4 Attributes of the message security binding Element Attri
195. s 165 166 name 176 parameter encoding 190 password 176 principal name 162 163 refresh field 183 184 res ref name 175 203 Index sun web xml elements Continued resource env ref 169 170 resource env ref name 170 resource ref 175 role name 162 security role 117 security role mapping 161 servlet 161 162 servlet name 162 session config 163 164 session manager 164 165 session properties 167 168 store properties 166 167 sun web app 157 timeout 183 value 186 sun web xml file about 116 135 changesto 137 creating 135 definingroles 116 elementsin 156 195 example 197 structure of 154 156 System Classloader 143 T tag libraries JSP 70 tags JSP cache 70 74 search 74 82 threading issues 50 52 timeout element 183 U URL parts of 137 url pattern 182 URL rewriting and sessions 84 using JSPs 65 82 NetBeans 147 using Continued servlets 45 64 V value element 186 W wadm utility 136 WAR files 26 131 136 Web Application Classloader 143 web applications 25 31 about 25 debugging 145 151 deploying 131 143 directory structure of 131 132 dynamic reloading of 139 140 enabling and disabling 139 Java Servlet and JSP specifications 25 response caching 56 57 securing 107 130 web deployment descriptors 135 WEB INF directory 131 web xml elements auth constraint 117 login config 113 more information about 113 realm name 115 res ref name 169 run asrole
196. s supported by the JAX RPC Call implementation AppendixA Deployment Descriptor Files 173 Elements in the sun web xml File 174 TABLEA 24 call property Subelements Element Required Description name Element on page 176 only one Specifies the name of the entity value Element on only one Specifies the value of the entity page 186 wsdl override Element This element specifies a valid URL pointing to a final WSDL document If not specified the WSDL document associated with the service ref in the standard J2EE deployment descriptor is used Subelements none Attributes none service impl class Element Specifies the name ofthe generated service implementation class Subelements none Attributes none service qname Element This element specifies the WSDL service element that is being referred to Subelements The following table describes subelements for the service qname element TABLEA 25 service qname Subelements Element Required Description Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Elements in the sun web xml File TABLE A 25 service qnameSubelements Continued namespaceURI Element on only one Specifies the namespace URI page 172 Localpart Element on page173 only one Specifies the local part ofa QNAME resource ref Element This element maps the res ref name Element on page 175 in
197. s targets using the Admin Console or change the application references using the wadm Because the application is stored in the central repository adding or deleting targets adds or deletes the same version ofan application on different targets However an application deployed to more than one target can be enabled on one target and disabled on another target Therefore even if an application is referenced by a target it is not available to you unless it is enabled on that target In Sun Java System Web Server 7 0 you can enable or disable a web application either using the Admin Console or command line interface To Enable or Disable a Deployed Web Application Access the Admin Console Select the server instance and click the edit Virtual Server tab Click the Web applications tab In the Web Applications table select the web application To enable the application click Enable Todisablethe application click Disable Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Dynamic Reloading of Web Applications 5 Tip Use the enable webapp and disable webapp commands to enable or disable the web application through the command line interface For more information see the enable webapp 1 and disable webapp 1 man pages Click Save Enabling Web Applications Sun Java System Web Server 7 0 allows you to enable or disable a web application You can do so in either ofthe following ways as discusse
198. s requests processes them according to the instructions you provide and directs the output appropriately You can create other methods in a servlet as well Overriding init Override the class initializer init to initialize or allocate resources for the servlet instance s life such as a counter The init method runs after the servlet is instantiated but before it accepts any requests For more information see the servlet API specification Note When extending GenericServlet or HttpServlet you must either override init ServletConfig to first call super init ServletConfig or simply override the init method that takes no arguments This your servlet s ServletConfig enables be saved locally and later returned by calls to your servlet s getServletConfig method The following example ofthe init method initializes a counter by creating a public integer variable called thisMany public class myServlet extends HttpServlet int thisMany public void init ServletConfig config throws ServletException 1 super init config thisMany 0 This method enables other servlet methods to access the variable Overriding Destroy Override the class destructor dest roy to write log messages or to release resources that have been opened in the servlet s cycle Resources should be appropriately closed and de referenced so that they are recycled or garbage collected The dest roy method runs just before the servlet itself is deal
199. s the name of the property or variable value none Specifies the value of the property or variable description Element This element contains a text description of the parent element Subelements none Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Elements in the sun web xml File Attributes none Security Elements The security elements are as follows security role mapping Element on page 161 servlet Element on page 161 servlet name Element on page 162 role name Element on page 162 principal name Element on page 162 group name Element on page 163 security role mapping Element This element maps roles to users or groups in the currently active realm Subelements The following table describes subelements for the security role mapping element TABLEA 6 security role mapping Subelements Element Required Description role name Element on only one Contains the role name page 162 principal name Element on requires atleast one Contains a principal user name in the current page 162 principal name or realm group name group name Element on requires at least one Contains a group name in the current realm page 163 principal name or group name Attributes none servlet Element This element specifies a principal name for a servlet which is used for the run as role defined in web xml Appendix A Deployment Descriptor Files 161 Ele
200. servlet called ShowSupplies from a browser is as follows http server port Of ficeFrontEnd servlet ShowSupplies name value You can call this servlet programmatically from another servlet in one of two ways To include another servlet s output use the include method from the RequestDispatcher interface This method calls a servlet by its URI and waits for it to return before continuing to process the interaction The include method can be called multiple times within a given servlet For example RequestDispatcher dispatcher getServletContext getRequestDispatcher servlet ShowSupplies dispatcher include request response To handle interaction control to another servlet use the RequestDispatcher interfaces forward method with the servlet s URI as a parameter This example shows a servlet using forward RequestDispatcher dispatcher getServletContext getRequestDispatcher servlet ShowSupplies dispatcher forward request response Servlet Output By default the System out and System err output of servlets is sent to the server log During startup server log messages are echoed to the System err output On Windows no console is created for the System err output You can change these defaults using the Admin Console For more information see Setting Up Logging for Your Server in Sun Java System Web Server 7 0 Administrators Guide Chapter4 Developing Servlets 55 Caching Servlet Results
201. setting is 0 If there is a form action exists these values will be retrieved from the form elements cssClass Optional The class name used in every HTML tag created in this tag This attribute is particularly useful when the type is checkbox since an HTML table is used for the layout See the sample code for details Usage slws collElem type checkbox cols 2 values 1 0 1 0 cssClass body gt This example creates checkboxes in 2 columns with a default name c with the first and third items selected Fonts and any other HTML styles are defined in the css class body which includes tr body td body and input body collection Tag This tag retrieves the name of the search collections on the server iterates through them and passes each of them to the collectionitem tag Use this tag with collection item tags write your own HTML search collections Attributes Optional A comma delimited string representing the search collections available The tag retrieves all collections available on the server if the attribute is empty Usage lt table border 0 gt lt slws collection gt lt tr gt lt td gt lt input type checkbox name c value lt slws collItem property name gt gt lt slws collItem property display name gt lt td gt lt tr gt lt slws collection gt lt table gt Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications JSP Search Tags The above code will dis
202. sloader Web Application Classloader o There is a seperate instance of this classloader for each web application There is a seperate instance of this classloader per JSP FIGURE9 1 Classloader Runtime Hierarchy This hierarchy is a delegation hierarchy not a Java inheritance hierarchy In the delegation design a classloader delegates classloading to its parent before attempting to load a class itself If the parent classloader cannot load a class the findClass method is called on the classloader subclass In effect a classloader is responsible for loading only the classes not available to the parent The exception is the web application classloader which follows the delegation model in the Servlet specification The web application Classloader looks in the local classloader before delegating to its parent You can make the web application Classloader delegate to its parent Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Classloaders first by setting delegate true in the class Loader element of the sun web xml file For more information see Classloader Element on page 186 The following table describes Sun Java System Web Server 7 0 classloaders TABLE9 3 Sun Java System Web Server 7 0 Classloaders Classloader Bootstrap Description The Bootstrap Classloader loads the JDK classes Only one instance of this classloader exists in the entire server System Common The
203. source principal element TABLEA 27 default resource principalSubelements Element Required Description name Element on page 176 only one Contains the name ofthe principal password Element on only one Contains the password for the principal page 176 Attributes none name Element This element contains data that specifies the name of the principal Subelements none Attributes none password Element This element contains data that specifies the password for the principal Subelements none Attributes none Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Elements in the sun web xml File jndi name Element This element contains data that specifies the absolute jndi name of a URL resource ora resource in the server xml file Note To avoid collisions with names of other enterprise resources in JNDI and to avoid portability problems all names in a Sun Java System Web Server 7 0 application should begin with the string java comp env Subelements none Attributes none Caching Elements For details about response caching as it pertains to servlets see Caching Servlet Results on page 56 and JSP Cache Tags on page 70 Caching elements are as follows cache Element on page 177 cache helper Element on page 179 default helper on page 180 cache mapping Element on page 181 url pattern Element on page 182 cach
204. ssion getId if mySession isNew log println currentDate log println client has not yet joined session mySessionID The following table shows the methods used to examine servlet request properties 86 Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Using Sessions TABLE6 2 HttpServletRequestMethods HttpServletRequest Method getRequestedSessionId isRequestedSessionIdValid isRequestedSessionIdFromCookie isRequestedSessionIdFromURL Description Returns the session ID specified with the request This value might differ from the session ID in the current session if the session ID given by the client is invalid and a new session was created Returns null ifthe request does not have a session associated with it Checks whether the request is associated with a currently valid session Ifthe session requested is not valid it is not returned through the getSession method Returns true ifthe request s session ID provided by the client is a cookie or false otherwise Returns true ifthe request s session ID provided by the client is a part of a URL or false otherwise For example if request isRequestedSessionIdValid if request isRequestedSessionIdFromCookie this session is maintained in a session cookie any other tasks that require a valid session else log an application error Binding Data to a Session You can bind
205. stack trace If the Xrs flag is used the server might dump core and restart when you send the signal to generate the trace The stack trace goes to the system log file or to stderr based on the log attributes in server xml For more information about the server xml file see the Sun Java System Web Server 7 0 Administrators Guide Chapter 10 Debugging Web Applications 147 Using Logging for Debugging Using Logging for Debugging You can use the Sun Java System Web Server 7 0 log files to help debug your applications For general information about logging see the Sun Java System Web Server 7 0 Administrators Guide For information about server xml file see the Sun Java System Web Server 7 0 Administrators Configuration File Reference You can change logging settings in one ofthese ways To Change the Log Settings Access the Admin Console Clickthe View Server Logs tab in the home page Set the log preferences Click Save to apply your changes Using Profiling for Debugging 148 You can use a profiler to perform remote profiling on the Sun Java System Web Server 7 0 to discover choke point in server side performance This section describes how to configure these profilers for use with Sun Java System Web Server 7 0 Using the HPROF Profiler on page 148 Using the Optimizeit Profiler on page 150 Using the HPROF Profiler HPROF is a simple profiler agent shipped with the Java 2 SDK It is a dynamically li
206. t Similar to getNamingContext Deploying a Lifecycle Module Server lifecycle listener classes are visible in the serve applications management area You can add delete update enable and disable listener classes and set their parameters Sun Java System Web Server 7 0 will not support dynamic deployment of startup and shutdown classes Any changes to these classes or their configuration requires server restart TABLE7 1 Elements ofthelifecycle Data type and Configurable element attribute Units Range of values Remarks lifecycle module name String Any Must be specified non null non empty while registering this unique string in lifecycle module lifecycle modules lifecycle module class String Fully qualified Java Must implement the class name LifecycleListener interface lifecycle module enabled Boolean true or false Default is true lifecycle module load order Integer 0 100 Reserved Order of loading the 100 MAXINT lifecycle event listeners in numerical order Choose a load order greater than or equal to 100 to avoid conflicts with internal lifecycle modules lifecycle module is failure fatal Boolean true or false If you want the server to treat exceptions thrown from the listener classes as fatal and prevent continuation Chapter 7 Developing Lifecycle Listeners of normal startup set this element to true 103 Considerations for Lifecycle Modules TABLE7 1 Elements of the li
207. t on page 192 message destination defined within the corresponding Java EE deployment descriptor file jndi name Element on page 177 only one Specifies the jndi name of the associated entity message destination name Element This element specifies the name of a logical message destination defined within the corresponding Java EE deployment descriptor file Subelements none webservice description Element This element specifies a name and optional publish location for a web service Subelements The following table describes subelements for the webservice description element Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Elements in the sun web xml File TABLE A 51 webservice descriptionSubelements Element Required Description webservice description name only one Specifies a unique name for the web Element on page 193 service within a web wsdl publish location Zero or one Specifies the URL ofa directory to Element on page 193 which the web services WSDL is published during deployment Attributes none webservice description name Element This element specifies a unique name for the web service within a web Subelements none Attributes none wsdl publish locationElement This element specifies the URL of a directory to which a web service s WSDL is published during deployment Any required files are published to this directo
208. t uri path index page The following table describes the parts of the URL TABLE9 2 Parts of the URL Part Description vs_urlhost One of the urlhosts values for the virtual server vs_port Optional Only needed if the virtual server uses a non default port uri_path The same path you used to deploy the application This is also the context path index_page Optional The page in the application that end users are meant to access first The following two examples show sample URLs http sun com 80 hello index jsp http sun com hello Chapter9 Deploying Web Applications 137 Deploying Using JSR 88 Deploying Using JSR 88 JSR 88 defines the contracts that enable the tool of multiple providers to configure and deploy applications on any platform product The implementation requires both tools and Java EE platform products You can write your own JSR 88 client to deploy an application to the Sun Java System Web Server 7 0 For more information about JSR 88 see http jcp org en jsr detail id 88 Managing Web Applications 138 Once deployed the application or module exists in the central repository and can be referenced by a number of server instances Initially the server instances or clusters that you deployed as targets reference the application or module To change the server instances and clusters that reference an application or module after it is deployed change an application or module
209. t 2 4 Support Java servlets are server side Java programs that generate content in response to a client request Servlets can be thought of as applets that run on the server side without a user interface Servlets are invoked through URL invocation or by other servlets Sun Java System Web Server 7 0 supports the Java Servlet 2 4 specification Note Java Servlet API version 2 4 is fully backward compatible with versions 2 1 2 2 and 2 3 Therefore all existing servlets continues to work without modification or recompilation To develop servlets use Sun s Java Servlet API For information about using the Java Servlet API see the documentation provided by Sun at http java sun com products servlet index html For the Java Servlet 2 4 specification see http java sun com products servlet download html For information about developing servlets in Sun Java System Web Server see Chapter 4 Developing Servlets JSP 2 0 Support Web Server 7 0 supports the JavaServer Pages JSP 2 0 specification A JSP page is much like an HTML page that can be viewed in a web browser However in addition to HTML tags JSP can include a set of JSP tags and directives intermixed with Java code that extend the ability of the web page designer to incorporate dynamic content in a page These additional features provide functionality such as displaying property values and using simple conditionals JSP pages can access full Java functionality using
210. t index and number of records per page by default The default names for the form index and number of records are searchform si and ns 74 Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications JSP Search Tags Attributes The searchForm tag uses the following attributes Name Specifies the name of the form The default is searchform The name ofa form is the identifier for all other tags Action Optional Specifies the form action Method Optional Specifies the method of submission GET or POST The default is GET elemStart Optional Specifies the name of the hidden Start element If not specified the default si will be used Start Optional An integer indicating the starting index for displaying the search result The default is 1 elemNumShown Optional The name of the nShown element If not specified the default ns is used numShown Optional An integer indicating the number of results to be shown per page The value of the attribute will be retrieved by requesting parameter eLemNumShown The default is 10 Usage lt slws form action results jsp gt slws searchForm This example creates an HTML form tag form name searchform action results jsp method GET gt along with two hidden input boxes A hidden input box for starting the index named si with a value from the si parameter or default 1 A hidden input box for the number of records
211. t of users who are related in some way For example members of the groups astronauts scientists and pilots all fit into the role of SpaceShuttlePassenger In Sun Java System Web Server 7 0 roles correspond to users groups or both used and groups configured in the active realm Security Features Specific to the Web Server In addition to supporting the Java EE 1 4 security model Sun Java System Web Server 7 0 also supports the following features that are specific to the Web Server Single sign on across all Sun Java System Web Server 7 0 applications within a single security domain Programmatic login m The parallel Access Control List ACL based security model in addition to the Java EE Servlet security model Support for secure ACL based Java web applications in addition to native content This section discusses the following Web Server Security Model on page 110 Web Application and URL Authorizations on page 112 Chapter 8 Securing Web Applications 109 Security Features Specific to the Web Server Web Server Security Model Secure applications require a client to be authenticated as a valid application user and have authorization to access servlets and JSPs Applications with a secure web container may enforce the following security processes for clients Authenticate the caller Authorize the caller for access to each servlet JSP based on the applicable access control configuration
212. t the configuration you want to modify and click Edit Configuration Clickthe Java tab Clickthe Authentication tab and scroll down to SOAP Authentication Click Delete To Delete a Message Provider To delete a message security provider through the command line interface type the following command Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Testing Web Services wadm delete soap auth provider port 8989 user admin password file tmp admin passwd config test msgsecurity provider Enabling Message Security Clients Configure the message protection policies of client so that they are equivalent to the message protection policies ofthe server side providers with which they interact A typical stand alone client is illustrated by the bundled sample f romwsdl soap12 Deploying Web Services You deploy a web service endpoint to the Sun Java System Web Server 7 0 just as you would deploy any servlet or application You can use the wadm deploy command to publish the web service The Sun sun web xml deployment descriptor file provides optional web service enhancements using webservice endpoint For more information see Deploying the Server Configuration in Sun Java System Web Server 7 0 Administrators Guide and Java Web Services Developer Pack 2 0 http java sun com webservices docs 2 0 tutorial doc index html Testing Web Services To test Web Services you invoke a web service endpoint deplo
213. ta flow 46 delivering client results 52 54 example of accessing 137 improving performance 61 invoking 54 55 output 55 overriding destroy 48 overriding initialize 48 overriding methods 47 48 overriding service Get Post 49 performance 61 security 50 session managers 83 99 sessions 50 83 storing data 50 threading 50 52 types 46 47 using 45 64 session config 163 164 session cookie 84 session manager 164 165 session managers 83 99 IWS60 91 97 memory 89 90 MMap 97 99 persistent 97 99 session properties 167 168 session properties examining 86 87 session timeout 88 168 sessions about 83 and cookies 84 and security 84 and URL rewriting 84 binding objects to 87 88 creating or accessing 85 86 examining session properties 86 87 ID generator 61 invalidating 88 timeout 88 168 SHTML using 25 single sign on 109 115 116 specifications Java Servlet 25 JSP 25 SSL 114 117 SSL mutual authentication 114 stack trace generating for debugging 147 store properties 166 167 sun web app 157 sun web app 2 4 l dtd 154 156 sun web xml elements 156 195 alphabetical quick referencelist 193 195 cache 177 179 cache helper 179 180 cache helper ref 182 cache mapping 181 182 class loader 186 187 constraint field 185 186 cookie properties 168 169 default helper 180 181 default resource principal 176 http method 184 jndi name 177 jsp config 187 189 key field 184 manager propertie
214. tack size 544288 For more information see Sun Java System Web Server 7 0 Update 1 NSAPI Developer s Guide Use the NSAPI cache improve servlet performance in cases where the obj conf configuration file has many directives To enable the NSAPI cache include the following line in magnus conf Init fn nsapi cache init enable true Check whether the session ID generator that is used for servlet sessions employs cryptographically unique random number generation algorithms This method might present a performance problem on older slow machines For more information see Chapter 6 Session Managers Reduce the number of directories in the classpath Disable dynamic reloading Disable the Java Security Manager Servlet Internationalization Issues This section describes how Sun Java System Web Server 7 0 determines the character encoding for the servlet request and the servlet response For information about encodings see http java sun com j2se 1 5 0 docs guide intl encoding doc html Servlet Request When processing the servlet request the server uses the following order of precedence first to last to determine the character encoding for the request parameters Chapter4 Developing Servlets 61 Migrating Legacy Servlets 1 TheServletRequest setCharacterEncoding method 2 A hidden field in the form if specified using the form hint field attribute ofthe parameter encoding element in the sun web xml file For
215. tags enable you to cache JSP page fragments within the Java engine Each fragment can be cached using different cache criteria For example suppose you have page fragments to view stock quotes and weather information The stock quote fragment can be cached for 10 minutes the weather report fragment for 30 minutes and so on For more information about response caching as it pertains to servlets see Caching Servlet Results on page 56 JSP caching uses the custom tag library support provided by JSP 2 0 JSP caching is implemented by a tag library packaged into the install_dir 1ib jar file which is always on the server classpath The sun web cache tld tag description file is in the install_dir lib tlds directory and can be copied into the WEB INF directory of your web application Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications JSP CacheTags JSP caching is available in three different scopes request session and application The default is application To use a cache with the request scope a web application must specify the com sun appserv web taglibs cache CacheRequestListener in its deployment descriptor as follows listener listener class com sun appserv web taglibs cache CacheRequestListener listener class lt listener gt To use a cache in session scope a web application must specify the com sun appserv web taglibs cache CacheSessionListener in its deployment descriptor
216. ter tete toten tete tete te tete tetas 102 Deploying a Lifecycle Module nte ttti tette b khe tias th festi erede 103 Considerations for Lifecycle Modules ertt tette nein teen tin heresi 104 Sample Lifecycle Configuration tentem dide te ov e dtd 105 Securing Web Applications sess nennen trennen enenentn 107 Supported Security Featur s aie eset niet eii enu lei i died brides 107 Common Security Terminology eritis tnt protesi osk ten ba abate po Rea peser be M pore usd 108 Authentication Java EE Application Role Mapping cunno 0 petet etes beside etes eet Ni Security Features Specific to the Web Server sse tette tentent Web Server Security Model de ftii onere epe e dede e tet ee rien Web Application and URL Authorizations Container SECUTICY s concen adatti ate nad ie ee rode id te iu ce feto dd vate dues ceto Programmatic Security sisse tia E ER EATUR RE AISURIA Declarative Security osea ain ap eae en Atome eI ARE EAT dU User Authentication by Setvlets dote cette ehe etre n tied oed HTTP Basic Authentication sioria un XC RR EO RE R SSL Mutual Authentication FOr BaSed Logit RP Ms User Authentication for Single Sign On essent ttes User Authorization by Servlets inaari deine edet edad et edeiidt and edetedeits Defining Roles etin din ned pied ntuiiongei m AOI ug ted uda rie Ried Dis Defining Servlet Authorization Constraints seen 117
217. the 4 x implementation referred to as legacy servlets was marked as deprecated See Chapter 8 Legacy Servlet and JSP Configuration of the iPlanet Web Server Enterprise Edition Programmer s Guide to Servlets Web Server versions 6 1 and 7 0 no longer support legacy servlets The legacy properties files for the server you want to migrate servlet properties context properties and rules properties are removed during migration Because no one to one mapping is possible for all of the features legacy servlets cannot be migrated automatically This section describes the main features involved in migrating legacy servlets to web applications This section includes the following topics Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Migrating Legacy Servlets JSP file by Extension on page 63 Servlet by Extension of Servlet by Directory on page 63 Registering Servlets on page 63 JSP file by Extension In Sun Java System Web Server 7 0 JSP file by extension works as it did in previous releases Any file name in the document tree with a suffix of jsp is treated as a JSP environment as long as the Java is turned on for the virtual server Servlet by Extension of Servlet by Directory Servlet extension is not supported in Sun Java System Web Server 7 0 You can deploy a web application to respond to a directory but all ofthe servlets must be in the WEB INF classes directory ofthe web appli
218. the JdbcStore class updatePool The number of dedicated connections that perform update operations on the database For higher performance use a precompiled SQL statement for each of these connections Applicable only if the session data store parameter is set to the JdbcStore class deletePool The number of dedicated connections that perform delete operations on the database For higher performance use a precompiled SQL statement for each of these connections Applicable only ifthe session data store parameter is set to the JdbcStore class Note Prior to using JdbcStore you must create the table in which the session information is stored The name of the table is specified by the table parameter and the table s four columns are specified by the accessTimeColumn timeOutColumn sessionIdColumn and valueColumn parameters Note FileStore JdbcStore IWSSessionManager IWSHttpSession IWSHttpSessionManager and SessionDataStore have been deprecated in Sun Java System Web Server 7 0 96 Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Session Managers Source Code for IWS60 The IWS60 session manager creates an IWSHttpSession object for each session The source files for IWSSessionManager java and IWSHttpSession java are in the install dir Vib directory The source code files for IWSSessionManager java and IWSHttpSession java are provided so you can use them as th
219. the WSDL file schema documents web xml sun jaxws xml service endpoint interface and implementation class value types and generated classes if any into a WARfile Deploy the WAR file to a web container Securing Web Services 36 Web Services Security SOAP Message Security WS Security is an international standard for interoperable web services security that was developed in OASIS by a collaboration of all the major providers of web services technology including Sun Microsystems WS Security is a message security mechanism that uses XML Encryption and XML Digital Signature to secure web services messages sent over SOAP The WS Security specification defines the use of various security tokens including X 509 certificates SAML assertions and username and password tokens to authenticate and encrypt SOAP Web Services messages This section also includes the following sections Understanding message security in the Web Server Securing a web service Securing a sample application Configuring the Web Server for message security Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Securing Web Services Admin Console tasks for message security Understanding Message Security in the Web Server The Web Server offers integrated support for the WS Security standard in the server side container This functionality is integrated with Web Services security and enforced by the container of the Web Server on b
220. the corresponding Java EE web xml file resource ref entry to the absolute jndi name Element on page 177 ofa resource Subelements The following table describes subelements for the resource ref element The left column lists the subelement name the middle column indicates the requirement rule and the right column describes what the element does TABLEA 26 resource ref Subelements Element Required Description res ref name Element on only one Specifies the res ref name in the corresponding page 175 Java EE web xml file resource ref entry jndi name Element on only one Specifies the absolute jndi name ofa resource page 177 default resource principal zero or one Specifies the default principal user for the resource Element on page 176 Attributes none res ref name Element This element contains data that specifies the res ref name in the corresponding Java EE web xml file resource ref entry Subelements none Attributes none Appendix A Deployment Descriptor Files 175 Elements in the sun web xml File 176 default resource principalElement This element specifies the default principal user for the resource If this element is used in conjunction with a JMS Connection Factory resource the name and password subelements must be valid entries in Message Queue s broker user repository Subelements The following table describes subelements for the default re
221. the following methods Embedding Java code directly into scriptlets Using server side tags that include Java servlets Servlets are Java classes that must be compiled Servlets can be defined and compiled by a Java programmer who then publishes the interface to the servlet The web page designer can access a precompiled servlet from a JSP page For information about creating JSPages see http java sun com products jsp index html JSTL1 1 The Java Server Pages Standard Tag Library JSTL encapsulates as simple tags the core functionality common to many web applications JSTL has support for common structural Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Technologies and Enhancements in Web Server 7 0 tasks such as iteration and conditionals tags for manipulating XML documents internationalization tags and SQL tags It also provides a framework for integrating existing custom tags with JSTL tags For more information on JSTL 1 1 see http java sun com j2ee 1 4 docs tutorial doc JSTL html wp74644 Java Web Services Developer Pack 2 0 Support Web Services uses a Web Services Description Language WSDL file to describe the service and a registry service to register and lookup the services The Simple Object Access Protocol SOAP binding is the standard interoperable binding for accessing Web Services Based on Java Web Services Developer Pack Java WSDP Sun Java System Web Server 7 0 supports i
222. the jvm element in servlet xml This instance wide setting affects all virtual servers and all web applications Servlet sessionmgr This element translates to the session manager element in the sun web xml Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications gt CHAPTER 5 Developing JavaServer Pages This chapter describes how to use JavaServer Pages JSP page templates in a Sun Java System Web Server 7 0 application This chapter has the following sections Introducing JSPs on page 65 Creating JSPs on page 66 Compiling JSPs Using the Command Line Compiler on page 67 Debugging JSPs on page 70 JSP Tag Libraries and Standard Portable Tags on page 70 JSP Cache Tags on page 70 JSP Search Tags on page 74 JSP Internationalization Issues on page 82 Introducing JSPs JSPs are browser pages in HTML or XML These pages contain Java code which enables them to perform complex processing conditionalize output and communicate with other application objects JSPs in Sun Java System Web Server 7 0 are based on the JSP 2 0 specification Ina Sun Java System Web Server 7 0 application you can call a JSP from a servlet to handle the user interaction output Because JSPs have the same application environment access as any other application component you can use a JSP as an interaction destination JSPs are made up of JSP elements and template data
223. ties zero or one Specifies session manager properties Element on page 165 store properties Element zero or one Specifies session persistence storage properties on page 166 Attribute The following table describes the persistence type attribute for the session manager element The left column lists the attribute name the middle column indicates the default value and the right column describes what the attribute does Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Elements in the sun web xml File TABLEA 10 session manager Attribute Attribute persistence type manager properties Element Default Value memory Description Optional Specifies the session persistence mechanism Allowed values are memory file s1ws60 and mmap Setting the value of persistence type to memory is equivalent to using Sun Java System Web Server 7 0 s IWS60 without any store Setting the value of persistence type to file is equivalent to using Sun Java System Web Server 7 0 s IWS60 with FileStore This element specifies session manager properties Subelement The following table describes the property subelement for the manager properties element TABLEA 11 manager properties Subelements Element Required Description property Element on page 160 zero or more Specifies a property which has a name and a value Attributes none Prop
224. tion and URL Authorizations Secure web applications may have authentication and authorization properties The web container supports three types of authentication basic certificate and form based The core ACLs support basic certificate and digest For more information about ACL configuration see the Sun Java System Web Server 7 0 Administrators Guide When a browser requests an application URL that requires authentication the web container collects the user authentication information for example user name and password and passes it to the security service for authentication For Java EE web applications Sun Java System Web Server 7 0 checks the application s web xml file for information on which parts ofthe application are protected and which roles are authorized to access It also checks sun web xml to see whether the currently authenticated user belongs to one ofthe required roles either directly through user mapping or indirectly through group mapping Container Security 112 The component containers are responsible for providing Java EE application security Two security forms are provided by the container programmatic security and declarative security Programmatic Security In programmatic security a servlet uses method calls to the security API as specified by the Java EE security model to make business logic decisions based on the caller or remote user s security role Programmatic security should only be used wh
225. value gt lt constraint field gt lt cache mapping gt lt cache mapping gt Chapter 4 Developing Servlets 59 Caching Servlet Results 60 servlet name InfoServlet servlet name lt cache helper ref gt myHelper lt cache helper ref gt lt cache mapping gt lt cache gt For more information about the sun web xml caching settings see Caching Elements on page 177 CacheKeyGenerator Interface The built in default CacheHelper implementation enables web applications to customize the key generation An application component in a servlet or JSP can set up a custom CacheKeyGenerator implementation as an attribute in the ServletContext The name of the context attribute is configurable as the value of the cacheKeyGeneratorAttrName property in the default helper element ofthe sun web xml deployment descriptor For more information see default helper on page 180 The CacheKeyGenerator interface contains the following information package com sun appserv web cache import javax servlet ServletContext import javax servlet http HttpServletRequest CacheKeyGenerator a helper interface to generate the key that is used to cache this request Name of the ServletContext attribute implementing the CacheKeyGenerator is configurable via a property of the default helper in sun web xml lt default helper gt property name cacheKeyGeneratorAttrName value com acme web MyCacheK
226. web generated code application reload interval 0 Specifies the frequency in seconds at which JSP files are checked for modifications Setting this value to 0 checks JSPs for modifications on every request Setting this value to 1 disables checks for JSP modifications and JSP recompilation initial capacity 32 Specifies the initial size of the hash table of compiled JSP classes see the following example The following example illustrates the use ofthe initial capacity property described in the table above The example shows how you would configure a value of 1024 lt jsp config gt property name initial capacity valuez 1024 gt lt jsp config gt Internationalization Elements The internationalization elements are as follows parameter encoding Element on page 190 locale charset info Element on page 190 Appendix A Deployment Descriptor Files 189 Elements in the sun web xml File 190 locale charset map Element on page 191 parameter encoding Element This element specifies a hidden field or default character set that determines the character encoding the web container uses to decode parameters for request getParameter calls when the character set is not set in the request s Content Type For encodings you can use see http java sun com j2se 1 4 2 docs guide intl encoding doc html Attributes The following table describes attributes for the parameter encoding eleme
227. which the JSP is located In another example the same hello jsp is precompiled using the p option and is precompiled as jspc webapp SOURCE d test1 test2 test3 p appl app2 app3 The generated servlet is located in Chapter 5 Developing JavaServer Pages 69 Debugging JSPs testl test2 test3 app1 app2 app3 JSP myjsps hello jsp java and defined inside package app1 app2 app3 JSP myjsps Note that the package specified with the p option app1 app2 app3 overrides the standard org apache jsp but does not affect the package derived from the directory in which the JSP is located Also note that the d option does not affect on the generated package name Other JSP Configuration Parameters For information about the various JSP configuration parameters you can use see the section jsp config Element on page 187 The JSP compiler uses the default values for parameters that are not included in the file Debugging JSPs When you use Sun Java Studio Enterprise 8 1 to debug JSPs you can set breakpoints in a JSP For information about setting up debugging in Sun Java Studio Enterprise 8 1 see Using Developer Tools for Debugging on page 147 JSP Tag Libraries and Standard Portable Tags Sun Java System Web Server 7 0 supports tag libraries and standard portable tags For more information about tag libraries see the JSP 2 0 specification at http java sun com products jsp download html JSP Cache Tags 70 JSP cache
228. which identifies the client to the server on each successive interaction If a client does not support or allow cookies the server rewrites the URLs where the session ID appears in the URLs from that client You can configure whether and how sessions use cookies For more information on related elements in the sun web xml file see session properties Element on page 167 and cookie properties Element on page 168 Sessions and URL Rewriting You can also configure whether sessions use URL rewriting For more information see the sun web xml element session properties Element on page 167 Sessions and Security The Sun Java System Web Server 7 0 security model is based on an authenticated user session Once a session has been created the application user is authenticated if authentication is used and is logged into the session Additionally you can specify that a session cookie is only passed on an HTTPS secured connection so the session can only remain active on a secure channel For more information about security see Chapter 8 Securing Web Applications Sun Java System Web Server 7 0 Developer s Guide to Java Web Applications Using Sessions Using Sessions To use a session first create a session using the HttpServletRequest method getSession Once the session is established examine and set its properties using the provided methods If desired set the session to time out after being inactive for a defined ti
229. y memory explicitly to change its default parameters To do so edit the sun web xml file for the web application as in the following example Note that persistence type must be set to memory lt sun web app gt lt session config gt session manager persistence type memory gt lt manager properties gt lt property name reapIntervalSeconds value 20 gt lt manager properties gt lt session manager gt lt session config gt sun web app For more information about the sun web xml file see Chapter 9 Deploying Web Applications Manager Properties for Memory The following table describes manager properties properties for the memory based session manager Chapter6 Session Managers 89 Session Managers TABLE6 4 manager properties for memory Property Name Default Value Description reapIntervalSeconds 60 Specifies the number of seconds between checks for expired sessions Setting this value lower than the frequency at which session data changes is recommended For example this value should be as low as possible 1 second for a hit counter servlet on a frequently accessed web site or you could lose the last few hits each time you restart the server maxSessions 1 Specifies the maximum number of active sessions or 1 the default for no limit sessionFilename SESSIONS Specifies the absolute or relative path name of the file in which the session state is preserved between appl
230. yed on a web service client A web service client is a Java program that makes a request to the service through a stub that acts as a proxy for the remote service This stub is generated by the wsimport tool based on the WSDL file ofthe service v Tolnvoke aWeb Service Client 1 WSDL of the deployed web service from URL http host port context root endpoint wsdl 2 Callwsimport to generate the client side artifacts using the deployed Web Services s WSDL 3 Implement the client to invoke the web service Clients can run a deployed web service by accessing its service endpoint address URL which has the following format http host port context root servlet mapping url pattern The context root is defined in the web xml file The servlet mapping url pattern is defined in the web xml file Chapter 3 Web Services Overview 43 Web Services Samples In the following example the context root is my ws and the servlet mapping url pattern is simple You can view the WSDL file of the deployed service in a browser by adding WSDL to the end ofthe URL for example http localhost 8080 my ws simple WSDL Web Services Samples 44 The f romwsdl soap1 application features a simple web service that is implemented by a Java Servlet endpoint The service endpoint interface defines a single operation addNumbers which takes two positive integers and returns an integer that is the sum ofthe two input integers The f romwsdl soa
Download Pdf Manuals
Related Search
Related Contents
USER`S MANUAL Intellinet 19" Server Cabinet 27U Lettore MP3 Impermeabile Lenco XEMIO Tecumseh AGA9538ZXTHM Technical Data Sheet Casio 5095 Watch User Manual Poulan 530088412 User's Manual Guía del Usuario de IDT Connect Latin America Design, Implementation and Control of a Humanoid Robot for Benq IL650 touch screen monitor GT-3 User Manual final 8th July 2013 revision 1 Copyright © All rights reserved.
Failed to retrieve file