3 Creating and Configuring Servlets
This chapter includes the following sections:
- What's New and Changed in Servlets
These sections summarize the changes in the Servlet programming model and requirements between Servlet 4.0 and 3.1. - Configuring Servlets
Learn how to configure servlets using Jakarta EE metadata annotations versus deployment descriptors, and how to use servlet mapping in a Web application. - Setting Up a Default Servlet
Each Web application has a default servlet. This default servlet can be a servlet that you specify, or, if you do not specify a default servlet, WebLogic Server uses an internal servlet called theFileServlet
as the default servlet. - Servlet Initialization Attributes
You define initialization attributes for servlets in the Web application deployment descriptor,web.xml
, in theinit-param
element of theservlet
element, usingparam-name
andparam-value
tags. Theweb.xml
file is located in theWEB-INF
directory of your Web application. - Writing a Simple HTTP Servlet
Examine a procedure for writing a simple HTTP servlet, which prints out the messageHello World
. - Advanced Features
Examine the steps create a basic servlet. You will probably also use more advanced features of servlets. - Complete HelloWorldServlet Example
Examine the complete Java source code for the example used in the preceding procedure. The example is a simple servlet that provides a response to an HTTP request. - Debugging Servlet Containers
Learn about the debugging options available in the WebLogic Server servlet container:
What's New and Changed in Servlets
These sections summarize the changes in the Servlet programming model and requirements between Servlet 4.0 and 3.1.
Parent topic: Creating and Configuring Servlets
What's New and Changed in Servlet 4.0
WebLogic Server supports the Jakarta Servlet 4.0 specification (see https://jakarta.ee/specifications/servlet/4.0/
), which introduces the following new features:
-
Support for HTTP/2—HTTP/2 enables a more efficient use of network resources and a reduced perception of latency by introducing header field compression and allowing multiple concurrent exchanges on the same connection. It also introduces an unsolicited push of representations from servers to clients.
-
Server Push—Server push is the most visible of the improvements in HTTP/2 to appear in the servlet API. All of the new features in HTTP/2, including server push, are aimed at improving the perceived performance of the web browsing experience. Server push is the ability of the server to anticipate what will be needed by the client in advance of the client’s request. It lets the server pre-populate the browser’s cache in advance of the browser asking for the resource to put in the cache. For example, servers might know that whenever a browser requests
index.html
, it will shortly thereafter requestheader.gif
,footer.gif
, andstyle.css
. Servers can preemptively start sending the bytes of these assets along with the bytes of theindex.html
.To use server push, obtain a reference to aPushBuilder
from anHttpServletRequest
, edit the builder as desired, then callpush()
.PushBuilder pb = req.newPushBuilder(); pb.path("bar.jpg"); pb.push();
-
HTTP/2 configuration parameters via a new
Http2ConfigMBean
.
-
-
HTTP Trailer support—HTTP trailer is a collection of a special type of HTTP headers that comes after the response body. The trailer response header allows the sender to include additional fields at the end of chunked messages in order to supply metadata that might be dynamically generated while the message body is sent, such as a message integrity check, digital signature, or post-processing status.
-
Mapping Discovery—Every mapping that causes a servlet to be activated, regardless of whether or not servlet filters are involved, is discoverable at runtime using the Servlet Mapping API. The method
getHttpServletMapping()
onHttpServletRequest
returns anHttpServletMapping
implementation that provides information for the mapping that caused the current servlet to be invoked. As with the included and forwarded request parameters,HttpServletMapping
is not available for servlets that have been obtained with a call toServletContext.getNamedDispatcher()
. -
Servlet examples—When you install WebLogic Server examples, the examples source code is placed in the
EXAMPLES_HOME\examples\src\examples\javaee8\servlet
directory. The default path isORACLE_HOME\wlserver\samples\server
. From this directory, you can access the source code and instruction files for the Servlet 4.0 code examples without having to set up the samples domain.The
ORACLE_HOME\user_projects\domains\wl_server
directory contains the WebLogic Server examples domain; it contains your applications and the XML configuration files that define how your applications and Oracle WebLogic Server will behave, as well as startup and environment scripts. For more information about the WebLogic Server code examples, see Sample Applications and Code Examples in Understanding Oracle WebLogic Server.-
Server Push - demonstrates how to build a HTTP/2 server push request and push a resource to the client.
EXAMPLES_HOME/examples/src/examples/javaee8/servlet/server-push
-
HTTP Trailer - demonstrates how to use the HTTP trailer API. The servlet consumes HTTP trailer from the request and produces HTTP trailer for the response.
EXAMPLES_HOME/examples/src/examples/javaee8/servlet/trailer
-
Mapping Discovery - demonstrates how to use
HttpServletMapping
to handle a series of hyperlinks that explore the various values for the properties ofHttpServletMapping
.EXAMPLES_HOME/examples/src/examples/javaee8/servlet/mapping-discovery
-
Parent topic: What's New and Changed in Servlets
What Was New and Changed in Servlet 3.1
The Servlet 3.1 specification (see https://jcp.org/en/jsr/detail?id=340
) introduced the following features:
-
Support added for non-blocking I/O reads and writes—Servlet 3.0 allowed asynchronous request processing but only traditional I/O was permitted, which restricted scalability of your applications because threads associated with client requests could be sitting idle due to input/output considerations. Servlet 3.1 supports non-blocking I/O for read and write listeners, which allows you to build scalable applications.
-
Supports HTTP protocol upgrade processing—HTTP/1.1 allows the client to specify additional communication protocols that it supports and would like to use. Servlet 3.1 supports the HTTP protocol upgrade functionality in servlets.
-
Enhanced security by handling uncovered HTTP methods—The
deny-uncovered-http-methods
flag can be set in an application'sweb.xml
file, which forces the container to deny any HTTP protocol method when it is used with a request URL for which the HTTP method is uncovered at the combined security constraint that applies to theurl-pattern
that is the best match for the request URL. -
New Java EE 7 servlet examples—When you install WebLogic Server complete with the examples, the examples source code is placed in the
EXAMPLES_HOME\examples\src\examples\javaee7
directory. The default path isORACLE_HOME\wlserver\samples\server
. From this directory, you can access the source code and instruction files for the Servlet 3.1 code examples without having to set up the samples domain.The
ORACLE_HOME\user_projects\domains\wl_server
directory contains the WebLogic Server examples domain; it contains your applications and the XML configuration files that define how your applications and Oracle WebLogic Server will behave, as well as startup and environment scripts. For more information about the WebLogic Server code examples, see Sample Applications and Code Examples in Understanding Oracle WebLogic Server.-
Using HTTP Protocol Upgrade API – demonstrates how to use the HTTP Protocol Upgrade API that allows the client to specify additional communication protocols.
EXAMPLES_HOME/examples/src/examples/javaee7/servlet/http-upgrade
-
Using the Non-Blocking I/O ReadListener – demonstrates how to use the
ReadListener
interface in servlets for reading from a request in a non-blocking manner.EXAMPLES_HOME/examples/src/examples/javaee7/servlet/non-blocking-io-read
-
Using the Non-Blocking I/O WriteListener – demonstrates how to use the
WriteListener
interface in servlets for writing to a request in a non-blocking manner.EXAMPLES_HOME/examples/src/examples/javaee7/servlet/non-blocking-io-write
-
Changing the Session ID – demonstrates how to change the session ID using the
HttpServletRequest
API.EXAMPLES_HOME/examples/src/examples/javaee7/servlet/session-id-change
-
Handling Uncovered HTTP Methods – demonstrates how to deny uncovered HTTP methods:
EXAMPLES_HOME/examples/src/examples/javaee7/servlet/uncovered-http-method
-
Parent topic: What's New and Changed in Servlets
Configuring Servlets
Learn how to configure servlets using Jakarta EE metadata annotations versus deployment descriptors, and how to use servlet mapping in a Web application.
Servlet Annotations
With Jakarta EE metadata annotations, the standard web.xml
deployment descriptor is optional. The servlet specification states annotations can be defined on certain Web components, such as servlets, filters, listeners, and tag handlers. The annotations are used to declare dependencies on external resources. The container will detect annotations on such components and inject necessary dependencies before the component's life cycle methods are invoked. See WebLogic Annotation for Web Components.
However, you can also define servlets as a part of a Web application in several entries in the standard Web application deployment descriptor, web.xml
. The web.xml
file is located in the WEB-INF
directory of your Web application.
The first entry, under the root servlet
element in web.xml
, defines a name for the servlet and specifies the compiled class that executes the servlet. (Or, instead of specifying a servlet class, you can specify a JSP.) The servlet
element also contains definitions for initialization attributes and security roles for the servlet.
The second entry in web.xml
, under the servlet-mapping
element, defines the URL pattern that calls this servlet.
Parent topic: Configuring Servlets
Servlet Mapping
Servlet mapping controls how you access a servlet. The following examples demonstrate how you can use servlet mapping in your Web application. In the examples, a set of servlet configurations and mappings (from the web.xml
deployment descriptor) is followed by a table (see Table 3-1) showing the URLs used to invoke these servlets.
Example 3-1 Servlet Mapping Example
<servlet> <servlet-name>watermelon</servlet-name> <servlet-class>myservlets.watermelon</servlet-class> </servlet> <servlet> <servlet-name>garden</servlet-name> <servlet-class>myservlets.garden</servlet-class> </servlet> <servlet> <servlet-name>list</servlet-name> <servlet-class>myservlets.list</servlet-class> </servlet> <servlet> <servlet-name>kiwi</servlet-name> <servlet-class>myservlets.kiwi</servlet-class> </servlet> <servlet-mapping> <servlet-name>watermelon</servlet-name> <url-pattern>/fruit/summer/*</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>garden</servlet-name> <url-pattern>/seeds/*</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>list</servlet-name> <url-pattern>/seedlist</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>kiwi</servlet-name> <url-pattern>*.abc</url-pattern> </servlet-mapping>
Table 3-1 url-patterns and Servlet Invocation
URL | Servlet Invoked |
---|---|
http://host:port/mywebapp/fruit/summer/index.html |
watermelon |
http://host:port/mywebapp/fruit/summer/index.abc |
watermelon |
http://host:port/mywebapp/seedlist |
list |
http://host:port/mywebapp/seedlist/index.html |
The default servlet, if configured, or an HTTP 404 File Not Found error message. If the mapping for the |
http://host:port/mywebapp/seedlist/pear.abc |
kiwi If the mapping for the list servlet had been |
http://host:port/mywebapp/seeds |
garden |
http://host:port/mywebapp/seeds/index.html |
garden |
http://host:port/mywebapp/index.abc |
kiwi |
Parent topic: Configuring Servlets
Setting Up a Default Servlet
Each Web application has a default servlet. This default servlet can be a servlet that you specify, or, if you do not specify a default servlet, WebLogic Server uses an internal servlet called the FileServlet
as the default servlet.
You can register any servlet as the default servlet. Writing your own default servlet allows you to use your own logic to decide how to handle a request that falls back to the default servlet.
Setting up a default servlet replaces the FileServlet
and should be done carefully because the FileServlet
is used to serve most files, such as text files, HTML file, image files, and more. If you expect your default servlet to serve such files, you will need to write that functionality into your default servlet.
To set up a user-defined default servlet:
-
Define your servlet as described in Configuring How a Client Accesses a Web Application.
-
Add a servlet-mapping with url-pattern = "
/
" as follows:<servlet-mapping> <servlet-name>MyOwnDefaultServlet</servlet-name> <url-pattern>/myservlet/*(</url-pattern> </servlet-mapping>
-
If you still want the
FileServlet
to serve files with other extensions:-
Define a servlet and give it a
<servlet-name>
, for examplemyFileServlet
. -
Define the
<servlet-class>
asweblogic.servlet.FileServlet
. -
Using the
<servlet-mapping>
element, map file extensions to themyFileServlet
(in addition to the mappings for your default servlet). For example, if you want themyFileServlet to serve.gif
files, map*.gif
to themyFileServlet
.Note:
The
FileServlet
includes theSERVLET_PATH
when determining the source filename if thedocHome
parameter (deprecated in this release) is not specified. As a result, it is possible to explicitly serve only files from specific directories by mapping theFileServlet to /dir/*
, etc.
-
Parent topic: Creating and Configuring Servlets
Servlet Initialization Attributes
You define initialization attributes for servlets in the Web application deployment descriptor, web.xml
, in the init-param
element of the servlet
element, using param-name
and param-value
tags. The web.xml
file is located in the WEB-INF
directory of your Web application.
For example:
Example 3-2 Example of Configuring Servlet Initialization Attributes in web.xml
<servlet> <servlet-name>HelloWorld2</servlet-name> <servlet-class>examples.servlets.HelloWorld2</servlet-class> <init-param> <param-name>greeting</param-name> <param-value>Welcome</param-value> </init-param> <init-param> <param-name>person</param-name> <param-value>WebLogic Developer</param-value> </init-param> </servlet>
Parent topic: Creating and Configuring Servlets
Writing a Simple HTTP Servlet
Examine a procedure for writing a simple HTTP servlet, which prints out the message Hello World
.
A complete code example (the HelloWorldServlet
) illustrating these steps is included at the end of this section. Additional information about using various Jakarta EE and WebLogic Server services such as JDBC, RMI, and JMS, in your servlet are discussed later in this document.
-
Import the appropriate package and classes, including the following:
import javax.servlet.*; import javax.servlet.http.*; import java.io.*;
-
Extend
javax.servlet.http.HttpServlet
. For example:public class HelloWorldServlet extends HttpServlet{
-
Implement a
service()
method.The main function of a servlet is to accept an HTTP request from a Web browser, and return an HTTP response. This work is done by the
service()
method of your servlet. Service methods include response objects used to create output and request objects used to receive data from the client.You may have seen other servlet examples implement the
doPost()
and/ordoGet()
methods. These methods reply only to POST or GET requests; if you want to handle all request types from a single method, your servlet can simply implement theservice()
method. (However, if you choose to implement theservice()
method, you cannot implement thedoPost()
ordoGet()
methods, unless you callsuper.service()
at the beginning of theservice()
method.) The HTTP servlet specification describes other methods used to handle other request types, but all of these methods are collectively referred to as service methods.All the service methods take the same parameter arguments. An
HttpServletRequest
provides information about the request, and your servlet uses anHttpServletResponse
to reply to the HTTP client. The service method looks like the following:public void service(HttpServletRequest req, HttpServletResponse res) throws IOException {
-
Set the content type, as follows:
res.setContentType("text/html");
-
Get a reference to a
java.io.PrintWriter
object to use for output, as follows:PrintWriter out = res.getWriter();
-
Create some HTML using the
println()
method on thePrintWriter
object, as shown in the following example:out.println("<html><head><title>Hello World!</title></head>"); out.println("<body><h1>Hello World!</h1></body></html>"); } }
-
Compile the servlet, as follows:
-
Set up a development environment shell with the correct classpath and path settings.
-
From the directory containing the Java source code for your servlet, compile your servlet into the
WEB-INF/classes
directory of the Web application that contains your servlet. For example:javac -d /myWebApplication/WEB-INF/classes myServlet.java
-
-
Deploy the servlet as part of a Web application hosted on WebLogic Server.
-
Call the servlet from a browser.
The URL you use to call a servlet is determined by:
-
The name of the Web application containing the servlet and
-
The name of the servlet as mapped in the deployment descriptor of the Web application. Request parameters can also be included in the URL used to call a servlet.
Generally the URL for a servlet conforms to the following:
http://host:port/webApplicationName/mappedServletName?parameter
The components of the URL are defined as follows:
-
host
is the name of the machine running WebLogic Server. -
port
is the port at which the above machine is listening for HTTP requests. -
webApplicationName
is the name of the Web application containing the servlet. -
parameters
are one or more name-value pairs containing information sent from the browser that can be used in your servlet.
For example, to use a Web browser to call the
HelloWorldServlet
(the example featured in this document), which is deployed in theexamplesWebApp
and served from a WebLogic Server running on your machine, enter the following URL:http://localhost:7001/examplesWebApp/HelloWorldServlet
The
host:port
portion of the URL can be replaced by a DNS name that is mapped to WebLogic Server. -
Parent topic: Creating and Configuring Servlets
Advanced Features
Examine the steps create a basic servlet. You will probably also use more advanced features of servlets.
-
Handling HTML form data—HTTP servlets can receive and process data received from a browser client in HTML forms.
-
Application design—HTTP servlets offer many ways to design your application. The following sections provide detailed information about writing servlets:
-
Initializing a servlet—if your servlet needs to initialize data, accept initialization arguments, or perform other actions when the servlet is initialized, you can override the
init()
method. -
Use of sessions and persistence in your servlet—sessions and persistence allow you to track your users within and between HTTP sessions. Session management includes the use of cookies. See the following sections:
-
Use of WebLogic services in your servlet—WebLogic Server provides a variety of services and APIs that you can use in your Web applications. These services include JDBC drivers, JDBC database connection pools, Jakarta Messaging (JMS), Enterprise JavaBeans (EJB), and Remote Method Invocation (RMI). See the following sections:
Parent topic: Creating and Configuring Servlets
Complete HelloWorldServlet Example
Examine the complete Java source code for the example used in the preceding procedure. The example is a simple servlet that provides a response to an HTTP request.
Later in this document, this example is expanded to illustrate how to use HTTP parameters, cookies, and session tracking.
Example 3-3 HelloWorldServlet.java
import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class HelloWorldServlet extends HttpServlet { public void service(HttpServletRequest req, HttpServletResponse res) throws IOException { // Must set the content type first res.setContentType("text/html"); // Now obtain a PrintWriter to insert HTML into PrintWriter out = res.getWriter(); out.println("<html><head><title>" + "Hello World!</title></head>"); out.println("<body><h1>Hello World!</h1></body></html>"); } }
You can find the source code and instructions for compiling and running examples in the ORACLE_HOME\wlserver\samples\server\examples\src\examples\splitdir\helloWorldEar
directory of your WebLogic Server distribution, whereORACLE_HOME
represents the directory in which you installed WebLogic Server. For more information about the WebLogic Server code examples, see Sample Applications and Code Examples in Understanding Oracle WebLogic Server.
Parent topic: Creating and Configuring Servlets
Debugging Servlet Containers
Learn about the debugging options available in the WebLogic Server servlet container:
Parent topic: Creating and Configuring Servlets
Disabling Access Logging
Logging access for servlets can be expensive with regard to server performance. Therefore, in cases where access logging is not required, you can improve performance by disabling logging to the access log file.
Parent topic: Debugging Servlet Containers
Usage
The optional access-logging-disabled
property in the container-descriptor
in weblogic.xml
can be used to specify whether access logging for an underlying Web application is disabled.
-
If the property is set as
true
, then application accesses are not logged. -
If the property is not defined or is set as
false
, then application accesses are logged.Note:
The
access-logging-disabled
property functions at the Web application level. Therefore, if it is defined in a Web application, it does not affect other Web applications. This property works under both development mode and production mode.Note:
To disable logging for internal applications, use this property,
weblogic.servlet.logging.LogInternalAppAccess=false
.
Parent topic: Disabling Access Logging
Example
The following example demonstrates how to disable access logging:
<?xml version="1.0" encoding="ISO-8859-1"?> <weblogic-web-app xmlns="http://xmlns.oracle.com/weblogic/weblogic-web-app"> <container-descriptor> <access-logging-disabled>true</access-logging-disabled> </container-descriptor> </weblogic-web-app>
Parent topic: Disabling Access Logging
Debugging Specific Sessions
Tracking session change is very helpful when developing applications, especially for replicated sessions. Although you can utilize HttpSessionAttributeListener
to track session changes at the Web application level, developers need a finer-grained debugging option to track session changes during a specific request.
Parent topic: Disabling Access Logging
Usage
The wl_debug_session
request attribute or a same-named session attribute can log attribute changes in the current session. When either flag is used, the container logs the modifications of the underlying session in the server log.
You can enable specific session debugging by using either of the following methods:
-
Set the
wl_debug_session
attribute to the current session, as follows: -
session.setAttribute('wl_debug_session', Boolean.TRUE);
-
Use the
wl_debug_session
attribute in the request query string as the indicator. The container adds awl_debug_session
session attribute to the current session, as shown in the following example:http://localhost/foocontext/foo?wl_debug_session
To stop debugging a session, you can simply remove the wl_debug_session
attribute.
Note:
This feature is available only in development mode. The severity of the debug message is at the debug
level. You need to adjust the severity of the logger to debug
or lower for the system logger to output the debug message to the server log file.
Parent topic: Disabling Access Logging
Tracking a Request Handle Footprint
Tracking a request handle footprint is very helpful while in application development mode. For example, when debugging an application, you need to know many pieces of information. This includes such information as: what request is received, how it is dispatched, what session it is bound to it, when the servlet is invoked, and what response is sent. Finally, when a ServletException
occurs, you need a way to link the exception to corresponding request to find the root cause of the error.
Parent topic: Debugging Servlet Containers
Usage
The WebLogic Server servlet container provides more detailed log messages during request handling to better describe each milestone in a request flow. No additional configuration changes are required other than enabling the DebugHttp
logger.
You can then find the footprint of a request handle in the server log. Once in production mode, you should disable DebugHttp
logger to maximize server performance.
Parent topic: Tracking a Request Handle Footprint