Creating and Configuring Servlets
The following sections describe how to create and configure servlets.
Configuring Servlets
You define servlets as a part of a Web application in several entries in the J2EE 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.
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 url-patterns and Servlet Invocation ) showing the URLs used to invoke these servlets.
For more information on servlet mappings, such as general servlet mapping rules and conventions, refer to Section 11 of the Servlet 2.4 specification .
watermelon myservlets.watermelon
ServletServlet can be used to create a default mappings for servlets. For example, to create a default mapping to map all servlets to /myservlet/*, so the servlets can be called using http://host:port/web-app-name/myservlet/com/foo/FooServlet, add the following to your web.xml file. (The web.xml file is located in the WEB-INF directory of your Web application.)
ServletServlet weblogic.servlet.ServletServlet
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 a servlet and give it a , for example myFileServlet .
- Define the as weblogic.servlet.FileServlet .
- Using the element, map file extensions to the myFileServlet (in addition to the mappings for your default servlet). For example, if you want the myFileServlet to serve .gif files, map *.gif to the myFileServlet .
Note: | The FileServlet includes the SERVLET_PATH when determining the source filename if the docHome parameter (deprecated in this release) is not specified. As a result, it is possible to explicitly serve only files from specific directories by mapping the FileServlet to /dir/* , etc. |
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:
HelloWorld2 examples.servlets.HelloWorld2
person WebLogic Developer
Writing a Simple HTTP Servlet
The section provides 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 J2EE and Weblogic Server services such as JDBC, RMI, and JMS, in your servlet are discussed later in this document.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class HelloWorldServlet extends HttpServletThe 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/or doGet() 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 the service() method. (However, if you choose to implement the service() method, you cannot implement the doPost() or doGet() methods, unless you call super.service() at the beginning of the service() 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 an HttpServletResponse to reply to the HTTP client. The service method looks like the following:
public void service(HttpServletRequest req,
HttpServletResponse res) throws IOException
res.setContentType("text/html");PrintWriter out = res.getWriter();out.println("");
out.println("Hello World!
");
>
>
- 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.javaThe URL you use to call a servlet is determined by: (a) the name of the Web Application containing the servlet and (b) 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?parameterThe 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 the examplesWebApp 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.
Advanced Features
The preceding 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.
Complete HelloWorldServlet Example
This section provides 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.
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("");
out.println("Hello World!
");
>
>
You can find the source code and instructions for compiling and running examples in the samples/examples/servlets directory of your WebLogic Server distribution.
Calling Servlet from Servlets in Java
I will let you know the second way to calling the servlet. To call another servlet’s public methods directly, you must:
- You Should know the name of servlet that you want to call.
- Acquire access to that servlet’s Servlet object
- Calling the servlet’s public method
To get the object of servlet, use the ServletContext object’s getServlet method. Get the ServletContext object from the ServletConfig object stored in the Servlet object. An example should make this clear. When the EmployeeDetail servlet calls the BookDB servlet, the EmployeeDetail servlet obtains the EmployeeDB servlet’s Servlet object like this:
Once you have the servlet object, you can call any of that servlet’s public methods. For example, the EmployeeDetail servlet calls the EmployeeDB servlet’s get getEmployeeDetail method:
You Should take care of the few things.If your servlet is following the singlethreadedModel interface then your call violate that single threaded model. Then you should implement the first way..
public class EmployeeDetail extends HttpServlet < public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException < . EmployeeDBdatabase = (EmployeeDB) getServletConfig().getServletContext().getServlet(employeedB); EmployeeDetail bd = database.getEmployeeDetails(empId); . >>
Vinay
I am an Oracle ACE in Oracle ADF/Webcenter. Sr Java Consultant-working on Java/J2EE/Oracle ADF/Webcenter Portal/ content and Hibernate for several years. I'm an active member of the OTN JDeveloper/Webcenter forum. Passionate about learning new technologies. I am here to share my knowledge. Give your views and suggestion on [email protected] .