SlideShare une entreprise Scribd logo
1  sur  7
HTML – SERVLET EXAMPLE
Servlets are the pure Java solution to handle web requests. Many application will use servlets instead
of JSP and others will use servlets in conjunction with JSP. Experienced JSP programmers use
servlets in conjunction with JSP to create clearer and simpler applications. The servlets handle Java
processing: form handing, calculation and database queries. JSP formats the results.

Servlets belong in WEB-INF/classes. On this machine, the source is in Java source in
/var/www/hosts/www.caucho.com/webapps/resin-3.0/servlet/tutorial/helloworld/WEB-INF/classes.
WEB-INF/classes is the standard location for servlets and other Java classes. Resin automatically
reloads and recompiles servlets, beans, and classes placed in WEB-INF/classes. You should make
some changes and add errors to become familiar with Resin's recompilation and the error reporting.

Create the following servlet in WEB-INF/classes/test/HelloServlet.java with your favorite text editor:
notepad, emacs, vi, or whatever. (On this machine, /var/www/hosts/www.caucho.com/webapps/resin-
3.0/servlet/tutorial/helloworld/WEB-INF/classes/test/HelloServlet.java)

                       WEB-INF/classes/test/HelloServlet.java
package test;

import java.io.*;

import javax.servlet.http.*;
import javax.servlet.*;

public class HelloServlet extends HttpServlet {
  public void doGet (HttpServletRequest req,
                     HttpServletResponse res)
    throws ServletException, IOException
  {
    PrintWriter out = res.getWriter();

        out.println("Hello, world!");
        out.close();
    }

}

Now browse the servlet at /resin-3.0/servlet/tutorial/helloworld/hello. Resin will automatically
compiles the servlet for you. Browsing servlets differs from page browsing because you're executing
a servlet class, not looking at a page. The /hello URL is configured for the hello, world servlet below.


Configuration
Configuration for the servlet is in the WEB-INF/web.xml file.

The servlet needs to be configured and it needs to be mapped to a URL. The <servlet> tag configures
the servlet. In our simple example, we just need to specify the class name for the servlet.

The <servlet-mapping> tag specifies the URLs which will invoke the servlet. In our case, the /hello
URL invokes the servlet. Because the tutorial webapp is a sub-URL like
/doc/servlet/tutorial/helloworld, the actual URL to invoke the servlet is the combination of the two.
WEB-INF/web.xml
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" version="2.4"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http:/java.sun.com/dtd/web-app_2_3.dtd">
  <servlet>
    <servlet-name>hello</servlet-name>
    <servlet-class>test.HelloServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>hello</servlet-name>
    <url-pattern>/hello</url-pattern>
  </servlet-mapping>
</web-app>

Resin allows a short cut for the XML configuration in the example above; you can use XML
attributes in place of elements. The Servlet 2.4 standard uses only elements. So the servlet-mapping
configuration following the Servlet 2.4 standard would look like:

                                WEB-INF/resin-web.xml
<web-app xmlns="http://caucho.com/ns/resin">
   <servlet servlet-name="hello"
            servlet-class="test.HelloServlet"/>

   <servlet-mapping url-pattern="/hello"
            servlet-name="hello"/>
</web-app>

The two are entirely equivalent. For larger configurations, using attributes makes the resin.conf or
web.xml more readable.

          tag                                          meaning
web-app               Web application top-level tag.

The xmlns="http://caucho.com/ns/resin" lets Resin validate the web.xml configuration. The validator
will catch most errors in the web.xml.



WEB-INF/classes/test/HelloServlet.java

package test;

import java.io.*;

import javax.servlet.http.*;
import javax.servlet.*;

/**
 * Hello world servlet. Most servlets will extend
 * javax.servlet.http.HttpServlet as this one does.
 */
public class HelloServlet extends HttpServlet {
  /**
    * Implements the HTTP GET method. The GET method is the standard
* browser method.
      *
      * @param request the request object, containing data from the browser
      * @param repsonse the response object to send data to the browser
      */
    public void doGet (HttpServletRequest request,
                         HttpServletResponse response)
        throws ServletException, IOException
    {
        // Returns a writer to write to the browser
        PrintWriter out = response.getWriter();

        // Writes the string to the browser.
        out.println("Hello, world!");
        out.close();
    }
}


WEB-INF/resin-web.xml

<web-app xmlns="http://caucho.com/ns/resin">
  <servlet servlet-name="hello"
           servlet-class="test.HelloServlet"/>

  <servlet-mapping url-pattern="/hello"
                   servlet-name="hello"/>
</web-app>



1. Basic Servlet Structure
Here's the outline of a basic servlet that handles GET requests. GET requests, for those unfamiliar with
HTTP, are requests made by browsers when the user types in a URL on the address line, follows a
link from a Web page, or makes an HTML form that does not specify a METHOD. Servlets can also
very easily handle POST requests, which are generated when someone creates an HTML form that
specifies METHOD="POST". We'll discuss that in later sections.

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public 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
    }}
To be a servlet, a class should extend HttpServlet and override doGet or doPost (or both), depending on
whether the data is being sent by GET or by POST. These methods take two arguments: an
HttpServletRequest and an HttpServletResponse. The HttpServletRequest has methods that let you find
out about incoming information such as FORM data, HTTP request headers, and the like. The
HttpServletResponse has methods that lets you specify the HTTP response line (200, 404, etc.), response
headers (Content-Type, Set-Cookie, etc.), and, most importantly, lets you obtain a PrintWriter used to
send output back to the client. For simple servlets, most of the effort is spent in println statements that
generate the desired page. Note that doGet and doPost throw two exceptions, so you are required to
include them in the declaration. Also note that you have to import classes in java.io (for PrintWriter,
etc.), javax.servlet (for HttpServlet, etc.), and javax.servlet.http (for HttpServletRequest
and HttpServletResponse). Finally, note that doGet and doPost are called by the service method, and
sometimes you may want to override service directly, e.g. for a servlet that handles both GET and POST
request.


2. A Simple Servlet Generating Plain Text
Here is a simple servlet that just generates plain text. The following section will show the more usual case
where HTML is generated.

2.1 HelloWorld.java
You can also download the source or try it on-line.

package hall;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloWorld extends HttpServlet {
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    out.println("Hello World");
  }
}


2.2 Compiling and Installing the Servlet
Note that the specific details for installing servlets vary from Web server to Web server. Please refer to your
Web server documentation for definitive directions. The on-line examples are running on Java Web Server
(JWS) 2.0, where servlets are expected to be in a directory called servlets in the JWS installation hierarchy.
However, I placed this servlet in a separate package (hall) to avoid conflicts with other servlets on this server;
you'll want to do the same if you are using a Web server that is used by other people and doesn't have a good
infrastructure for "virtual servers" to prevent these conflicts automatically. Thus, HelloWorld.java actually goes
in a subdirectory called hall in the servlets directory. Note that setup on most other servers is similar, and the
servlet and JSP examples in the tutorial have also been tested using BEA WebLogic and IBM WebSphere 3.0.
WebSphere has an excellent mechanism for virtual servers, and it is not necessary to use packages solely to
prevent name conflicts with other users.

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

One way is to set your CLASSPATH to point to the directory above the one actually containing your
servlets. You can them compile normally from within the directory. For example, if your base
directory is C:JavaWebServerservlets and your package name (and thus subdirectory name) is
hall, and you were on Windows, you'd do:


  DOS> set CLASSPATH=C:JavaWebServerservlets;%CLASSPATH%
  DOS> cd C:JavaWebServerservletshall
  DOS> javac YourServlet.java


The first part, setting the CLASSPATH, you probably want to do permanently, rather than each time you
start a new DOS window. On Windows 95/98 you'd typically put the "set CLASSPATH=..." statement
in your autoexec.bat file somewhere after the line that set the CLASSPATH to point to servlet.jar
and jsp.jar. On Windows NT, you'd go to the Start menu, select Settings, select Control Panel,
select System, select Environment, then enter the variable and value. Note also that if your package
were of the form name1.name2.name3 rather than simply name1 as here, you'd still have the
CLASSPATH point to the top-level directory of your package hierarchy (the one containing name1).

A second way to compile classes that are in packages is to go to the directory above the one
containing your servlets, and then do "javac directoryYourServlet.java" (Windows; note the
backslash) or "javac directory/YourServlet.java" (Unix; note the forward slash). For example,
suppose again that your base directory is C:JavaWebServerservlets and your package name (and
thus subdirectory name) is hall, and you were on Windows. In that case, you'd do the following:
  DOS> cd C:JavaWebServerservlets
  DOS> javac hallYourServlet.java
Note that, on Windows, most JDK 1.1 versions of javac require a backslash, not a forward slash,
after the directory name. This is fixed in JDK 1.2, but since many Web servers are configured to use
JDK 1.1, many servlet authors stick with JDK 1.1 for portability.

Finally, another advanced option is to keep the source code in a location distinct from the .class files,
and use javac's "-d" option to install them in the location the Web server expects.

2.3 Running the Servlet

With the Java Web Server, servlets are placed in the servlets directory within the main JWS installation
directory, and are invoked via http://host/servlet/ServletName. Note that the directory is
servlets, plural, while the URL refers to servlet, singular. Since this example was placed in the hall
package, it would be invoked via http://host/servlet/hall.HelloWorld. Other Web servers may
have slightly different conventions on where to install servlets and how to invoke them. Most servers also let
you define aliases for servlets, so that a servlet can be invoked via http://host/any-path/any-
file.html. The process for doing this is completely server-specific; check your server's documentation for
details.
3. A Servlet that Generates HTML
Most servlets generate HTML, not plain text as in the previous example. To do that, you need two additional
steps: tell the browser that you're sending back HTML, and modify the println statements to build a legal
Web page. The first step is done by setting the Content-Type response header. In general, headers can be
set via the setHeader method of HttpServletResponse, but setting the content type is such a common
task that there is also a special setContentType method just for this purpose. Note that you need to set
response headers before actually returning any of the content via the PrintWriter. Here's an example:

3.1 HelloWWW.java
You can also download the source or try it on-line.

package hall;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloWWW extends HttpServlet {
  public void doGet(HttpServletRequest request,
                     HttpServletResponse response)
       throws ServletException, IOException {
     response.setContentType("text/html");
     PrintWriter out = response.getWriter();
     out.println("<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 " +
                                         "Transitional//EN">n" +
                 "<HTML>n" +
                 "<HEAD><TITLE>Hello WWW</TITLE></HEAD>n" +
                 "<BODY>n" +
                 "<H1>Hello WWW</H1>n" +
                 "</BODY></HTML>");
  }}


3.2 HelloWWW Result
4. Simple HTML-Building Utilities
It is a bit cumbersome to generate HTML with println statements. The real solution is to use Java Server
Pages (JSP), which is discussed later in this tutorial. However, for standard servlets, there are two parts of the
Web page (DOCTYPE and HEAD) that are unlikely to change and thus could benefit from being incorporated
into a simple utility file.

The DOCTYPE line is technically required by the HTML spec, and although most major browsers
ignore it, it is very useful when sending pages to formal HTML validators. These validators compare
the HTML syntax of pages against the formal HTML specification, and use the DOCTYPE line to
determine which version of HTML to check against. Their use is very highly recommended both for
static HTML pages and for pages generated via servlets, so the use of DOCTYPE is well worth the
effort, especially if it can be easily incorporated into a servlet utilities class.

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

4.1 ServletUtilities.java (Download source code)
package hall;

public class ServletUtilities {
  public static final String DOCTYPE =
    "<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">";

    public static String headWithTitle(String title) {
      return(DOCTYPE + "n" +
             "<HTML>n" +
             "<HEAD><TITLE>" + title + "</TITLE></HEAD>n");
    }

    // Other utilities will be shown later...
}

4.2 HelloWWW2.java (Download source code)
Here's a rewrite of the HelloWWW class that uses this.

package hall;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public 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") +
                "<BODY>n" +
                "<H1>Hello WWW</H1>n" +
                "</BODY></HTML>");
  }
}

Contenu connexe

Tendances

Web Tech Java Servlet Update1
Web Tech   Java Servlet Update1Web Tech   Java Servlet Update1
Web Tech Java Servlet Update1
vikram singh
 
An Introduction To Java Web Technology
An Introduction To Java Web TechnologyAn Introduction To Java Web Technology
An Introduction To Java Web Technology
vikram singh
 
JAVA EE DEVELOPMENT (JSP and Servlets)
JAVA EE DEVELOPMENT (JSP and Servlets)JAVA EE DEVELOPMENT (JSP and Servlets)
JAVA EE DEVELOPMENT (JSP and Servlets)
Talha Ocakçı
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
vamsi krishna
 

Tendances (20)

Jsf 2.0 in depth
Jsf 2.0 in depthJsf 2.0 in depth
Jsf 2.0 in depth
 
Jsp and jstl
Jsp and jstlJsp and jstl
Jsp and jstl
 
Servlets
ServletsServlets
Servlets
 
Spring introduction
Spring introductionSpring introduction
Spring introduction
 
Web Tech Java Servlet Update1
Web Tech   Java Servlet Update1Web Tech   Java Servlet Update1
Web Tech Java Servlet Update1
 
Knowledge Sharing : Java Servlet
Knowledge Sharing : Java ServletKnowledge Sharing : Java Servlet
Knowledge Sharing : Java Servlet
 
Mule jdbc
Mule   jdbcMule   jdbc
Mule jdbc
 
An Introduction To Java Web Technology
An Introduction To Java Web TechnologyAn Introduction To Java Web Technology
An Introduction To Java Web Technology
 
java servlet and servlet programming
java servlet and servlet programmingjava servlet and servlet programming
java servlet and servlet programming
 
Web Applications and Deployment
Web Applications and DeploymentWeb Applications and Deployment
Web Applications and Deployment
 
JAVA EE DEVELOPMENT (JSP and Servlets)
JAVA EE DEVELOPMENT (JSP and Servlets)JAVA EE DEVELOPMENT (JSP and Servlets)
JAVA EE DEVELOPMENT (JSP and Servlets)
 
JSP
JSPJSP
JSP
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
 
Java Servlet
Java Servlet Java Servlet
Java Servlet
 
Introduction to the Servlet / JSP course
Introduction to the Servlet / JSP course Introduction to the Servlet / JSP course
Introduction to the Servlet / JSP course
 
Box connector Mule ESB Integration
Box connector Mule ESB IntegrationBox connector Mule ESB Integration
Box connector Mule ESB Integration
 
Data Access with JDBC
Data Access with JDBCData Access with JDBC
Data Access with JDBC
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technology
 
Multi Client Development with Spring
Multi Client Development with SpringMulti Client Development with Spring
Multi Client Development with Spring
 
Servlets
ServletsServlets
Servlets
 

Similaire à Html servlet example

Jsp and Servlets
Jsp and ServletsJsp and Servlets
Jsp and Servlets
Raghu nath
 
Web Application Deployment
Web Application DeploymentWeb Application Deployment
Web Application Deployment
elliando dias
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
Nitin Pai
 
Jsp and servlet_netbeans-webapps
Jsp and servlet_netbeans-webappsJsp and servlet_netbeans-webapps
Jsp and servlet_netbeans-webapps
OPENLANE
 

Similaire à Html servlet example (20)

Web container and Apache Tomcat
Web container and Apache TomcatWeb container and Apache Tomcat
Web container and Apache Tomcat
 
Cis 274 intro
Cis 274   introCis 274   intro
Cis 274 intro
 
Jsp and Servlets
Jsp and ServletsJsp and Servlets
Jsp and Servlets
 
Http Server Programming in JAVA - Handling http requests and responses
Http Server Programming in JAVA - Handling http requests and responsesHttp Server Programming in JAVA - Handling http requests and responses
Http Server Programming in JAVA - Handling http requests and responses
 
Weblogic
WeblogicWeblogic
Weblogic
 
Web Application Deployment
Web Application DeploymentWeb Application Deployment
Web Application Deployment
 
JavaEE6 my way
JavaEE6 my wayJavaEE6 my way
JavaEE6 my way
 
Java servlet technology
Java servlet technologyJava servlet technology
Java servlet technology
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Jsp tutorial
Jsp tutorialJsp tutorial
Jsp tutorial
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servlet
 
Unit5 servlets
Unit5 servletsUnit5 servlets
Unit5 servlets
 
Lecture5
Lecture5Lecture5
Lecture5
 
Java EE 02-First Servlet
Java EE 02-First ServletJava EE 02-First Servlet
Java EE 02-First Servlet
 
JEE Course - The Web Tier
JEE Course - The Web TierJEE Course - The Web Tier
JEE Course - The Web Tier
 
JEE5 New Features
JEE5 New FeaturesJEE5 New Features
JEE5 New Features
 
jsp tutorial
jsp tutorialjsp tutorial
jsp tutorial
 
JSP
JSPJSP
JSP
 
JSR 168 Portal - Overview
JSR 168 Portal - OverviewJSR 168 Portal - Overview
JSR 168 Portal - Overview
 
Jsp and servlet_netbeans-webapps
Jsp and servlet_netbeans-webappsJsp and servlet_netbeans-webapps
Jsp and servlet_netbeans-webapps
 

Dernier

Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 

Dernier (20)

Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 

Html servlet example

  • 1. HTML – SERVLET EXAMPLE Servlets are the pure Java solution to handle web requests. Many application will use servlets instead of JSP and others will use servlets in conjunction with JSP. Experienced JSP programmers use servlets in conjunction with JSP to create clearer and simpler applications. The servlets handle Java processing: form handing, calculation and database queries. JSP formats the results. Servlets belong in WEB-INF/classes. On this machine, the source is in Java source in /var/www/hosts/www.caucho.com/webapps/resin-3.0/servlet/tutorial/helloworld/WEB-INF/classes. WEB-INF/classes is the standard location for servlets and other Java classes. Resin automatically reloads and recompiles servlets, beans, and classes placed in WEB-INF/classes. You should make some changes and add errors to become familiar with Resin's recompilation and the error reporting. Create the following servlet in WEB-INF/classes/test/HelloServlet.java with your favorite text editor: notepad, emacs, vi, or whatever. (On this machine, /var/www/hosts/www.caucho.com/webapps/resin- 3.0/servlet/tutorial/helloworld/WEB-INF/classes/test/HelloServlet.java) WEB-INF/classes/test/HelloServlet.java package test; import java.io.*; import javax.servlet.http.*; import javax.servlet.*; public class HelloServlet extends HttpServlet { public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { PrintWriter out = res.getWriter(); out.println("Hello, world!"); out.close(); } } Now browse the servlet at /resin-3.0/servlet/tutorial/helloworld/hello. Resin will automatically compiles the servlet for you. Browsing servlets differs from page browsing because you're executing a servlet class, not looking at a page. The /hello URL is configured for the hello, world servlet below. Configuration Configuration for the servlet is in the WEB-INF/web.xml file. The servlet needs to be configured and it needs to be mapped to a URL. The <servlet> tag configures the servlet. In our simple example, we just need to specify the class name for the servlet. The <servlet-mapping> tag specifies the URLs which will invoke the servlet. In our case, the /hello URL invokes the servlet. Because the tutorial webapp is a sub-URL like /doc/servlet/tutorial/helloworld, the actual URL to invoke the servlet is the combination of the two.
  • 2. WEB-INF/web.xml <web-app xmlns="http://java.sun.com/xml/ns/j2ee" version="2.4" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http:/java.sun.com/dtd/web-app_2_3.dtd"> <servlet> <servlet-name>hello</servlet-name> <servlet-class>test.HelloServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> </web-app> Resin allows a short cut for the XML configuration in the example above; you can use XML attributes in place of elements. The Servlet 2.4 standard uses only elements. So the servlet-mapping configuration following the Servlet 2.4 standard would look like: WEB-INF/resin-web.xml <web-app xmlns="http://caucho.com/ns/resin"> <servlet servlet-name="hello" servlet-class="test.HelloServlet"/> <servlet-mapping url-pattern="/hello" servlet-name="hello"/> </web-app> The two are entirely equivalent. For larger configurations, using attributes makes the resin.conf or web.xml more readable. tag meaning web-app Web application top-level tag. The xmlns="http://caucho.com/ns/resin" lets Resin validate the web.xml configuration. The validator will catch most errors in the web.xml. WEB-INF/classes/test/HelloServlet.java package test; import java.io.*; import javax.servlet.http.*; import javax.servlet.*; /** * Hello world servlet. Most servlets will extend * javax.servlet.http.HttpServlet as this one does. */ public class HelloServlet extends HttpServlet { /** * Implements the HTTP GET method. The GET method is the standard
  • 3. * browser method. * * @param request the request object, containing data from the browser * @param repsonse the response object to send data to the browser */ public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Returns a writer to write to the browser PrintWriter out = response.getWriter(); // Writes the string to the browser. out.println("Hello, world!"); out.close(); } } WEB-INF/resin-web.xml <web-app xmlns="http://caucho.com/ns/resin"> <servlet servlet-name="hello" servlet-class="test.HelloServlet"/> <servlet-mapping url-pattern="/hello" servlet-name="hello"/> </web-app> 1. Basic Servlet Structure Here's the outline of a basic servlet that handles GET requests. GET requests, for those unfamiliar with HTTP, are requests made by browsers when the user types in a URL on the address line, follows a link from a Web page, or makes an HTML form that does not specify a METHOD. Servlets can also very easily handle POST requests, which are generated when someone creates an HTML form that specifies METHOD="POST". We'll discuss that in later sections. import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public 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 }}
  • 4. To be a servlet, a class should extend HttpServlet and override doGet or doPost (or both), depending on whether the data is being sent by GET or by POST. These methods take two arguments: an HttpServletRequest and an HttpServletResponse. The HttpServletRequest has methods that let you find out about incoming information such as FORM data, HTTP request headers, and the like. The HttpServletResponse has methods that lets you specify the HTTP response line (200, 404, etc.), response headers (Content-Type, Set-Cookie, etc.), and, most importantly, lets you obtain a PrintWriter used to send output back to the client. For simple servlets, most of the effort is spent in println statements that generate the desired page. Note that doGet and doPost throw two exceptions, so you are required to include them in the declaration. Also note that you have to import classes in java.io (for PrintWriter, etc.), javax.servlet (for HttpServlet, etc.), and javax.servlet.http (for HttpServletRequest and HttpServletResponse). Finally, note that doGet and doPost are called by the service method, and sometimes you may want to override service directly, e.g. for a servlet that handles both GET and POST request. 2. A Simple Servlet Generating Plain Text Here is a simple servlet that just generates plain text. The following section will show the more usual case where HTML is generated. 2.1 HelloWorld.java You can also download the source or try it on-line. package hall; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorld extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); out.println("Hello World"); } } 2.2 Compiling and Installing the Servlet Note that the specific details for installing servlets vary from Web server to Web server. Please refer to your Web server documentation for definitive directions. The on-line examples are running on Java Web Server (JWS) 2.0, where servlets are expected to be in a directory called servlets in the JWS installation hierarchy. However, I placed this servlet in a separate package (hall) to avoid conflicts with other servlets on this server; you'll want to do the same if you are using a Web server that is used by other people and doesn't have a good infrastructure for "virtual servers" to prevent these conflicts automatically. Thus, HelloWorld.java actually goes in a subdirectory called hall in the servlets directory. Note that setup on most other servers is similar, and the servlet and JSP examples in the tutorial have also been tested using BEA WebLogic and IBM WebSphere 3.0.
  • 5. WebSphere has an excellent mechanism for virtual servers, and it is not necessary to use packages solely to prevent name conflicts with other users. If you've never used packages before, there are two main ways to compile classes that are in packages. One way is to set your CLASSPATH to point to the directory above the one actually containing your servlets. You can them compile normally from within the directory. For example, if your base directory is C:JavaWebServerservlets and your package name (and thus subdirectory name) is hall, and you were on Windows, you'd do: DOS> set CLASSPATH=C:JavaWebServerservlets;%CLASSPATH% DOS> cd C:JavaWebServerservletshall DOS> javac YourServlet.java The first part, setting the CLASSPATH, you probably want to do permanently, rather than each time you start a new DOS window. On Windows 95/98 you'd typically put the "set CLASSPATH=..." statement in your autoexec.bat file somewhere after the line that set the CLASSPATH to point to servlet.jar and jsp.jar. On Windows NT, you'd go to the Start menu, select Settings, select Control Panel, select System, select Environment, then enter the variable and value. Note also that if your package were of the form name1.name2.name3 rather than simply name1 as here, you'd still have the CLASSPATH point to the top-level directory of your package hierarchy (the one containing name1). A second way to compile classes that are in packages is to go to the directory above the one containing your servlets, and then do "javac directoryYourServlet.java" (Windows; note the backslash) or "javac directory/YourServlet.java" (Unix; note the forward slash). For example, suppose again that your base directory is C:JavaWebServerservlets and your package name (and thus subdirectory name) is hall, and you were on Windows. In that case, you'd do the following: DOS> cd C:JavaWebServerservlets DOS> javac hallYourServlet.java Note that, on Windows, most JDK 1.1 versions of javac require a backslash, not a forward slash, after the directory name. This is fixed in JDK 1.2, but since many Web servers are configured to use JDK 1.1, many servlet authors stick with JDK 1.1 for portability. Finally, another advanced option is to keep the source code in a location distinct from the .class files, and use javac's "-d" option to install them in the location the Web server expects. 2.3 Running the Servlet With the Java Web Server, servlets are placed in the servlets directory within the main JWS installation directory, and are invoked via http://host/servlet/ServletName. Note that the directory is servlets, plural, while the URL refers to servlet, singular. Since this example was placed in the hall package, it would be invoked via http://host/servlet/hall.HelloWorld. Other Web servers may have slightly different conventions on where to install servlets and how to invoke them. Most servers also let you define aliases for servlets, so that a servlet can be invoked via http://host/any-path/any- file.html. The process for doing this is completely server-specific; check your server's documentation for details.
  • 6. 3. A Servlet that Generates HTML Most servlets generate HTML, not plain text as in the previous example. To do that, you need two additional steps: tell the browser that you're sending back HTML, and modify the println statements to build a legal Web page. The first step is done by setting the Content-Type response header. In general, headers can be set via the setHeader method of HttpServletResponse, but setting the content type is such a common task that there is also a special setContentType method just for this purpose. Note that you need to set response headers before actually returning any of the content via the PrintWriter. Here's an example: 3.1 HelloWWW.java You can also download the source or try it on-line. package hall; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWWW extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 " + "Transitional//EN">n" + "<HTML>n" + "<HEAD><TITLE>Hello WWW</TITLE></HEAD>n" + "<BODY>n" + "<H1>Hello WWW</H1>n" + "</BODY></HTML>"); }} 3.2 HelloWWW Result
  • 7. 4. Simple HTML-Building Utilities It is a bit cumbersome to generate HTML with println statements. The real solution is to use Java Server Pages (JSP), which is discussed later in this tutorial. However, for standard servlets, there are two parts of the Web page (DOCTYPE and HEAD) that are unlikely to change and thus could benefit from being incorporated into a simple utility file. The DOCTYPE line is technically required by the HTML spec, and although most major browsers ignore it, it is very useful when sending pages to formal HTML validators. These validators compare the HTML syntax of pages against the formal HTML specification, and use the DOCTYPE line to determine which version of HTML to check against. Their use is very highly recommended both for static HTML pages and for pages generated via servlets, so the use of DOCTYPE is well worth the effort, especially if it can be easily incorporated into a servlet utilities class. In many Web pages, the HEAD line contains nothing but the TITLE, although advanced developers may want to include META tags and style sheets. But for the simple case, I'll create a method that takes a title as input and returns the DOCTYPE, HEAD, and TITLE entries as output. Here's the code: 4.1 ServletUtilities.java (Download source code) package hall; public class ServletUtilities { public static final String DOCTYPE = "<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">"; public static String headWithTitle(String title) { return(DOCTYPE + "n" + "<HTML>n" + "<HEAD><TITLE>" + title + "</TITLE></HEAD>n"); } // Other utilities will be shown later... } 4.2 HelloWWW2.java (Download source code) Here's a rewrite of the HelloWWW class that uses this. package hall; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public 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") + "<BODY>n" + "<H1>Hello WWW</H1>n" + "</BODY></HTML>"); } }