servere java

Upload: tony-montana

Post on 05-Apr-2018

217 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/31/2019 Servere Java

    1/93

    ervlet and JSP Tutorial: Table of Contents

    ONTENTS

    tro & TOC

    ervlet Overview

    etup

    rst Servlets

    andling FORM Data

    equest Headers

    GI Variables

    esponse Status Codes

    esponse Headers

    ookies

    ession Tracking

    avaServer Pages (JSP)

    ervlet/JSP Book. Sun Press book that grew from this tutorial.

    ervlet/JSP Training Courses Public or on-site courses.

    ttp://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-TOC.html2007/04/22 08:55:36 .

    http://www.coreservlets.com/http://courses.coreservlets.com/http://courses.coreservlets.com/http://www.coreservlets.com/http://www.coreservlets.com/
  • 7/31/2019 Servere Java

    2/93

    ava Servlet Tutorial

    Servlets and JavaServer Pages(JSP) 1.0: A Tutorial

    NOTE: This tutorial is now out of date. Please see the following sites for updated and advancedinformation.

    q Intermediate servlet and JSP tutorial

    q Advanced servlet and JSP tutorial

    q Jakarta Struts tutorial

    q Tutorial on JSF (JavaServer Faces) and Apache MyFaces

    q Apache Tomcat Setup and Introductory Tutorial

    q Ajax tutorial

    q Tutorials on Java 5 and Java 6 Programming

    Table of Cont ent s

    s Extended Table of Contents (This page)s Core Servlets and JavaServer Pages. Sun

    Microsystems Press book on servlets 2.2 and JSP1.1. This online tutorial served as a very early outlinefor the book, but of course the book covers manymore topics and includes much more detail. Also see

    this new book (More Servlets and JSP) on servlets2.3 and JSP 1.2.

    s Overview of Servlets and JSPq What is a Java servlet?q What advantage does a Java servlet have over

    a traditional CGI program?q What is JSP?q What are the advantages of JSP?

    s Getting Started: Installation and Setupq New:Guide to installing and configuring

    Apache Tomcat 4 as a standalone servlet andJSP engine. The tutorial you are reading waswritten long before Tomcat 4.0 was available,but if you are starting now, I stronglyrecommend you use Tomcat or anotherengine compatible with servlets 2.2 or later.The above link gives a quick summary ofhow to set up and use the latest version ofApache Tomcat.

    q Obtaining and Installing the Servlet and JSP

    s Accessing the Standard CGI Variablesq The CGI Variables, Their Meaning, and th

    Servlet Equivalentq Example: Making a Table of All CGI

    Variabless Generating the Response: HTTP Status Codes

    q Overview: Status Codes and Messagesq Setting Status Codes from Servletsq HTTP 1.1 Status Codes and Their Meaninq Example: A Search Engine Front End

    s Generating the Response: HTTP Response Headeq Overviewq Common Response Headers and Their

    Meaningq

    Example: Starting a Long-RunningCalculation, Showing Partial Results, andPeriodically Updating Display with New D

    s Handling Cookiesq Intro: How Cookies Can Be Used (and

    Abused)q The Servlet Cookie APIq Some Cookie Utilitiesq Example: A Customized Search Engine

    Interfaces Session Tracking

    ttp://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-Intro.html (1 of 3)2007/04/22 08:55:38 .

    http://courses.coreservlets.com/Course-Materials/csajsp2.htmlhttp://courses.coreservlets.com/Course-Materials/msajsp.htmlhttp://courses.coreservlets.com/Course-Materials/struts.htmlhttp://www.coreservlets.com/JSF-Tutorial/http://www.coreservlets.com/Apache-Tomcat-Tutorial/http://courses.coreservlets.com/Course-Materials/ajax.htmlhttp://courses.coreservlets.com/Course-Materials/java5.htmlhttp://www.coreservlets.com/http://www.moreservlets.com/http://www.moreservlets.com/http://www.moreservlets.com/http://www.moreservlets.com/Using-Tomcat-4.htmlhttp://www.moreservlets.com/Using-Tomcat-4.htmlhttp://www.moreservlets.com/Using-Tomcat-4.htmlhttp://www.moreservlets.com/Using-Tomcat-4.htmlhttp://www.moreservlets.com/Using-Tomcat-4.htmlhttp://www.moreservlets.com/Using-Tomcat-4.htmlhttp://www.moreservlets.com/http://www.coreservlets.com/http://courses.coreservlets.com/Course-Materials/java5.htmlhttp://courses.coreservlets.com/Course-Materials/ajax.htmlhttp://www.coreservlets.com/Apache-Tomcat-Tutorial/http://www.coreservlets.com/JSF-Tutorial/http://courses.coreservlets.com/Course-Materials/struts.htmlhttp://courses.coreservlets.com/Course-Materials/msajsp.htmlhttp://courses.coreservlets.com/Course-Materials/csajsp2.html
  • 7/31/2019 Servere Java

    3/93

    ava Servlet Tutorial

    Classesq Getting a Servlet-Capable Web Server or

    Servlet Engines First Servlets

    q Basic Servlet Structureq A Simple Servlet Generating Plain Textq Compiling and Invoking the Servletq A Simple Servlet Generating HTMLq

    Some Simple HTML Utilities for Servletss Processing the Request: Form Dataq Introduction (Format, URL-encoding, GET,

    POST)q Example: Reading Specific Parametersq Example: Making Table of All Parameters

    s Processing the Request: HTTP Request Headersq Common Request Headers and Their

    Meaningq Reading Headers from Servletsq Example: Making Table of All Headers

    q Overview of Session Trackingq The Servlet Session Tracking APIq Example

    s JavaServer Pages (JSP)q JSP Overviewq JSP Syntax Summaryq Template Text (Static HTML)q JSP Scripting Elements: Expressions,

    Scriptlets, and Declarationsq JSP Directivesq Example using JSP Scripting Elements an

    Directivesq Predefined Variablesq JSP Actionsq JSP Comments and Character Escaping

    Conventionsq Creating Custom JSP Tag Libraries

    Sitemap for coreservlets.com

    ttp://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-Intro.html (2 of 3)2007/04/22 08:55:38 .

    bout the Instructorourse Reviews

    ntermediate Servlet & JSP Trainingoursesdvanced Servlet & JSP TrainingoursesCWCD Training Coursesakarta Struts Training CoursesavaServer Faces (JSF) & Apache

    MyFaces Training Coursesjax Training Courses

    ava 5 & 6 Programming Trainingoursesustomized On-Site Training Coursesublic Training Course Schedule

    Apache Tomcat TutorialIntermediate Servlets & JSP TutorialAdvanced Servlets & JSP TutorialSCWCD (Sun Certified WebComponent Developer) ExamJakarta Struts TutorialJavaServer Faces (JSF) & ApacheMyFaces TutorialJava 5 & 6 Programming TutorialsTutorials in ChineseTutorials in Japanese

    Specifications & DocumentationServersIDEsJava-Related JobsJavaServer Faces (JSF)BooksWeb Hosting ProvidersJava Programming Resources

    Tra in ing

    Tu to r i a l s

    Progr am m ing Resour ces

    http://courses.coreservlets.com/about-instructor.htmlhttp://courses.coreservlets.com/student-reviews.htmlhttp://courses.coreservlets.com/servlet+jsp-training.htmlhttp://courses.coreservlets.com/servlet+jsp-training.htmlhttp://courses.coreservlets.com/advanced-servlet+jsp-training.htmlhttp://courses.coreservlets.com/advanced-servlet+jsp-training.htmlhttp://courses.coreservlets.com/scwcd-training.htmlhttp://courses.coreservlets.com/struts-training.htmlhttp://courses.coreservlets.com/jsf-training.htmlhttp://courses.coreservlets.com/jsf-training.htmlhttp://courses.coreservlets.com/ajax-training.htmlhttp://courses.coreservlets.com/java-training.htmlhttp://courses.coreservlets.com/java-training.htmlhttp://courses.coreservlets.com/http://courses.coreservlets.com/public-courses/http://www.coreservlets.com/Apache-Tomcat-Tutorial/http://courses.coreservlets.com/Course-Materials/csajsp2.htmlhttp://courses.coreservlets.com/Course-Materials/msajsp.htmlhttp://courses.coreservlets.com/Course-Materials/scwcd.htmlhttp://courses.coreservlets.com/Course-Materials/scwcd.htmlhttp://courses.coreservlets.com/Course-Materials/struts.htmlhttp://www.coreservlets.com/JSF-Tutorial/http://www.coreservlets.com/JSF-Tutorial/http://courses.coreservlets.com/Course-Materials/java5.htmlhttp://courses.coreservlets.com/Course-Materials/chinese.htmlhttp://courses.coreservlets.com/Course-Materials/japanese.htmlhttp://resources.coreservlets.com/jsp-docs.htmlhttp://resources.coreservlets.com/jsp-servers.htmlhttp://resources.coreservlets.com/jsp-ides.htmlhttp://resources.coreservlets.com/j2ee-jobs.htmlhttp://resources.coreservlets.com/jsf.htmlhttp://resources.coreservlets.com/jsp+servlet-books.htmlhttp://resources.coreservlets.com/jsp-hosting.htmlhttp://www.apl.jhu.edu/~hall/java/http://www.apl.jhu.edu/~hall/java/http://resources.coreservlets.com/jsp-hosting.htmlhttp://resources.coreservlets.com/jsp+servlet-books.htmlhttp://resources.coreservlets.com/jsf.htmlhttp://resources.coreservlets.com/j2ee-jobs.htmlhttp://resources.coreservlets.com/jsp-ides.htmlhttp://resources.coreservlets.com/jsp-servers.htmlhttp://resources.coreservlets.com/jsp-docs.htmlhttp://courses.coreservlets.com/Course-Materials/japanese.htmlhttp://courses.coreservlets.com/Course-Materials/chinese.htmlhttp://courses.coreservlets.com/Course-Materials/java5.htmlhttp://www.coreservlets.com/JSF-Tutorial/http://www.coreservlets.com/JSF-Tutorial/http://courses.coreservlets.com/Course-Materials/struts.htmlhttp://courses.coreservlets.com/Course-Materials/scwcd.htmlhttp://courses.coreservlets.com/Course-Materials/scwcd.htmlhttp://courses.coreservlets.com/Course-Materials/msajsp.htmlhttp://courses.coreservlets.com/Course-Materials/csajsp2.htmlhttp://www.coreservlets.com/Apache-Tomcat-Tutorial/http://courses.coreservlets.com/public-courses/http://courses.coreservlets.com/http://courses.coreservlets.com/java-training.htmlhttp://courses.coreservlets.com/java-training.htmlhttp://courses.coreservlets.com/ajax-training.htmlhttp://courses.coreservlets.com/jsf-training.htmlhttp://courses.coreservlets.com/jsf-training.htmlhttp://courses.coreservlets.com/struts-training.htmlhttp://courses.coreservlets.com/scwcd-training.htmlhttp://courses.coreservlets.com/advanced-servlet+jsp-training.htmlhttp://courses.coreservlets.com/advanced-servlet+jsp-training.htmlhttp://courses.coreservlets.com/servlet+jsp-training.htmlhttp://courses.coreservlets.com/servlet+jsp-training.htmlhttp://courses.coreservlets.com/student-reviews.htmlhttp://courses.coreservlets.com/about-instructor.html
  • 7/31/2019 Servere Java

    4/93

    ava Servlet Tutorial

    ttp://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-Intro.html (3 of 3)2007/04/22 08:55:38 .

    ore Servlets & JSP 2nd Ed.More Servlets & JSP

    ore Web Programmingore Servlets & JSP 1st Ed.ore Servlets & JSP E-Book

    More Servlets & JSP E-Book

    Our consulting services We are hiring!

    Books Consu l t ing Jobs

    http://volume1.coreservlets.com/http://www.moreservlets.com/http://www.corewebprogramming.com/http://www.coreservlets.com/first-edition.htmlhttp://pdf.coreservlets.com/http://pdf.moreservlets.com/http://consulting.coreservlets.com/http://jobs.coreservlets.com/http://jobs.coreservlets.com/http://consulting.coreservlets.com/http://pdf.moreservlets.com/http://pdf.coreservlets.com/http://www.coreservlets.com/first-edition.htmlhttp://www.corewebprogramming.com/http://www.moreservlets.com/http://volume1.coreservlets.com/
  • 7/31/2019 Servere Java

    5/93

    ervlets and JSP: An Overview

    Servlets and JSP: An Overview

    NOTE: This tutorial is now out of date. Please see the following sites for updated and advanced

    information.

    q Intermediate servlet and JSP tutorial

    q Advanced servlet and JSP tutorial

    q Jakarta Struts tutorial

    q Tutorial on JSF (JavaServer Faces) and Apache MyFaces

    q Apache Tomcat Setup and Introductory Tutorial

    q Ajax tutorial

    q Tutorials on Java 5 and Java 6 Programming

    1. What are Java Servlets?2. What are the Advantage of Servlets Over "Traditional"

    CGI?3. What is JSP?

    4. What are the Advantages of JSP?5. Servlet and JSP Tutorial: Top6. Servlet and JSP Training Courses On-site atyo

    company or at public venues.

    What are Java Servlets?

    Servlets are Java technology's answer to CGI programming. They are programs that run on a Web server and build Wpages. Building Web pages on the fly is useful (and commonly done) for a number of reasons:

    q The Web page is based on data submitted by the user. For example the results pages from search engines generated this way, and programs that process orders for e-commerce sites do this as well.q The data changes frequently. For example, a weather-report or news headlines page might build the page

    dynamically, perhaps returning a previously built page if it is still up to date.q The Web page uses information from corporate databases or other such sources. For example, you would

    this for making a Web page at an on-line store that lists current prices and number of items in stock.

    What are the Advantage of Servlets Over "Traditional" CGI?

    Java servlets are more efficient, easier to use, more powerful, more portable, and cheaper than traditional CGI and th

    many alternative CGI-like technologies. (More importantly, servlet developers get paid more than Perl programmersq Efficient. With traditional CGI, a new process is started for each HTTP request. If the CGI program does a rela

    fast operation, the overhead of starting the process can dominate the execution time. With servlets, the Java ViMachine stays up, and each request is handled by a lightweight Java thread, not a heavyweight operating syst

    process. Similarly, in traditional CGI, if there areNsimultaneous request to the same CGI program, then the cfor the CGI program is loaded into memory N times. With servlets, however, there areNthreads but only a sincopy of the servlet class. Servlets also have more alternatives than do regular CGI programs for optimizations

    as caching previous computations, keeping database connections open, and the like.q Convenient. Hey, you already know Java. Why learn Perl too? Besides the convenience of being able to use

    familiar language, servlets have an extensive infrastructure for automatically parsing and decoding HTML fodata, reading and setting HTTP headers, handling cookies, tracking sessions, and many other such utilities

    ttp://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-Overview.html (1 of 3)2007/04/22 08:55:39 .

    http://courses.coreservlets.com/Course-Materials/csajsp2.htmlhttp://courses.coreservlets.com/Course-Materials/msajsp.htmlhttp://courses.coreservlets.com/Course-Materials/struts.htmlhttp://www.coreservlets.com/JSF-Tutorial/http://www.coreservlets.com/Apache-Tomcat-Tutorial/http://courses.coreservlets.com/Course-Materials/ajax.htmlhttp://courses.coreservlets.com/Course-Materials/java5.htmlhttp://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/index.htmlhttp://courses.coreservlets.com/http://courses.coreservlets.com/http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/index.htmlhttp://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://courses.coreservlets.com/Course-Materials/java5.htmlhttp://courses.coreservlets.com/Course-Materials/ajax.htmlhttp://www.coreservlets.com/Apache-Tomcat-Tutorial/http://www.coreservlets.com/JSF-Tutorial/http://courses.coreservlets.com/Course-Materials/struts.htmlhttp://courses.coreservlets.com/Course-Materials/msajsp.htmlhttp://courses.coreservlets.com/Course-Materials/csajsp2.html
  • 7/31/2019 Servere Java

    6/93

    ervlets and JSP: An Overview

    q Powerful. Java servlets let you easily do several things that are difficult or impossible with regular CGI. For othing, servlets can talk directly to the Web server (regular CGI programs can't). This simplifies operations that to look up images and other data stored in standard places. Servlets can also share data among each other, mak

    useful things like database connection pools easy to implement. They can also maintain information from requerequest, simplifying things like session tracking and caching of previous computations.

    q Portable. Servlets are written in Java and follow a well-standardized API. Consequently, servlets written for, sPlanet Enterprise Server can run virtually unchanged on Apache, Microsoft IIS, or WebStar. Servlets are suppo

    directly or via a plugin on almost every major Web server.q

    Inexpensive. There are a number of free or very inexpensive Web servers available that are good for "personalor low-volume Web sites. However, with the major exception of Apache, which is free, most commercial-quaWeb servers are relatively expensive. Nevertheless, once you have a Web server, no matter the cost of that ser

    adding servlet support to it (if it doesn't come preconfigured to support servlets) is generally free or cheap

    What is JSP?

    va Server Pages (JSP) is a technology that lets you mix regular, static HTML with dynamically-generated HTML. MWeb pages that are built by CGI programs are mostly static, with the dynamic part limited to a few small locations. Bmost CGI variations, including servlets, make you generate the entire page via your program, even though most of it

    always the same. JSP lets you create the two parts separately. Here's an example:

    Welcome to Our Store

    Welcome to Our Store

    Welcome,

    To access your account settings, click

    here.

    Regular HTML for all the rest of the on-line store's Web page.

    What are the Advantages of JSP?

    q vs. Active Server Pages (ASP). ASP is a similar technology from Microsoft. The advantages of JSP are twofFirst, the dynamic part is written in Java, not Visual Basic or other MS-specific language, so it is more powerfu

    easier to use. Second, it is portable to other operating systems and non-Microsoft Web servers.q vs. Pure Servlets. JSP doesn't give you anything that you couldn't in principle do with a servlet. But it is mo

    convenient to write (and to modify!) regular HTML than to have a zillion println statements that generate thHTML. Plus, by separating the look from the content you can put different people on different tasks: your Web

    design experts can build the HTML, leaving places for your servlet programmers to insert the dynamic conteq vs. Server-Side Includes (SSI). SSI is a widely-supported technology for including externally-defined pieces i

    static Web page. JSP is better because it lets you use servlets instead of a separate program to generate that dynpart. Besides, SSI is really only intended for simple inclusions, not for "real" programs that use form data, ma

    database connections, and the like.q vs. JavaScript. JavaScript can generate HTML dynamically on the client. This is a useful capability, but on

    handles situations where the dynamic information is based on the client's environment. With the exception o

    ttp://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-Overview.html (2 of 3)2007/04/22 08:55:39 .

  • 7/31/2019 Servere Java

    7/93

    ervlets and JSP: An Overview

    cookies, HTTP and form submission data is not available to JavaScript. And, since it runs on the client, JavaSccan't access server-side resources like databases, catalogs, pricing information, and the like.

    q vs. Static HTML. Regular HTML, of course, cannot contain dynamic information. JSP is so easy and conventhat it is quite feasible to augment HTML pages that only benefit marginally by the insertion of small amount

    dynamic data. Previously, the cost of using dynamic data would preclude its use in all but the most valuablinstances.

    Sitemap for coreservlets.com

    ttp://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-Overview.html (3 of 3)2007/04/22 08:55:39 .

    bout the Instructorourse Reviews

    ntermediate Servlet & JSP Trainingoursesdvanced Servlet & JSP TrainingoursesCWCD Training Coursesakarta Struts Training CoursesavaServer Faces (JSF) & Apache

    MyFaces Training Coursesjax Training Courses

    ava 5 & 6 Programming Trainingoursesustomized On-Site Training Coursesublic Training Course Schedule

    Apache Tomcat TutorialIntermediate Servlets & JSP TutorialAdvanced Servlets & JSP TutorialSCWCD (Sun Certified WebComponent Developer) ExamJakarta Struts TutorialJavaServer Faces (JSF) & ApacheMyFaces TutorialJava 5 & 6 Programming TutorialsTutorials in ChineseTutorials in Japanese

    Specifications & DocumentationServersIDEsJava-Related Jobs

    JavaServer Faces (JSF)BooksWeb Hosting ProvidersJava Programming Resources

    ore Servlets & JSP 2nd Ed.More Servlets & JSP

    ore Web Programmingore Servlets & JSP 1st Ed.ore Servlets & JSP E-Book

    More Servlets & JSP E-Book

    Our consulting services We are hiring!

    Tra in ing

    Tu to r i a l s

    Progr am m ing Resour ces

    Books Consu l t ing Jobs

    http://courses.coreservlets.com/about-instructor.htmlhttp://courses.coreservlets.com/student-reviews.htmlhttp://courses.coreservlets.com/servlet+jsp-training.htmlhttp://courses.coreservlets.com/servlet+jsp-training.htmlhttp://courses.coreservlets.com/advanced-servlet+jsp-training.htmlhttp://courses.coreservlets.com/advanced-servlet+jsp-training.htmlhttp://courses.coreservlets.com/scwcd-training.htmlhttp://courses.coreservlets.com/struts-training.htmlhttp://courses.coreservlets.com/jsf-training.htmlhttp://courses.coreservlets.com/jsf-training.htmlhttp://courses.coreservlets.com/ajax-training.htmlhttp://courses.coreservlets.com/java-training.htmlhttp://courses.coreservlets.com/java-training.htmlhttp://courses.coreservlets.com/http://courses.coreservlets.com/public-courses/http://www.coreservlets.com/Apache-Tomcat-Tutorial/http://courses.coreservlets.com/Course-Materials/csajsp2.htmlhttp://courses.coreservlets.com/Course-Materials/msajsp.htmlhttp://courses.coreservlets.com/Course-Materials/scwcd.htmlhttp://courses.coreservlets.com/Course-Materials/scwcd.htmlhttp://courses.coreservlets.com/Course-Materials/struts.htmlhttp://www.coreservlets.com/JSF-Tutorial/http://www.coreservlets.com/JSF-Tutorial/http://courses.coreservlets.com/Course-Materials/java5.htmlhttp://courses.coreservlets.com/Course-Materials/chinese.htmlhttp://courses.coreservlets.com/Course-Materials/japanese.htmlhttp://resources.coreservlets.com/jsp-docs.htmlhttp://resources.coreservlets.com/jsp-servers.htmlhttp://resources.coreservlets.com/jsp-ides.htmlhttp://resources.coreservlets.com/j2ee-jobs.htmlhttp://resources.coreservlets.com/jsf.htmlhttp://resources.coreservlets.com/jsp+servlet-books.htmlhttp://resources.coreservlets.com/jsp-hosting.htmlhttp://www.apl.jhu.edu/~hall/java/http://volume1.coreservlets.com/http://www.moreservlets.com/http://www.corewebprogramming.com/http://www.coreservlets.com/first-edition.htmlhttp://pdf.coreservlets.com/http://pdf.moreservlets.com/http://consulting.coreservlets.com/http://jobs.coreservlets.com/http://jobs.coreservlets.com/http://consulting.coreservlets.com/http://pdf.moreservlets.com/http://pdf.coreservlets.com/http://www.coreservlets.com/first-edition.htmlhttp://www.corewebprogramming.com/http://www.moreservlets.com/http://volume1.coreservlets.com/http://www.apl.jhu.edu/~hall/java/http://resources.coreservlets.com/jsp-hosting.htmlhttp://resources.coreservlets.com/jsp+servlet-books.htmlhttp://resources.coreservlets.com/jsf.htmlhttp://resources.coreservlets.com/j2ee-jobs.htmlhttp://resources.coreservlets.com/jsp-ides.htmlhttp://resources.coreservlets.com/jsp-servers.htmlhttp://resources.coreservlets.com/jsp-docs.htmlhttp://courses.coreservlets.com/Course-Materials/japanese.htmlhttp://courses.coreservlets.com/Course-Materials/chinese.htmlhttp://courses.coreservlets.com/Course-Materials/java5.htmlhttp://www.coreservlets.com/JSF-Tutorial/http://www.coreservlets.com/JSF-Tutorial/http://courses.coreservlets.com/Course-Materials/struts.htmlhttp://courses.coreservlets.com/Course-Materials/scwcd.htmlhttp://courses.coreservlets.com/Course-Materials/scwcd.htmlhttp://courses.coreservlets.com/Course-Materials/msajsp.htmlhttp://courses.coreservlets.com/Course-Materials/csajsp2.htmlhttp://www.coreservlets.com/Apache-Tomcat-Tutorial/http://courses.coreservlets.com/public-courses/http://courses.coreservlets.com/http://courses.coreservlets.com/java-training.htmlhttp://courses.coreservlets.com/java-training.htmlhttp://courses.coreservlets.com/ajax-training.htmlhttp://courses.coreservlets.com/jsf-training.htmlhttp://courses.coreservlets.com/jsf-training.htmlhttp://courses.coreservlets.com/struts-training.htmlhttp://courses.coreservlets.com/scwcd-training.htmlhttp://courses.coreservlets.com/advanced-servlet+jsp-training.htmlhttp://courses.coreservlets.com/advanced-servlet+jsp-training.htmlhttp://courses.coreservlets.com/servlet+jsp-training.htmlhttp://courses.coreservlets.com/servlet+jsp-training.htmlhttp://courses.coreservlets.com/student-reviews.htmlhttp://courses.coreservlets.com/about-instructor.html
  • 7/31/2019 Servere Java

    8/93

    ervlet and JSP Tutorial: Software and Server Setup

    Getting Started: Software andServer Setup

    NOTE: This tutorial is now out of date. Please see the following sites for updated and advanced

    information.

    q Intermediate servlet and JSP tutorial

    q Advanced servlet and JSP tutorial

    q Jakarta Struts tutorial

    q Tutorial on JSF (JavaServer Faces) and Apache MyFaces

    q Apache Tomcat Setup and Introductory Tutorial

    q Ajax tutorial

    q Tutorials on Java 5 and Java 6 Programming

    1. Obtain and Install the Servlet and JSP Development Kits2. Install a Servlet-Capable Web Server

    3. Servlet and JSP Tutorial: Top4. Servlet and JSP Training Courses On-site a

    yourcompany or at public venues.

    Note: this tutorial was written long before Apache Tomcat 4 or 5 were available. I strongly recommend you u

    Tomcat 4 or 5 instead of following the old directions listed on this page. Click here for a guide to configuring a

    using Tomcat as a servlet and JSP engine. Note that the older servlet and JSP examples of this tutorial still wo

    with the newer Tomcat server.

    Obtain and Install the Servlet and JSP Development Kits

    ur first step is to download software that implements the Java Servlet 2.1 or 2.2 and Java Server Pages 1.0 or 1.1ecifications. You can get a free version from Sun, known as the JavaServer Web Development Kit (JSWDK), at httpa.sun.com/products/servlet/.

    xt, you need to tell javac where to find the servlet and JSP classes when you compile a servlet file. The JSWDKtallation instructions explain this, but it basically amounts to putting servlet.jar and jsp.jar (which come

    JSWDK) on your CLASSPATH. If you've never dealt with the CLASSPATH before, it is the variable that specifiesere Java looks for classes. If it is unspecified, Java looks in the current directory and the standard system libraries. Ifit yourself, you need to be sure to include ".", signifying the current directory. Here's a quick summary of how to sea couple of different platforms:

    nix (C Shell)

    tenv CLASSPATH .:servlet_dir/servlet.jar:servlet_dir/jsp.jar

    ttp://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-Setup.html (1 of 3)2007/04/22 08:55:40 .

    http://courses.coreservlets.com/Course-Materials/csajsp2.htmlhttp://courses.coreservlets.com/Course-Materials/msajsp.htmlhttp://courses.coreservlets.com/Course-Materials/struts.htmlhttp://www.coreservlets.com/JSF-Tutorial/http://www.coreservlets.com/Apache-Tomcat-Tutorial/http://courses.coreservlets.com/Course-Materials/ajax.htmlhttp://courses.coreservlets.com/Course-Materials/java5.htmlhttp://-/?-http://-/?-http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/index.htmlhttp://courses.coreservlets.com/http://www.coreservlets.com/Apache-Tomcat-Tutorial/http://java.sun.com/products/servlet/http://java.sun.com/products/servlet/http://java.sun.com/products/servlet/http://java.sun.com/products/servlet/http://www.coreservlets.com/Apache-Tomcat-Tutorial/http://courses.coreservlets.com/http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/index.htmlhttp://-/?-http://-/?-http://courses.coreservlets.com/Course-Materials/java5.htmlhttp://courses.coreservlets.com/Course-Materials/ajax.htmlhttp://www.coreservlets.com/Apache-Tomcat-Tutorial/http://www.coreservlets.com/JSF-Tutorial/http://courses.coreservlets.com/Course-Materials/struts.htmlhttp://courses.coreservlets.com/Course-Materials/msajsp.htmlhttp://courses.coreservlets.com/Course-Materials/csajsp2.html
  • 7/31/2019 Servere Java

    9/93

    ervlet and JSP Tutorial: Software and Server Setup

    d ":$CLASSPATH" to the end of the setenv line if your CLASSPATH is already set, and you want to add moret replace it. Note that you use colons to separate directories, while you use semicolons on Windows. To make this sermanent, you'd typically put this statement in your .cshrc file.

    indows 95/98/NT

    t CLASSPATH=.;servlet_dir/servlet.jar;servlet_dir/jsp.jar

    d ";%CLASSPATH%" to the end of the above line if your CLASSPATH is already set. Note that you use semicolonparate directories, while you use colons on Unix. To make this setting permanent in Windows 95/98 you'd typically ps statement in your autoexec.bat file. On Windows NT, you'd go to the Start menu, select Settings, select Contnel, select System, select Environment, then enter the variable and value.

    nally, as you'll see in the next section, you probably want to put your servlets into packages to avoid name conflicts wvlets other people write for the same Web or application server. In that case, you may find it convenient to add the tel directory of your package hierarchy to the CLASSPATH as well. See the section on first servlets for details.

    Install a Servlet-Capable Web Server

    ur next step is to obtain and install a Web server that supports Java servlets, or to install a servlet package in yoursting Web server. If you are using an up-to-date Web or application server, there is a good chance that it already has

    erything you need. Check your server documentation or see the latest list of servers that supports servlets at http://javn.com/products/servlet/industry.html. Although youll eventually want to deploy in a commercial-quality server, whst learning it is useful to have a free system that you can install on your desktop machine for development and testingrposes. Here are some of the most popular options:

    q Apache Tomcat.Tomcat is the official reference implementation of the servlet 2.2 and JSP 1.1 specifications. It can be used as asmall stand-alone server for testing servlets and JSP pages, or can be integrated into the Apache Web server. As

    early 2000, it was the only server to support the servlet 2.2 or JSP 1.1 specifications. However, many other servhave announced upcoming support. Tomcat, like Apache itself, is free. However, also like Apache (which is verfast, highly reliable, but a bit hard to configure and install), Tomcat requires significantly more effort to set up tdo the commercial servlet engines. For details, see http://jakarta.apache.org/.

    q JavaServer Web Development Kit (JSWDK).The JSWDK is the official reference implementation of the servlet 2.1 and JSP 1.0 specifications. It is used as asmall stand-alone server for testing servlets and JSP pages before they are deployed to a full Web server thatsupports these technologies. It is free and reliable, but takes quite a bit of effort to install and configure. For detasee http://java.sun.com/products/servlet/download.html.

    q Allaire JRun.

    JRun is a servlet and JSP engine that can be plugged into Netscape Enterprise or FastTrack servers, IIS, MicrosoPersonal Web Server, older versions of Apache, OReillys WebSite, or StarNine WebSTAR. A limited versionsupports up to five simultaneous connections is available for free; the commercial version removes this restrictiand adds capabilities like a remote administration console. For details, see http://www.allaire.com/products/jrun

    q New Atlantas ServletExec.ServletExec is a fast servlet and JSP engine that can be plugged into most popular Web servers for Solaris,Windows, MacOS, HP-UX and Linux. You can download and use it for free, but many of the advanced featuresadministration utilities are disabled until you purchase a license. New Atlanta also provides a free servlet debugthat works with many of the popular Java IDEs. For details, see http://newatlanta.com/.

    q Gefion's LiteWebServer (LWS). LWS is a small free Web server that supports servlets version 2.2 and JSP 1.1.

    ttp://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-Setup.html (2 of 3)2007/04/22 08:55:40 .

    http://java.sun.com/products/servlet/industry.htmlhttp://java.sun.com/products/servlet/industry.htmlhttp://jakarta.apache.org/downloads/binindex.htmlhttp://jakarta.apache.org/http://java.sun.com/products/servlet/download.htmlhttp://java.sun.com/products/servlet/download.htmlhttp://www.allaire.com/products/jrun/http://www.allaire.com/products/jrun/http://newatlanta.com/http://newatlanta.com/http://www.gefionsoftware.com/LiteWebServer/http://www.gefionsoftware.com/LiteWebServer/http://newatlanta.com/http://newatlanta.com/http://www.allaire.com/products/jrun/http://www.allaire.com/products/jrun/http://java.sun.com/products/servlet/download.htmlhttp://java.sun.com/products/servlet/download.htmlhttp://jakarta.apache.org/http://jakarta.apache.org/downloads/binindex.htmlhttp://java.sun.com/products/servlet/industry.htmlhttp://java.sun.com/products/servlet/industry.html
  • 7/31/2019 Servere Java

    10/93

    ervlet and JSP Tutorial: Software and Server Setup

    They also have a free plugin called WAICoolRunner that adds servlet 2.2 and JSP 1.1 support to Netscape FastTand Enterprise servers. They also sell a number of custom servlet and JSP components in a package calledInstantOnline. For details, see http://www.gefionsoftware.com/.

    q Suns Java Web Server.This server is written entirely in Java and was one of the first Web servers to fully support the servlet 2.1 and JS1.0 specifications. Although it is no longer under active development because Sun is concentrating on the NetscPlanet server, it is still a popular choice for learning servlets and JSP. For a free trial version, see http://www.sucom/software/jwebserver/try/. For a free non-expiring version for teaching purposes at academic institutions, se

    http://freeware.thesphere.com/.

    Sitemap for coreservlets.com

    ttp://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-Setup.html (3 of 3)2007/04/22 08:55:40 .

    bout the Instructorourse Reviews

    ntermediate Servlet & JSP Trainingourses

    dvanced Servlet & JSP TrainingoursesCWCD Training Coursesakarta Struts Training CoursesavaServer Faces (JSF) & Apache

    MyFaces Training Coursesjax Training Courses

    ava 5 & 6 Programming Trainingoursesustomized On-Site Training Coursesublic Training Course Schedule

    Apache Tomcat TutorialIntermediate Servlets & JSP TutorialAdvanced Servlets & JSP TutorialSCWCD (Sun Certified WebComponent Developer) ExamJakarta Struts TutorialJavaServer Faces (JSF) & ApacheMyFaces TutorialJava 5 & 6 Programming TutorialsTutorials in ChineseTutorials in Japanese

    Specifications & DocumentationServersIDEsJava-Related JobsJavaServer Faces (JSF)BooksWeb Hosting ProvidersJava Programming Resources

    ore Servlets & JSP 2nd Ed.More Servlets & JSP

    ore Web Programmingore Servlets & JSP 1st Ed.ore Servlets & JSP E-Book

    More Servlets & JSP E-Book

    Our consulting services We are hiring!

    Tra in ing

    Tu to r i a l s

    Progr am m ing Resour ces

    Books Consu l t ing Jobs

    http://www.gefionsoftware.com/WAICoolRunner/http://www.gefionsoftware.com/InstantOnline/http://www.gefionsoftware.com/http://www.sun.com/software/jwebserver/http://www.sun.com/software/jwebserver/try/http://www.sun.com/software/jwebserver/try/http://freeware.thesphere.com/http://courses.coreservlets.com/about-instructor.htmlhttp://courses.coreservlets.com/student-reviews.htmlhttp://courses.coreservlets.com/servlet+jsp-training.htmlhttp://courses.coreservlets.com/servlet+jsp-training.htmlhttp://courses.coreservlets.com/advanced-servlet+jsp-training.htmlhttp://courses.coreservlets.com/advanced-servlet+jsp-training.htmlhttp://courses.coreservlets.com/scwcd-training.htmlhttp://courses.coreservlets.com/struts-training.htmlhttp://courses.coreservlets.com/jsf-training.htmlhttp://courses.coreservlets.com/jsf-training.htmlhttp://courses.coreservlets.com/ajax-training.htmlhttp://courses.coreservlets.com/java-training.htmlhttp://courses.coreservlets.com/java-training.htmlhttp://courses.coreservlets.com/http://courses.coreservlets.com/public-courses/http://www.coreservlets.com/Apache-Tomcat-Tutorial/http://courses.coreservlets.com/Course-Materials/csajsp2.htmlhttp://courses.coreservlets.com/Course-Materials/msajsp.htmlhttp://courses.coreservlets.com/Course-Materials/scwcd.htmlhttp://courses.coreservlets.com/Course-Materials/scwcd.htmlhttp://courses.coreservlets.com/Course-Materials/struts.htmlhttp://www.coreservlets.com/JSF-Tutorial/http://www.coreservlets.com/JSF-Tutorial/http://courses.coreservlets.com/Course-Materials/java5.htmlhttp://courses.coreservlets.com/Course-Materials/chinese.htmlhttp://courses.coreservlets.com/Course-Materials/japanese.htmlhttp://resources.coreservlets.com/jsp-docs.htmlhttp://resources.coreservlets.com/jsp-servers.htmlhttp://resources.coreservlets.com/jsp-ides.htmlhttp://resources.coreservlets.com/j2ee-jobs.htmlhttp://resources.coreservlets.com/jsf.htmlhttp://resources.coreservlets.com/jsp+servlet-books.htmlhttp://resources.coreservlets.com/jsp-hosting.htmlhttp://www.apl.jhu.edu/~hall/java/http://volume1.coreservlets.com/http://www.moreservlets.com/http://www.corewebprogramming.com/http://www.coreservlets.com/first-edition.htmlhttp://pdf.coreservlets.com/http://pdf.moreservlets.com/http://consulting.coreservlets.com/http://jobs.coreservlets.com/http://jobs.coreservlets.com/http://consulting.coreservlets.com/http://pdf.moreservlets.com/http://pdf.coreservlets.com/http://www.coreservlets.com/first-edition.htmlhttp://www.corewebprogramming.com/http://www.moreservlets.com/http://volume1.coreservlets.com/http://www.apl.jhu.edu/~hall/java/http://resources.coreservlets.com/jsp-hosting.htmlhttp://resources.coreservlets.com/jsp+servlet-books.htmlhttp://resources.coreservlets.com/jsf.htmlhttp://resources.coreservlets.com/j2ee-jobs.htmlhttp://resources.coreservlets.com/jsp-ides.htmlhttp://resources.coreservlets.com/jsp-servers.htmlhttp://resources.coreservlets.com/jsp-docs.htmlhttp://courses.coreservlets.com/Course-Materials/japanese.htmlhttp://courses.coreservlets.com/Course-Materials/chinese.htmlhttp://courses.coreservlets.com/Course-Materials/java5.htmlhttp://www.coreservlets.com/JSF-Tutorial/http://www.coreservlets.com/JSF-Tutorial/http://courses.coreservlets.com/Course-Materials/struts.htmlhttp://courses.coreservlets.com/Course-Materials/scwcd.htmlhttp://courses.coreservlets.com/Course-Materials/scwcd.htmlhttp://courses.coreservlets.com/Course-Materials/msajsp.htmlhttp://courses.coreservlets.com/Course-Materials/csajsp2.htmlhttp://www.coreservlets.com/Apache-Tomcat-Tutorial/http://courses.coreservlets.com/public-courses/http://courses.coreservlets.com/http://courses.coreservlets.com/java-training.htmlhttp://courses.coreservlets.com/java-training.htmlhttp://courses.coreservlets.com/ajax-training.htmlhttp://courses.coreservlets.com/jsf-training.htmlhttp://courses.coreservlets.com/jsf-training.htmlhttp://courses.coreservlets.com/struts-training.htmlhttp://courses.coreservlets.com/scwcd-training.htmlhttp://courses.coreservlets.com/advanced-servlet+jsp-training.htmlhttp://courses.coreservlets.com/advanced-servlet+jsp-training.htmlhttp://courses.coreservlets.com/servlet+jsp-training.htmlhttp://courses.coreservlets.com/servlet+jsp-training.htmlhttp://courses.coreservlets.com/student-reviews.htmlhttp://courses.coreservlets.com/about-instructor.htmlhttp://freeware.thesphere.com/http://www.sun.com/software/jwebserver/try/http://www.sun.com/software/jwebserver/try/http://www.sun.com/software/jwebserver/http://www.gefionsoftware.com/http://www.gefionsoftware.com/InstantOnline/http://www.gefionsoftware.com/WAICoolRunner/
  • 7/31/2019 Servere Java

    11/93

    ervlet Tutorial: First Servlets

    First Servlets

    NOTE: This tutorial is now out of date. Please see the following sites for updated and advanced

    information.

    q Intermediate servlet and JSP tutorial

    q Advanced servlet and JSP tutorial

    q Jakarta Struts tutorial

    q Tutorial on JSF (JavaServer Faces) and Apache MyFaces

    q Apache Tomcat Setup and Introductory Tutorial

    q Ajax tutorial

    q Tutorials on Java 5 and Java 6 Programming

    1. Basic Servlet Structure

    2. A Simple Servlet Generating Plain Text3. A Servlet that Generates HTML

    4. Simple HTML-Building Utilities5. Servlet and JSP Tutorial: Top6. Servlet and JSP Training Courses On-site atyourcompany o

    public venues.

    Basic Servlet Structure

    re's the outline of a basic servlet that handles GET requests. GET requests, for those unfamiliar with HTTP, are requde by browsers when the user types in a URL on the address line, follows a link from a Web page, or makes an HTM

    m that does not specify a METHOD. Servlets can also very easily handle POST requests, which are generated whenmeone creates an HTML form that specifies METHOD="POST". We'll discuss that in later sections.

    port java.io.*;

    port javax.servlet.*;

    port javax.servlet.http.*;

    blic class SomeServlet extends HttpServlet {

    public void doGet(HttpServletRequest request,

    HttpServletResponse response)

    throws ServletException, IOException {

    // Use "request" to read incoming HTTP headers (e.g. cookies)

    // and HTML form data (e.g. data the user entered and submitted)

    // Use "response" to specify the HTTP response line and headers

    // (e.g. specifying the content type, setting cookies).

    PrintWriter out = response.getWriter();

    // Use "out" to send content to browser

    ttp://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-First-Servlets.html (1 of 7)2007/04/22 08:55:41 .

    http://courses.coreservlets.com/Course-Materials/csajsp2.htmlhttp://courses.coreservlets.com/Course-Materials/msajsp.htmlhttp://courses.coreservlets.com/Course-Materials/struts.htmlhttp://www.coreservlets.com/JSF-Tutorial/http://www.coreservlets.com/Apache-Tomcat-Tutorial/http://courses.coreservlets.com/Course-Materials/ajax.htmlhttp://courses.coreservlets.com/Course-Materials/java5.htmlhttp://-/?-http://-/?-http://-/?-http://-/?-http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/index.htmlhttp://courses.coreservlets.com/http://courses.coreservlets.com/http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/index.htmlhttp://-/?-http://-/?-http://-/?-http://-/?-http://courses.coreservlets.com/Course-Materials/java5.htmlhttp://courses.coreservlets.com/Course-Materials/ajax.htmlhttp://www.coreservlets.com/Apache-Tomcat-Tutorial/http://www.coreservlets.com/JSF-Tutorial/http://courses.coreservlets.com/Course-Materials/struts.htmlhttp://courses.coreservlets.com/Course-Materials/msajsp.htmlhttp://courses.coreservlets.com/Course-Materials/csajsp2.html
  • 7/31/2019 Servere Java

    12/93

    ervlet Tutorial: First Servlets

    }

    ownload template source code -- click with the right mouse on the link or hold down SHIFT while clicking on the li

    be a servlet, a class should extend HttpServlet and override doGet or doPost (or both), depending on whether th

    a is being sent by GET or by POST. These methods take two arguments: an HttpServletRequest and antpServletResponse. The HttpServletRequest has methods that let you find out about incoming information sFORM data, HTTP request headers, and the like. The HttpServletResponse has methods that lets you specif

    TTP response line (200, 404, etc.), response headers (Content-Type, Set-Cookie, etc.), and, most importantls you obtain a PrintWriter used to send output back to the client. For simple servlets, most of the effort is spent inintln statements that generate the desired page. Note that doGet and doPost throw two exceptions, so you are

    quired to include them in the declaration. Also note that you have to import classes in java.io (for PrintWrite.), javax.servlet (for HttpServlet, etc.), and javax.servlet.http (for HttpServletRequesd HttpServletResponse). Finally, note that doGet and doPost are called by the service method, andmetimes you may want to override service directly, e.g. for a servlet that handles both GET and POST request.

    A Simple Servlet Generating Plain Textre is a simple servlet that just generates plain text. The following section will show the more usual case where HTMnerated.

    1 HelloWorld.java

    u can also download the source or try it on-line.

    ckage hall;

    port java.io.*;

    port javax.servlet.*;

    port javax.servlet.http.*;

    blic class HelloWorld extends HttpServlet {

    public void doGet(HttpServletRequest request,

    HttpServletResponse response)

    throws ServletException, IOException {

    PrintWriter out = response.getWriter();

    out.println("Hello World");}

    2 Compiling and Installing the Servlet

    te that the specific details for installing servlets vary from Web server to Web server. Please refer to your Web servecumentation for definitive directions. The on-line examples are running on Java Web Server (JWS) 2.0, where servleexpected to be in a directory called servlets in the JWS installation hierarchy. However, I placed this servlet in

    parate package (hall) to avoid conflicts with other servlets on this server; you'll want to do the same if you are usin

    ttp://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-First-Servlets.html (2 of 7)2007/04/22 08:55:41 .

    http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/hall/SomeServlet.javahttp://java.sun.com/products/servlet/2.2/javadoc/javax/servlet/http/HttpServlet.htmlhttp://java.sun.com/products/servlet/2.2/javadoc/javax/servlet/http/HttpServletRequest.htmlhttp://java.sun.com/products/servlet/2.2/javadoc/javax/servlet/http/HttpServletResponse.htmlhttp://java.sun.com/products/jdk/1.2/docs/api/java/io/PrintWriter.htmlhttp://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/hall/HelloWorld.javahttp://webdev.apl.jhu.edu/servlet/hall.HelloWorldhttp://webdev.apl.jhu.edu/servlet/hall.HelloWorldhttp://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/hall/HelloWorld.javahttp://java.sun.com/products/jdk/1.2/docs/api/java/io/PrintWriter.htmlhttp://java.sun.com/products/servlet/2.2/javadoc/javax/servlet/http/HttpServletResponse.htmlhttp://java.sun.com/products/servlet/2.2/javadoc/javax/servlet/http/HttpServletRequest.htmlhttp://java.sun.com/products/servlet/2.2/javadoc/javax/servlet/http/HttpServlet.htmlhttp://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/hall/SomeServlet.java
  • 7/31/2019 Servere Java

    13/93

    ervlet Tutorial: First Servlets

    eb server that is used by other people and doesn't have a good infrastructure for "virtual servers" to prevent these conomatically. Thus, HelloWorld.java actually goes in a subdirectory called hall in the servlets directoryte that setup on most other servers is similar, and the servlet and JSP examples in the tutorial have also been tested u

    EA WebLogic and IBM WebSphere 3.0. WebSphere has an excellent mechanism for virtual servers, and it is notcessary to use packages solely to prevent name conflicts with other users.

    you've never used packages before, there are two main ways to compile classes that are in packages.

    e way is to set your CLASSPATH to point to the directory above the one actually containing your servlets. You canm compile normally from within the directory. For example, if your base directory is C:\JavaWebServerervlets and your package name (and thus subdirectory name) is hall, and you were on Windows, you'd do:DOS> set CLASSPATH=C:\JavaWebServer\servlets;%CLASSPATH%

    DOS> cd C:\JavaWebServer\servlets\hall

    DOS> javac YourServlet.java

    e first part, setting the CLASSPATH, you probably want to do permanently, rather than each time you start a new Dndow. On Windows 95/98 you'd typically put the "set CLASSPATH=..." statement in your autoexec.bat filmewhere after the line that set the CLASSPATH to point to servlet.jar and jsp.jar. On Windows NT, youthe Start menu, select Settings, select Control Panel, select System, select Environment, then enter the variable and v

    te also that if your package were of the form name1.name2.name3 rather than simply name1 as here, you'd stve the CLASSPATH point to the top-level directory of your package hierarchy (the one containing name1).

    second way to compile classes that are in packages is to go to the directory above the one containing your servlets, an do "javac directory\YourServlet.java" (Windows; note the backslash) or "javac directoryurServlet.java" (Unix; note the forward slash). For example, suppose again that your base directory is C:avaWebServer\servlets and your package name (and thus subdirectory name) is hall, and you were onndows. In that case, you'd do the following:DOS> cd C:\JavaWebServer\servlets

    DOS> javac hall\YourServlet.java

    te that, on Windows, most JDK 1.1 versions ofjavac require a backslash, not a forward slash, after the directoryme. This is fixed in JDK 1.2, but since many Web servers are configured to use JDK 1.1, many servlet authors stick K 1.1 for portability.

    nally, another advanced option is to keep the source code in a location distinct from the .class files, and use javac'soption to install them in the location the Web server expects.

    3 Running the Servlet

    th the Java Web Server, servlets are placed in the servlets directory within the main JWS installation directory,invoked via http://host/servlet/ServletName . Note that the directory is servlets, plural, while

    RL refers to servlet, singular. Since this example was placed in the hall package, it would be invoked viatp://host/servlet/hall.HelloWorld . Other Web servers may have slightly different conventions onere to install servlets and how to invoke them. Most servers also let you define aliases for servlets, so that a servlet cinvoked via http://host/any-path/any-file.html . The process for doing this is completely server-

    ecific; check your server's documentation for details.

    ttp://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-First-Servlets.html (3 of 7)2007/04/22 08:55:41 .

  • 7/31/2019 Servere Java

    14/93

    ervlet Tutorial: First Servlets

    A Servlet that Generates HTML

    ost servlets generate HTML, not plain text as in the previous example. To do that, you need two additional steps: tellowser that you're sending back HTML, and modify the println statements to build a legal Web page. The first stene by setting the Content-Type response header. In general, headers can be set via the setHeader method oftpServletResponse, but setting the content type is such a common task that there is also a specialtContentType method just for this purpose. Note that you need to set response headers before actually returninthe content via the PrintWriter. Here's an example:

    1 HelloWWW.java

    u can also download the source or try it on-line.

    ckage hall;

    port java.io.*;

    port javax.servlet.*;port javax.servlet.http.*;

    blic class HelloWWW extends HttpServlet {

    public void doGet(HttpServletRequest request,

    HttpServletResponse response)

    throws ServletException, IOException {

    response.setContentType("text/html");

    PrintWriter out = response.getWriter();

    out.println("\n" +

    "\n" +

    "Hello WWW\n" +

    "\n" +

    "Hello WWW\n" +

    "");

    }

    2 HelloWWW Result

    ttp://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-First-Servlets.html (4 of 7)2007/04/22 08:55:41 .

    http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/hall/HelloWWW.javahttp://webdev.apl.jhu.edu/servlet/hall.HelloWWWhttp://webdev.apl.jhu.edu/servlet/hall.HelloWWWhttp://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/hall/HelloWWW.java
  • 7/31/2019 Servere Java

    15/93

    ervlet Tutorial: First Servlets

    Simple HTML-Building Utilities

    s a bit cumbersome to generate HTML with println statements. The real solution is to use Java Server Pages (JSich is discussed later in this tutorial. However, for standard servlets, there are two parts of the Web page (DOCTYPE

    AD) that are unlikely to change and thus could benefit from being incorporated into a simple utility file.

    e DOCTYPE line is technically required by the HTML spec, and although most major browsers ignore it, it is very uen sending pages to formal HTML validators. These validators compare the HTML syntax of pages against the form

    TML specification, and use the DOCTYPE line to determine which version of HTML to check against. Their use is vghly recommended both for static HTML pages and for pages generated via servlets, so the use ofDOCTYPE is wellrth the effort, especially if it can be easily incorporated into a servlet utilities class.

    many Web pages, the HEAD line contains nothing but the TITLE, although advanced developers may want to incluTA tags and style sheets. But for the simple case, I'll create a method that takes a title as input and returns theCTYPE, HEAD, and TITLE entries as output. Here's the code:

    1 ServletUtilities.java (Download source code)

    ckage hall;

    blic class ServletUtilities {

    public static final String DOCTYPE =

    "";

    public static String headWithTitle(String title) {

    return(DOCTYPE + "\n" +

    "\n" +

    "" + title + "\n");

    }

    // Other utilities will be shown later...

    2 HelloWWW2.java (Download source code)

    ttp://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-First-Servlets.html (5 of 7)2007/04/22 08:55:41 .

    http://www.apl.jhu.edu/~hall/WWW/#Validatorshttp://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/hall/ServletUtilities.javahttp://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/hall/HelloWWW2.javahttp://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/hall/HelloWWW2.javahttp://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/hall/ServletUtilities.javahttp://www.apl.jhu.edu/~hall/WWW/#Validators
  • 7/31/2019 Servere Java

    16/93

    ervlet Tutorial: First Servlets

    re's a rewrite of the HelloWWW class that uses this.

    ckage hall;

    port java.io.*;

    port javax.servlet.*;

    port javax.servlet.http.*;

    blic class HelloWWW2 extends HttpServlet {

    public void doGet(HttpServletRequest request,

    HttpServletResponse response)

    throws ServletException, IOException {

    response.setContentType("text/html");

    PrintWriter out = response.getWriter();

    out.println(ServletUtilities.headWithTitle("Hello WWW") +

    "\n" +

    "Hello WWW\n" +

    "");

    }

    Sitemap for coreservlets.com

    ttp://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-First-Servlets.html (6 of 7)2007/04/22 08:55:41 .

    bout the Instructorourse Reviews

    ntermediate Servlet & JSP Trainingoursesdvanced Servlet & JSP TrainingoursesCWCD Training Coursesakarta Struts Training CoursesavaServer Faces (JSF) & Apache

    MyFaces Training Coursesjax Training Courses

    ava 5 & 6 Programming Trainingoursesustomized On-Site Training Coursesublic Training Course Schedule

    Apache Tomcat TutorialIntermediate Servlets & JSP TutorialAdvanced Servlets & JSP TutorialSCWCD (Sun Certified WebComponent Developer) ExamJakarta Struts TutorialJavaServer Faces (JSF) & ApacheMyFaces TutorialJava 5 & 6 Programming TutorialsTutorials in ChineseTutorials in Japanese

    Specifications & DocumentationServersIDEsJava-Related JobsJavaServer Faces (JSF)BooksWeb Hosting ProvidersJava Programming Resources

    Tra in ing

    Tu to r i a l s

    Progr am m ing Resour ces

    http://courses.coreservlets.com/about-instructor.htmlhttp://courses.coreservlets.com/student-reviews.htmlhttp://courses.coreservlets.com/servlet+jsp-training.htmlhttp://courses.coreservlets.com/servlet+jsp-training.htmlhttp://courses.coreservlets.com/advanced-servlet+jsp-training.htmlhttp://courses.coreservlets.com/advanced-servlet+jsp-training.htmlhttp://courses.coreservlets.com/scwcd-training.htmlhttp://courses.coreservlets.com/struts-training.htmlhttp://courses.coreservlets.com/jsf-training.htmlhttp://courses.coreservlets.com/jsf-training.htmlhttp://courses.coreservlets.com/ajax-training.htmlhttp://courses.coreservlets.com/java-training.htmlhttp://courses.coreservlets.com/java-training.htmlhttp://courses.coreservlets.com/http://courses.coreservlets.com/public-courses/http://www.coreservlets.com/Apache-Tomcat-Tutorial/http://courses.coreservlets.com/Course-Materials/csajsp2.htmlhttp://courses.coreservlets.com/Course-Materials/msajsp.htmlhttp://courses.coreservlets.com/Course-Materials/scwcd.htmlhttp://courses.coreservlets.com/Course-Materials/scwcd.htmlhttp://courses.coreservlets.com/Course-Materials/struts.htmlhttp://www.coreservlets.com/JSF-Tutorial/http://www.coreservlets.com/JSF-Tutorial/http://courses.coreservlets.com/Course-Materials/java5.htmlhttp://courses.coreservlets.com/Course-Materials/chinese.htmlhttp://courses.coreservlets.com/Course-Materials/japanese.htmlhttp://resources.coreservlets.com/jsp-docs.htmlhttp://resources.coreservlets.com/jsp-servers.htmlhttp://resources.coreservlets.com/jsp-ides.htmlhttp://resources.coreservlets.com/j2ee-jobs.htmlhttp://resources.coreservlets.com/jsf.htmlhttp://resources.coreservlets.com/jsp+servlet-books.htmlhttp://resources.coreservlets.com/jsp-hosting.htmlhttp://www.apl.jhu.edu/~hall/java/http://www.apl.jhu.edu/~hall/java/http://resources.coreservlets.com/jsp-hosting.htmlhttp://resources.coreservlets.com/jsp+servlet-books.htmlhttp://resources.coreservlets.com/jsf.htmlhttp://resources.coreservlets.com/j2ee-jobs.htmlhttp://resources.coreservlets.com/jsp-ides.htmlhttp://resources.coreservlets.com/jsp-servers.htmlhttp://resources.coreservlets.com/jsp-docs.htmlhttp://courses.coreservlets.com/Course-Materials/japanese.htmlhttp://courses.coreservlets.com/Course-Materials/chinese.htmlhttp://courses.coreservlets.com/Course-Materials/java5.htmlhttp://www.coreservlets.com/JSF-Tutorial/http://www.coreservlets.com/JSF-Tutorial/http://courses.coreservlets.com/Course-Materials/struts.htmlhttp://courses.coreservlets.com/Course-Materials/scwcd.htmlhttp://courses.coreservlets.com/Course-Materials/scwcd.htmlhttp://courses.coreservlets.com/Course-Materials/msajsp.htmlhttp://courses.coreservlets.com/Course-Materials/csajsp2.htmlhttp://www.coreservlets.com/Apache-Tomcat-Tutorial/http://courses.coreservlets.com/public-courses/http://courses.coreservlets.com/http://courses.coreservlets.com/java-training.htmlhttp://courses.coreservlets.com/java-training.htmlhttp://courses.coreservlets.com/ajax-training.htmlhttp://courses.coreservlets.com/jsf-training.htmlhttp://courses.coreservlets.com/jsf-training.htmlhttp://courses.coreservlets.com/struts-training.htmlhttp://courses.coreservlets.com/scwcd-training.htmlhttp://courses.coreservlets.com/advanced-servlet+jsp-training.htmlhttp://courses.coreservlets.com/advanced-servlet+jsp-training.htmlhttp://courses.coreservlets.com/servlet+jsp-training.htmlhttp://courses.coreservlets.com/servlet+jsp-training.htmlhttp://courses.coreservlets.com/student-reviews.htmlhttp://courses.coreservlets.com/about-instructor.html
  • 7/31/2019 Servere Java

    17/93

    ervlet Tutorial: First Servlets

    ttp://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-First-Servlets.html (7 of 7)2007/04/22 08:55:41 .

    ore Servlets & JSP 2nd Ed.More Servlets & JSP

    ore Web Programmingore Servlets & JSP 1st Ed.ore Servlets & JSP E-Book

    More Servlets & JSP E-Book

    Our consulting services We are hiring!

    Books Consu l t ing Jobs

    http://volume1.coreservlets.com/http://www.moreservlets.com/http://www.corewebprogramming.com/http://www.coreservlets.com/first-edition.htmlhttp://pdf.coreservlets.com/http://pdf.moreservlets.com/http://consulting.coreservlets.com/http://jobs.coreservlets.com/http://jobs.coreservlets.com/http://consulting.coreservlets.com/http://pdf.moreservlets.com/http://pdf.coreservlets.com/http://www.coreservlets.com/first-edition.htmlhttp://www.corewebprogramming.com/http://www.moreservlets.com/http://volume1.coreservlets.com/
  • 7/31/2019 Servere Java

    18/93

    ervlet Tutorial: Handling Form Data

    Handling Form Data

    NOTE: This tutorial is now out of date. Please see the following sites for updated and advanced

    information.

    q Intermediate servlet and JSP tutorial

    q Advanced servlet and JSP tutorial

    q Jakarta Struts tutorial

    q Tutorial on JSF (JavaServer Faces) and Apache MyFaces

    q Apache Tomcat Setup and Introductory Tutorial

    q Ajax tutorial

    q Tutorials on Java 5 and Java 6 Programming

    1. Introduction2. Example: Reading Three Parameters

    3. Example: Listing All Form Data4. Servlet and JSP Tutorial: Top5. Servlet and JSP Training Courses On-site atyourcompany or at public venues.

    Introduction

    ou've ever used a Web search engine, visited an on-line bookstore, tracked stocks on-line, or asked a Web-based site for quotes on planets, you've probably seen funny looking URLs like http://host/path?user=Marty+Hall&origin=bwi&dest=laxt after the question mark (i.e. user=Marty+Hall&origin=bwi&dest=lax) is known asform data, and is the most commonet data from a Web page to a server-side program. It can be attached to the end of the URL after a question mark (as above), for GETuests, or sent to the server on a separate line, for POST requests.

    racting the needed information from this form data is traditionally one of the most tedious parts of CGI programming. First of all, youead the data one way for GET requests (in traditional CGI, this is usually via the QUERY_STRING environment variable), and anothePOST requests (usually by reading the standard input). Second, you have to chop the pairs at the ampersands, then separate the param

    mes (left of the equals signs) from the parameter values (right of the equals signs). Third, you have to URL-decode the values. Alphanuracters get sent unchanged, but spaces get converted to plus signs and other characters get converted to %XX whereXX is the ASCII

    O Latin-1) value of the character, in hex. For example, if someone entered a value of "~hall, ~gates, and ~mcnealy" into field with the name "users" in an HTML form, the data would get sent as "users=%7Ehall%2C+%7Egates%2C+and+%mcnealy". Finally, the fourth reason that parsing form data is tedious is that values can be omitted (e.g.ram1=val1&param2=&param3=val3) and a parameter can have more than one value in that the same parameter can appear mn once (e.g. param1=val1&param2=val2&param1=val3).

    e of the nice features of Java servlets is that all of this form parsing is handled automatically. You simply call the getParameter mhe HttpServletRequest, supplying the parameter name as an argument. Note that parameter names are case sensitive. You do t

    ctly the same way when the data is sent via GET as you do when it is sent via POST. The return value is a String corresponding toecoded value of the first occurrence of that parameter name. An empty String is returned if the parameter exists but has no value, all is returned if there was no such parameter. If the parameter could potentially have more than one value, as in the example above, yould call getParameterValues instead ofgetParameter. This returns an array of strings. Finally, although in real applicatior servlets probably have a specific set of parameter names they are looking for, for debugging purposes it is sometimes useful to get a Use getParameterNames for this, which returns an Enumeration, each entry of which can be cast to a String and used intParameter call.

    Example: Reading Three Parameters

    e's a simple example that reads parameters named param1, param2, and param3, listing their values in a bulleted list. Note that,ough you are required to specify response settings (content type, status line, other HTTP headings) before beginning to generate the co

    tp://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-Form-Data.html (1 of 8)2007/04/22 08:55:43 .

    http://courses.coreservlets.com/Course-Materials/csajsp2.htmlhttp://courses.coreservlets.com/Course-Materials/msajsp.htmlhttp://courses.coreservlets.com/Course-Materials/struts.htmlhttp://www.coreservlets.com/JSF-Tutorial/http://www.coreservlets.com/Apache-Tomcat-Tutorial/http://courses.coreservlets.com/Course-Materials/ajax.htmlhttp://courses.coreservlets.com/Course-Materials/java5.htmlhttp://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/index.htmlhttp://courses.coreservlets.com/http://courses.coreservlets.com/http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/index.htmlhttp://courses.coreservlets.com/Course-Materials/java5.htmlhttp://courses.coreservlets.com/Course-Materials/ajax.htmlhttp://www.coreservlets.com/Apache-Tomcat-Tutorial/http://www.coreservlets.com/JSF-Tutorial/http://courses.coreservlets.com/Course-Materials/struts.htmlhttp://courses.coreservlets.com/Course-Materials/msajsp.htmlhttp://courses.coreservlets.com/Course-Materials/csajsp2.html
  • 7/31/2019 Servere Java

    19/93

    ervlet Tutorial: Handling Form Data

    re is no requirement that you read the request parameters at any particular time.

    o note you can easily make servlets that can handle both GET and POST data, simply by having its doPost method call doGet or brriding service (which calls doGet, doPost, doHead, etc.). This is good standard practice, since it requires very little extra wopermits flexibility on the part of the client. If you're used to the traditional CGI approach where you read POST data via the standard should note that there is a similar way with servlets by first calling getReader or getInputStream on thetpServletRequest. This is a bad idea for regular parameters, but might be of use for uploaded files or POST data being sent bytom clients rather than via HTML forms. Note, however, that if you read the POST data in that manner, it might no longer be found bytParameter.

    ThreeParams.java

    u can also download the source or try it on-line. Note: also uses ServletUtilities.java, shown earlier.

    ckage hall;

    port java.io.*;

    port javax.servlet.*;

    port javax.servlet.http.*;

    port java.util.*;

    blic class ThreeParams extends HttpServlet {

    public void doGet(HttpServletRequest request,

    HttpServletResponse response)

    throws ServletException, IOException {

    response.setContentType("text/html");

    PrintWriter out = response.getWriter();

    String title = "Reading Three Request Parameters";

    out.println(ServletUtilities.headWithTitle(title) +

    "\n" +

    "" + title + "\n" +

    "\n" +

    " param1: "

    + request.getParameter("param1") + "\n" +

    " param2: "

    + request.getParameter("param2") + "\n" +

    " param3: "

    + request.getParameter("param3") + "\n" +

    "\n" +

    "");

    }

    public void doPost(HttpServletRequest request,

    HttpServletResponse response)

    throws ServletException, IOException {doGet(request, response);

    }

    2 ThreeParams Output

    tp://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-Form-Data.html (2 of 8)2007/04/22 08:55:43 .

    http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/hall/ThreeParams.javahttp://webdev.apl.jhu.edu/servlet/hall.ThreeParams?param1=%7Ehall&param2=%7Egates&param3=%7Emcnealyhttp://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/hall/ServletUtilities.javahttp://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/hall/ServletUtilities.javahttp://webdev.apl.jhu.edu/servlet/hall.ThreeParams?param1=%7Ehall&param2=%7Egates&param3=%7Emcnealyhttp://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/hall/ThreeParams.java
  • 7/31/2019 Servere Java

    20/93

    ervlet Tutorial: Handling Form Data

    Example: Listing All Form Data

    e's an example that looks up all the parameter names that were sent and puts them in a table. It highlights parameters that have zero vawell as ones that have multiple values. First, it looks up all the parameter names via the getParameterNamesmethod oftpServletRequest. This returns an Enumeration. Next, it loops down the Enumeration in the standard manner, usingsMoreElements to determine when to stop and using nextElement to get each entry. Since nextElement returns an Objets the result to a String and passes that to getParameterValues, yielding an array ofStrings. If that array is one entry lontains only an empty string, then the parameter had no values, and the servlet generates an italicized "No Value" entry. If the array is mn one entry long, then the parameter had multiple values, and they are displayed in a bulleted list. Otherwise the one main value is justced into the table.

    ShowParameters.java

    u can also download the source or try it on-line. Note: also uses ServletUtilities.java, shown earlier.

    ckage hall;

    port java.io.*;

    port javax.servlet.*;

    port javax.servlet.http.*;

    port java.util.*;

    * Shows all the parameters sent to the servlet via either

    GET or POST. Specially marks parameters that have no values or

    multiple values.

    Part of tutorial on servlets and JSP that appears at

    http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/

    1999 Marty Hall; may be freely used or adapted.

    /

    blic class ShowParameters extends HttpServlet {

    public void doGet(HttpServletRequest request,

    HttpServletResponse response)

    throws ServletException, IOException {

    tp://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-Form-Data.html (3 of 8)2007/04/22 08:55:43 .

    http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/hall/ShowParameters.javahttp://webdev.apl.jhu.edu/servlet/hall.ShowParameters?ceo=%7Ehall&assistant1=%7Egates&assistant2=%7Emcnealyhttp://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/hall/ServletUtilities.javahttp://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/hall/ServletUtilities.javahttp://webdev.apl.jhu.edu/servlet/hall.ShowParameters?ceo=%7Ehall&assistant1=%7Egates&assistant2=%7Emcnealyhttp://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/hall/ShowParameters.java
  • 7/31/2019 Servere Java

    21/93

    ervlet Tutorial: Handling Form Data

    response.setContentType("text/html");

    PrintWriter out = response.getWriter();

    String title = "Reading All Request Parameters";

    out.println(ServletUtilities.headWithTitle(title) +

    "\n" +

    "" + title + "\n" +

    "\n" +

    "\n" +

    "Parameter NameParameter Value(s)");

    Enumeration paramNames = request.getParameterNames();

    while(paramNames.hasMoreElements()) {

    String paramName = (String)paramNames.nextElement();

    out.println("" + paramName + "\n");

    String[] paramValues = request.getParameterValues(paramName);

    if (paramValues.length == 1) {

    String paramValue = paramValues[0];

    if (paramValue.length() == 0)

    out.print("No Value");

    else

    out.print(paramValue);

    } else {

    out.println("");for(int i=0; i

  • 7/31/2019 Servere Java

    22/93

    ervlet Tutorial: Handling Form Data

    ORM ACTION="/servlet/hall.ShowParameters"

    METHOD="POST">

    Item Number:


    Quantity:


    Price Each:


    First Name:


    Last Name:


    Middle Initial:


    Shipping Address:


    Credit Card:

    Visa

    Master Card
    American Express

    Discover

    Java SmartCard

    Credit Card Number:


    Repeat Credit Card Number:



    FORM>

    BODY>

    HTML>

    tp://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-Form-Data.html (5 of 8)2007/04/22 08:55:43 .

  • 7/31/2019 Servere Java

    23/93

    ervlet Tutorial: Handling Form Data

    3 Submission Result

    tp://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-Form-Data.html (6 of 8)2007/04/22 08:55:43 .

  • 7/31/2019 Servere Java

    24/93

    ervlet Tutorial: Handling Form Data

    Sitemap for coreservlets.com

    tp://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-Form-Data.html (7 of 8)2007/04/22 08:55:43 .

    bout the Instructorourse Reviewsermediate Servlet & JSP Training

    oursesdvanced Servlet & JSP TrainingoursesCWCD Training Courseskarta Struts Training CoursesvaServer Faces (JSF) & ApacheyFaces Training Coursesax Training Coursesva 5 & 6 Programming Trainingoursesustomized On-Site Training Coursesblic Training Course Schedule

    Apache Tomcat TutorialIntermediate Servlets & JSP TutorialAdvanced Servlets & JSP TutorialSCWCD (Sun Certified WebComponent Developer) ExamJakarta Struts TutorialJavaServer Faces (JSF) & ApacheMyFaces TutorialJava 5 & 6 Programming TutorialsTutorials in ChineseTutorials in Japanese

    Specifications & DocumentationServersIDEs

    Java-Related JobsJavaServer Faces (JSF)BooksWeb Hosting ProvidersJava Programming Resources

    Tra in ing

    Tuto r i a l s

    Progr am m ing Resour ces

    http://courses.coreservlets.com/about-instructor.htmlhttp://courses.coreservlets.com/student-reviews.htmlhttp://courses.coreservlets.com/servlet+jsp-training.htmlhttp://courses.coreservlets.com/servlet+jsp-training.htmlhttp://courses.coreservlets.com/advanced-servlet+jsp-training.htmlhttp://courses.coreservlets.com/advanced-servlet+jsp-training.htmlhttp://courses.coreservlets.com/scwcd-training.htmlhttp://courses.coreservlets.com/struts-training.htmlhttp://courses.coreservlets.com/jsf-training.htmlhttp://courses.coreservlets.com/jsf-training.htmlhttp://courses.coreservlets.com/ajax-training.htmlhttp://courses.coreservlets.com/java-training.htmlhttp://courses.coreservlets.com/java-training.htmlhttp://courses.coreservlets.com/http://courses.coreservlets.com/public-courses/http://www.coreservlets.com/Apache-Tomcat-Tutorial/http://courses.coreservlets.com/Course-Materials/csajsp2.htmlhttp://courses.coreservlets.com/Course-Materials/msajsp.htmlhttp://courses.coreservlets.com/Course-Materials/scwcd.htmlhttp://courses.coreservlets.com/Course-Materials/scwcd.htmlhttp://courses.coreservlets.com/Course-Materials/struts.htmlhttp://www.coreservlets.com/JSF-Tutorial/http://www.coreservlets.com/JSF-Tutorial/http://courses.coreservlets.com/Course-Materials/java5.htmlhttp://courses.coreservlets.com/Course-Materials/chinese.htmlhttp://courses.coreservlets.com/Course-Materials/japanese.htmlhttp://resources.coreservlets.com/jsp-docs.htmlhttp://resources.coreservlets.com/jsp-servers.htmlhttp://resources.coreservlets.com/jsp-ides.htmlhttp://resources.coreservlets.com/j2ee-jobs.htmlhttp://resources.coreservlets.com/jsf.htmlhttp://resources.coreservlets.com/jsp+servlet-books.htmlhttp://resources.coreservlets.com/jsp-hosting.htmlhttp://www.apl.jhu.edu/~hall/java/http://www.apl.jhu.edu/~hall/java/http://resources.coreservlets.com/jsp-hosting.htmlhttp://resources.coreservlets.com/jsp+servlet-books.htmlhttp://resources.coreservlets.com/jsf.htmlhttp://resources.coreservlets.com/j2ee-jobs.htmlhttp://resources.coreservlets.com/jsp-ides.htmlhttp://resources.coreservlets.com/jsp-servers.htmlhttp://resources.coreservlets.com/jsp-docs.htmlhttp://courses.coreservlets.com/Course-Materials/japanese.htmlhttp://courses.coreservlets.com/Course-Materials/chinese.htmlhttp://courses.coreservlets.com/Course-Materials/java5.htmlhttp://www.coreservlets.com/JSF-Tutorial/http://www.coreservlets.com/JSF-Tutorial/http://courses.coreservlets.com/Course-Materials/struts.htmlhttp://courses.coreservlets.com/Course-Materials/scwcd.htmlhttp://courses.coreservlets.com/Course-Materials/scwcd.htmlhttp://courses.coreservlets.com/Course-Materials/msajsp.htmlhttp://courses.coreservlets.com/Course-Materials/csajsp2.htmlhttp://www.coreservlets.com/Apache-Tomcat-Tutorial/http://courses.coreservlets.com/public-courses/http://courses.coreservlets.com/http://courses.coreservlets.com/java-training.htmlhttp://courses.coreservlets.com/java-training.htmlhttp://courses.coreservlets.com/ajax-training.htmlhttp://courses.coreservlets.com/jsf-training.htmlhttp://courses.coreservlets.com/jsf-training.htmlhttp://courses.coreservlets.com/struts-training.htmlhttp://courses.coreservlets.com/scwcd-training.htmlhttp://courses.coreservlets.com/advanced-servlet+jsp-training.htmlhttp://courses.coreservlets.com/advanced-servlet+jsp-training.htmlhttp://courses.coreservlets.com/servlet+jsp-training.htmlhttp://courses.coreservlets.com/servlet+jsp-training.htmlhttp://courses.coreservlets.com/student-reviews.htmlhttp://courses.coreservlets.com/about-instructor.html
  • 7/31/2019 Servere Java

    25/93

    ervlet Tutorial: Handling Form Data

    tp://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-Form-Data.html (8 of 8)2007/04/22 08:55:43 .

    ore Servlets & JSP 2nd Ed.ore Servlets & JSPore Web Programmingore Servlets & JSP 1st Ed.ore Servlets & JSP E-Bookore Servlets & JSP E-Book

    Our consulting services We are hiring!

    B ooks Consu l t i ng Jobs

    http://volume1.coreservlets.com/http://www.moreservlets.com/http://www.corewebprogramming.com/http://www.coreservlets.com/first-edition.htmlhttp://pdf.coreservlets.com/http://pdf.moreservlets.com/http://consulting.coreservlets.com/http://jobs.coreservlets.com/http://jobs.coreservlets.com/http://consulting.coreservlets.com/http://pdf.moreservlets.com/http://pdf.coreservlets.com/http://www.coreservlets.com/first-edition.htmlhttp://www.corewebprogramming.com/http://www.moreservlets.com/http://volume1.coreservlets.com/
  • 7/31/2019 Servere Java

    26/93

    ervlet Tutorial: Reading HTTP Request Headers

    Reading HTTP Request Headers

    NOTE: This tutorial is now out of date. Please see the following sites for updated and advanced

    information.

    q Intermediate servlet and JSP tutorial

    q Advanced servlet and JSP tutorial

    q Jakarta Struts tutorial

    q Tutorial on JSF (JavaServer Faces) and Apache MyFaces

    q Apache Tomcat Setup and Introductory Tutorial

    q Ajax tutorial

    q Tutorials on Java 5 and Java 6 Programming

    1. An Overview of Request Headers

    2. Reading Request Headers from Servlets

    3. Example: Printing all Headers4. Servlet and JSP Tutorial: Top5. Servlet and JSP Training Courses On-site atyourcompany o

    public venues.

    An Overview of Request Headers

    hen an HTTP client (e.g. a browser) sends a request, it is required to supply a request line (usually GET or POST). Ifnts to, it can also send a number of headers, all of which are optional except for Content-Length, which is requ

    ly for POST requests. Here are the most common headers:q Accept The MIME types the browser prefers.q Accept-Charset The character set the browser expects.q Accept-Encoding The types of data encodings (such as gzip) the browser knows how to decode. Servlets

    explicitly check for gzip support and return gzipped HTML pages to browsers that support them, setting theContent-Encoding response header to indicate that they are gzipped. In many cases, this can reduce pagedownload times by a factor of five or ten.

    q Accept-Language The language the browser is expecting, in case the server has versions in more than onelanguage.

    q Authorization Authorization info, usually in response to a WWW-Authenticate header from the servq

    Connection Use persistent connection? If a servlet gets a Keep-Alive value here, or gets a request lineindicating HTTP 1.1 (where persistent connections are the default), it may be able to take advantage of persistenconnections, saving significant time for Web pages that include several small pieces (images or applet classes). do this, it needs to send a Content-Length header in the response, which is most easily accomplished bywriting into a ByteArrayOutputStream, then looking up the size just before writing it out.

    q Content-Length (for POST messages, how much data is attached)q Cookie (one of the most important headers; see separate section in this tutorial on handling cookies)q From (email address of requester; only used by Web spiders and other custom clients, not by browsers)q Host (host and port as listed in the original URL)q If-Modified-Since (only return documents newer than this, otherwise send a 304 "Not Modified" respon

    ttp://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-Request-Headers.html (1 of 6)2007/04/22 08:55:45 .

    http://courses.coreservlets.com/Course-Materials/csajsp2.htmlhttp://courses.coreservlets.com/Course-Materials/msajsp.htmlhttp://courses.coreservlets.com/Course-Materials/struts.htmlhttp://www.coreservlets.com/JSF-Tutorial/http://www.coreservlets.com/Apache-Tomcat-Tutorial/http://courses.coreservlets.com/Course-Materials/ajax.htmlhttp://courses.coreservlets.com/Course-Materials/java5.htmlhttp://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/index.htmlhttp://courses.coreservlets.com/http://courses.coreservlets.com/http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/index.htmlhttp://courses.coreservlets.com/Course-Materials/java5.htmlhttp://courses.coreservlets.com/Course-Materials/ajax.htmlhttp://www.coreservlets.com/Apache-Tomcat-Tutorial/http://www.coreservlets.com/JSF-Tutorial/http://courses.coreservlets.com/Course-Materials/struts.htmlhttp://courses.coreservlets.com/Course-Materials/msajsp.htmlhttp://courses.coreservlets.com/Course-Materials/csajsp2.html
  • 7/31/2019 Servere Java

    27/93

    ervlet Tutorial: Reading HTTP Request Headers

    q Pragma (the no-cache value indicates that the server should return a fresh document, even if it is a proxy wlocal copy)

    q Referer (the URL of the page containing the link the user followed to get to current page)q User-Agent (type of browser, useful if servlet is returning browser-specific content)q UA-Pixels, UA-Color, UA-OS, UA-CPU (nonstandard headers sent by some Internet Explorer versions,

    indicating screen size, color depth, operating system, and cpu type used by the browser's system)

    r full details on HTTP headers, see the specifications at http://www.w3.org/Protocols/.

    Reading Request Headers from Servlets

    ading headers is very straightforward; just call the getHeader method of the HttpServletRequest, whichurns a String if the header was supplied on this request, null otherwise. However, there are a couple of headersso commonly used that they have special access methods. The getCookies method returns the contents of theokie header, parsed and stored in an array ofCookie objects. See the separate section of this tutorial on cookiestAuthType and getRemoteUser methods break the Authorization header into its component pieces. TtDateHeader and getIntHeader methods read the specified header and then convert them to Date and inues, respectively.

    ther than looking up one particular header, you can use the getHeaderNames to get an Enumeration of allader names received on this particular request.

    nally, in addition to looking up the request headers, you can get information on the main request line itself. ThetMethod method returns the main request method (normally GET or POST, but things like HEAD, PUT, and DELpossible). The getRequestURI method returns the URI (the part of the URL that came after the host and port, b

    fore the form data). The getRequestProtocol returns the third part of the request line, which is generallyTTP/1.0" or "HTTP/1.1".

    Example: Printing all Headers

    re's a servlet that simply creates a table of all the headers it receives, along with their associated values. It also printsthree components of the main request line (method, URI, and protocol).

    1 ShowRequestHeaders.java

    u can also download the source or try it on-line.

    ckage hall;

    port java.io.*;

    port javax.servlet.*;

    port javax.servlet.http.*;

    port java.util.*;

    blic class ShowRequestHeaders extends HttpServlet {

    public void doGet(HttpServletRequest request,

    HttpServletResponse response)

    ttp://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-Request-Headers.html (2 of 6)2007/04/22 08:55:45 .

    http://www.w3.org/Protocols/http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/hall/ShowRequestHeaders.javahttp://webdev.apl.jhu.edu/servlet/hall.ShowRequestHeadershttp://webdev.apl.jhu.edu/servlet/hall.ShowRequestHeadershttp://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/hall/ShowRequestHeaders.javahttp://www.w3.org/Protocols/
  • 7/31/2019 Servere Java

    28/93

    ervlet Tutorial: Reading HTTP Request Headers

    throws ServletException, IOException {

    response.setContentType("text/html");

    PrintWriter out = response.getWriter();

    String title = "Servlet Example: Showing Request Headers";

    out.println(ServletUtilities.headWithTitle(title) +

    "\n" +

    "" + title + "\n" +

    "Request Method: " +

    request.getMethod() + "
    \n" +"Request URI: " +

    request.getRequestURI() + "
    \n" +

    "Request Protocol: " +

    request.getProtocol() + "

    \n" +

    "\n" +

    "\n" +

    "Header NameHeader Value");

    Enumeration headerNames = request.getHeaderNames();

    while(headerNames.hasMoreElements()) {

    String headerName = (String)headerNames.nextElement();out.println("" + headerName);

    out.println(" " + request.getHeader(headerName));

    }

    out.println("\n");

    }

    public void doPost(HttpServletRequest request,

    HttpServletResponse response)

    throws ServletException, IOException {

    doGet(request, response);

    }

    2 ShowRequestHeaders Output

    re are the results of two typical requests, one from Netscape and one from Internet Explorer. You'll see the reasontscape shows a Cookie header when you get to the tutorial section on cookies.

    ttp://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-Request-Headers.html (3 of 6)2007/04/22 08:55:45 .

  • 7/31/2019 Servere Java

    29/93

  • 7/31/2019 Servere Java

    30/93

  • 7/31/2019 Servere Java

    31/93

    ervlet Tutorial: Reading HTTP Request Headers

    ttp://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-Request-Headers.html (6 of 6)2007/04/22 08:55:45 .

    bout the Instructorourse Reviews

    ntermediate Servlet & JSP Trainingoursesdvanced Servlet & JSP Trainingourses

    CWCD Training Coursesakarta Struts Training CoursesavaServer Faces (JSF) & Apache

    MyFaces Training Coursesjax Training Courses

    ava 5 & 6 Programming Trainingoursesustomized On-Site Training Coursesublic Training Course Schedule

    Apache Tomcat TutorialIntermediate Servlets & JSP TutorialAdvanced Servlets & JSP TutorialSCWCD (Sun Certified Web

    Component Developer) ExamJakarta Struts TutorialJavaServer Faces (JSF) & ApacheMyFaces TutorialJava 5 & 6 Programming TutorialsTutorials in ChineseTutorials in Japanese

    Specifications & DocumentationServers

    IDEsJava-Related JobsJavaServer Faces (JSF)BooksWeb Hosting ProvidersJava Programming Resources

    ore Servlets & JSP 2nd Ed.More Servlets & JSP

    ore Web Programmingore Servlets & JSP 1st Ed.ore Servlets & JSP E-Book

    More Servlets & JSP E-Book

    Our consulting services We are hiring!

    Tra in ing

    Tu to r i a l s

    Progr am m ing Resour ces

    Books Consu l t ing Jobs

    http://courses.coreservlets.com/about-instructor.htmlhttp://courses.coreservlets.com/student-reviews.htmlhttp://courses.coreservlets.com/servlet+jsp-training.htmlhttp://courses.coreservlets.com/servlet+jsp-training.htmlhttp://courses.coreservlets.com/advanced-servlet+jsp-training.htmlhttp://courses.coreservlets.com/advanced-servlet+jsp-training.htmlhttp://courses.coreservlets.com/scwcd-training.htmlhttp://courses.coreservlets.com/struts-training.htmlhttp://courses.coreservlets.com/jsf-training.htmlhttp://courses.coreservlets.com/jsf-training.htmlhttp://courses.coreservlets.com/ajax-training.htmlhttp://courses.coreservlets.com/java-training.htmlhttp://courses.coreservlets.com/java-training.htmlhttp://courses.coreservlets.com/http://courses.coreservlets.com/public-courses/http://www.coreservlets.com/Apache-Tomcat-Tutorial/http://courses.coreservlets.com/Course-Materials/csajsp2.htmlhttp://courses.coreservlets.com/Course-Materials/msajsp.htmlhttp://courses.coreservlets.com/Course-Materials/scwcd.htmlhttp://courses.coreservlets.com/Course-Materials/scwcd.htmlhttp://courses.coreservlets.com/Course-Materials/struts.htmlhttp://www.coreserv