1.1 Servlet
1.1.1 Servlet Introduction
A servlet is a Java applet that runs on a Web server. The servlet 3.0 specification defines the implementation of the SERVLETAPI and the methods for deploying the servlet. The BES application server fully supports the Servlet 3.0 specification.
The servlet is a Java class that runs in the BES application server and can do the following using a servlet running in the BES application server:
1. Create a Dynamic Web page that can use an HTML form to get input from an end user and provide a response for this input.
2. Create a collaboration system, such as an online meeting.
3. Access various APIs and features, such as:
1) session tracking-allows websites to track the progress of users across multiple pages. This feature supports websites such as e-commerce sites that use shopping carts. The BES application server can support session persistence for the database by providing failover between the server shutdown and the sessions that are shared between the cluster servers.
2) The JDBC Driver--JDBC driver provides basic database access. With the multi-tier JDBC implementation of the BES application server, you can leverage the connection cache pool, server-side data caching, and transactions. For JDBC use, see jdbc.
3) Ejb--servlet can use EJB encapsulation sessions, data in the database, and other functions. See EJB application for EJB usage.
4) jms--can exchange messages with other Servlets and Java programs through Jms,servlet. For JMS use, see JMS.
5) Java JDK Api--servlet can use the standard Java JDK API.
6) Forward Request--servlet can forward the request to another servlet or resource.
4. Any servlet specification-compliant servlet can be easily deployed to the BES application server.
An HTTP servlet is a special type of servlet that typically handles HTTP requests and provides HTTP responses in the form of HTML pages. The BES HTTP servlet also has access to other tools for databases, EJBS, JMS, HTTP sessions, and BES application servers.
1.1.2 Writing a servlet
The Servlet API provides the Javax.servlet.Servlet interface, which must be implemented by all servlets. Servletapi also gives the servlet implementation of the HTTP protocol-- Javax.servlet.http.HTTPServlet, you can write your own servlet,httpservlet by inheriting the HttpServlet class to read the HTTP header and write HTML encoding to pass the response to the browser client.
The servlet 3.0 specification can use annotation @webservlet to define a servlet, and classes that use annotations @webservlet annotations must inherit the Javax.servlet.http.HTTPServlet class. The following code fragment defines a servlet that maps to a URL pattern of/sendmailservlet:
Importjavax.servlet.annotation.WebServlet;
Import Javax.servlet.http.HttpServlet;
@WebServlet ("/sendmailservlet")
public class Sendmailservlet Extendshttpservlet {
Using the annotation @webservlet, you can omit the configuration servlet in Web. XML (Web-fragment.xml). The configuration in Web. XML (Web-fragment.xml) takes precedence if the implementation class of a servlet is annotated @webservlet and the servlet is also configured in Web. XML (Web-fragment.xml). Common configuration properties for annotation @webservlet are as follows:
Table 1?1 Annotations @webservlet Common Configuration
|
Property |
Use |
Default value |
|
Name |
Specify the name of the servlet |
“” |
|
Value |
Specifies the URL pattern for the request servlet, equivalent to Urlpatterns |
{} |
|
Urlpatterns |
Specify the URL pattern for the request servlet |
{} |
|
Loadonstartup |
Specifies whether the servlet is initialized when the Web container starts. |
-1 |
|
InitParams |
Specifying the initialization parameters for a servlet |
{} |
|
asyncsupported |
Specifies whether the servlet supports asynchronous mode |
False |
Cases:
@WebServlet (name= "Sendmailservlet",
Urlpatterns= "/sendmailservlet",
Loadonstartup=3,
InitParams ={
@WebInitParam (name= "greeting", value= "Welcome"),
@WebInitParam (name= "name", value= "Developer")},
Asyncsupported=true)
2.1.2.1 Initialize servlet
Typically, the BES application server initializes the servlet when the first request is made to the servlet, and when the servlet is initialized, the BES application server executes the servlet's init () method. Parameters defined in the Web app are passed to the servlet during initialization, for example, two initialization parameters are defined in note @webservlet on the class that implements the servlet: greeting (value welcome) and name (value developer):
@WebServlet (...,
initparams={
@WebInitParam (name= "greeting", value= "Welcome"),
@WebInitParam (name= "name", value= "Developer")})
You can also define the above initialization parameters to the Web App standard deployment descriptor, XML (Web-fragment.xml):
<servlet>
......
<init-param>
<param-name>greeting</param-name>
<param-value>welcome</param-value>
</init-param>
<init-param>
<param-name>name</param-name>
<param-value>developer</param-value>
</init-param>
</servlet>
The init () method of the servlet executes all initialization work that the BES application server needs to perform when it loads the servlet. The default init () method performs all initialization work that the BES application server requires, and can be overridden by overriding the Servlet's init () method to implement the required initialization functions, such as initializing counters, creating database connections, and so on. If you need to replace init (), call Super.init () first to perform the default initialization operation first.
2.1.2.2 processing requests, returning responses
The main function of a servlet is to accept HTTP requests from a Web browser and return an HTTP response. This work is done by the servlet's service () method. The service () method includes the request object HttpServletRequest to receive data from the client and the response object HttpServletResponse used to create the output.
HTTP requests from a Web browser can contain information about form data, client information, Cookies, sessions, and query parameters in addition to URLs, and HttpServlet can obtain this information from the request through the HttpServletRequest object.
Using a HttpServletResponse object that provides a response to the client, you can set several servlet attributes that can be converted to HTTP header information, such as setting the content type, character encoding, caching, and so on, or you can get the output stream and write the response content to the output stream in HTML format.
2.1.2.3 Request Scheduling
A servlet can pass a request to another resource, such as a servlet, JSP, or HTML page, which is called a request dispatch. When scheduling a request, use the include () or forward () method of the RequestDispatcher interface. By using RequestDispatcher, you can avoid sending HTTP redirect responses back to the client. RequestDispatcher will pass the HTTP request to the requested resource.
To schedule a request to a specific resource, do the following:
1. Get a reference to ServletContext:
ServletContext sc = getservletconfig (). Getservletcontext ();
2. Locate the RequestDispatcher object using one of the following methods:
RequestDispatcher rd = sc.getrequestdispatcher (String path);
In this method, path is the root directory relative to the Web App.
RequestDispatcher rd = sc.getnameddispatcher (String name);
The name in this method is the Web App standard deployment descriptor for the servlet specified by using the <servlet-name> element in the XML.
RequestDispatcher rd = servletrequest.getrequestdispatcher (String path);
This method is similar to the Servletcontext.getrequestdispatcher (String path) method, except that it allows path relative to the current servlet. If the path starts with a/character, it is interpreted as relative to the Web App. By requesting the appropriate URL for a resource in the Getrequestdispatcher () method, you can get RequestDispatcher for any HTTP resource in your Web app, including HTTP Servlets, JSP pages, or plain HTML pages. Forwards the request to another servlet using the returned RequestDispatcher object.
3. Use the appropriate method to forward or include the request. The uses for forwarding and including requests are:
1) Rd.forward (request,response);
2) Rd.include (request,response);
1.1.3 Configuring Servlets
After you have written the servlet, you can annotate the name of the servlet and the URL pattern for accessing the servlet by annotating the annotation @webservlet directly on the class. The Name property of the annotation @webservlet defines the names of the servlet, the Urlpatterns property defines the URL pattern that invokes the servlet, and the InitParams property defines the initialization parameters of the servlet:
@WebServlet (name= "Sendmailservlet",
Urlpatterns= "/sendmailservlet",
initparams={
@WebInitParam (name= "greeting", value= "Welcome"),
@WebInitParam (name= "name", value= "Developer")})
You can also configure the access URL for the servlet in Web. XML (Web-fragment.xml). The <servlet> element defines the name of the servlet, specifies the compiled class that executes the servlet, and uses the Init-param element to define the initialization attributes of the servlet. The <servlet-mapping> element defines the URL pattern that calls this servlet. For example:
<!--servlet declaration, take an application-wide unique name for the Servlet class--
<servlet>
<servlet-name>MailServlet</servlet-name>
<servlet-class>
Samples.javamail.servlet.SendMailServlet
</servlet-class>
<init-param>
<param-name>greeting</param-name>
<param-value>Welcome</param-value>
</init-param>
</servlet>
<!--Configure the URL for the declared servlet class, all/mail requests will be processed by Mailservlet-
<servlet-mapping>
<servlet-name>MailServlet</servlet-name>
<url-pattern>/mail</url-pattern>
</servlet-mapping>
1.1.4 Access servlet
When you access or reference a servlet in a web app, the URL is constructed as follows:
Http://server:port/context-root/requestPath?requestParameters
Table 1?2 URL Construction element description for accessing web Apps
|
Elements |
Description |
|
Server:port |
The host name and the listening port number that service the app. |
|
Context-root |
The access root path of the app. |
|
Requestpath |
The URL format configured for the servlet in Web. Xml. |
|
Requestparameters |
Optional HTTP request parameter name value pairs. |
Besappserver in Servlet3.0 development use