Skip to content Skip to sidebar Skip to footer

Servlet if Value Is Return and Start Over Again

Developing Spider web Applications, Servlets, and JSPs for Oracle WebLogic Server

Content starts here

Servlet Programming Tasks

The following sections draw how to write HTTP servlets in a WebLogic Server environs:

  • Initializing a Servlet
  • Providing an HTTP Response
  • Retrieving Client Input
  • Using Cookies in a Servlet
  • Response Caching
  • Using WebLogic Services from an HTTP Servlet
  • Accessing Databases
  • Threading Bug in HTTP Servlets
  • Dispatching Requests to Another Resource
  • Proxying Requests to Another Web Server
  • Clustering Servlets
  • Referencing a Servlet in a Web Awarding
  • URL Design Matching
  • The SimpleApacheURLMatchMap Utility
  • A Futurity Response Model for HTTP Servlets

Initializing a Servlet

Usually, WebLogic Server initializes a servlet when the first request is fabricated for the servlet. Later, if the servlet is modified, the destroy() method is chosen on the existing version of the servlet. And so, after a asking is made for the modified servlet, the init() method of the modified servlet is executed. For more data, see Servlet Best Practices.

When a servlet is initialized, WebLogic Server executes the init() method of the servlet. Once the servlet is initialized, it is non initialized again until you restart WebLogic Server or modify the servlet lawmaking. If you choose to override the init() method, your servlet can perform certain tasks, such as establishing database connections, when the servlet is initialized. (See Overriding the init() Method.)

Initializing a Servlet when WebLogic Server Starts

Rather than having WebLogic Server initialize a servlet when the showtime request is made for it, y'all tin first configure WebLogic Server to initialize a servlet when the server starts. You do this by specifying the servlet course in the load-on-startup element in the J2EE standard Spider web Application deployment descriptor, web.xml. The order in which resources within a Web application are initialized is as follows:

  1. ServletContextListeners—the contextCreated() callback for ServletContextListeners registered for this Spider web awarding.
  2. ServletFilters init() method.
  3. Servlet init() method, marked as load-on-startup in web.xml.

You can laissez passer parameters to an HTTP servlet during initialization by defining these parameters in the Spider web Application containing the servlet. You tin use these parameters to pass values to your servlet every time the servlet is initialized without having to rewrite the servlet.

For case, the post-obit entries in the J2EE standard Web Application deployment descriptor, spider web.xml, ascertain two initialization parameters: greeting, which has a value of Welcome and person, which has a value of WebLogic Programmer.

<servlet>
...
<init-param>
<description>The salutation</description>
<param-name>greeting</param-name>
<param-value>Welcome</param-value>
</init-param>
<init-param>
<description>name</description>
<param-name>person</param-name>
<param-value>WebLogic Programmer</param-value>
</init-param>
</servlet>

To retrieve initialization parameters, call the getInitParameter(String name) method from the parent javax.servlet.GenericServlet class. When passed the proper noun of the parameter, this method returns the parameter's value as a String.

Overriding the init() Method

You can have your servlet execute tasks at initialization time past overriding the init() method. The following code fragment reads the <init-param> tags that define a greeting and a proper noun in the J2EE standard Web Application deployment descriptor, web.xml:

Cord defaultGreeting;
String defaultName;
public void init(ServletConfig config)          
throws ServletException {
if ((defaultGreeting = getInitParameter("greeting")) == nothing)
defaultGreeting = "Hello";
          if ((defaultName = getInitParameter("person")) == zero)
defaultName = "Earth";
}

The values of each parameter are stored in the class instance variables defaultGreeting and defaultName. The first lawmaking tests whether the parameters accept zilch values, and if nothing values are returned, provides appropriate default values.

You tin and so use the service() method to include these variables in the response. For case:

          out.print("<body><h1>");
out.println(defaultGreeting + " " + defaultName + "!");
out.println("</h1></body></html>");

The init() method of a servlet does whatever initialization work is required when WebLogic Server loads the servlet. The default init() method does all of the initial work that WebLogic Server requires, and so you practice not need to override it unless you take special initialization requirements. If you practice override init(), first telephone call super.init() so that the default initialization actions are done starting time.


Providing an HTTP Response

This section describes how to provide a response to the client in your HTTP servlet. Deliver all responses by using the HttpServletResponse object that is passed every bit a parameter to the service() method of your servlet.

  1. Configure the HttpServletResponse.
  2. Using the HttpServletResponse object, you lot can fix several servlet properties that are translated into HTTP header information:

    • At a minimum, set the content type using the setContentType() method before you obtain the output stream to which you write the page contents. For HTML pages, set the content blazon to text/html. For case:
    • res.setContentType("text/html");
    • (optional) You can likewise use the setContentType() method to set the character encoding. For example:
    • res.setContentType("text/html;ISO-88859-4");
    • Set header attributes using the setHeader() method. For dynamic responses, it is useful to set the "Pragma" attribute to no-enshroud, which causes the browser to always reload the folio and ensures the data is current. For example:
    • res.setHeader("Pragma", "no-enshroud");
  3. Etch the HTML page.
  4. The response that your servlet sends dorsum to the customer must look like regular HTTP content, essentially formatted as an HTML page.Your servlet returns an HTTP response through an output stream that yous obtain using the response parameter of the service() method. To send an HTTP response:

    1. Obtain an output stream by using the HttpServletResponse object and 1 of the methods shown in the post-obit 2 examples:
    • PrintWriter out = res.getWriter();
    • ServletOutputStream out = res.getOutputStream();
    • You can utilize both PrintWriter and ServletOutputStream in the same servlet (or in some other servlet that is included in a servlet). The output of both is written to the same buffer.

    1. Write the contents of the response to the output stream using the print() method. You can use HTML tags in these statements. For instance:
    2. out.print("<html><head><championship>My Servlet</championship>");
      out.impress("</head><body><h1>");
      out.print("Welcome");
      out.print("</h1></body></html>");

      Whatever time yous impress data that a user has previously supplied, Oracle recommends that you remove whatsoever HTML special characters that a user might have entered. If you exercise not remove these characters, your Spider web site could be exploited by cross-site scripting. For more than information, refer to Securing Client Input in Servlets.

      Do not close the output stream past using the close() method, and avoid flushing the contents of the stream. If you do not close or flush the output stream, WebLogic Server can take advantage of persistent HTTP connections, as described in the next step.

  5. Optimize the response.
  6. Past default, WebLogic Server attempts to use HTTP persistent connections whenever possible. A persistent connection attempts to reuse the same HTTP TCP/IP connexion for a series of communications between client and server. Application performance improves because a new connection need not be opened for each request. Persistent connections are useful for HTML pages containing many in-line images, where each requested epitome would otherwise crave a new TCP/IP connection.

    Using the WebLogic Server Administration Panel, y'all can configure the corporeality of time that WebLogic Server keeps an HTTP connection open.

    WebLogic Server must know the length of the HTTP response in club to establish a persistent connection and automatically adds a Content-Length property to the HTTP response header. In gild to determine the content length, WebLogic Server must buffer the response. Nevertheless, if your servlet explicitly flushes the ServletOutputStream, WebLogic Server cannot determine the length of the response and therefore cannot apply persistent connections. For this reason, y'all should avoid explicitly flushing the HTTP response in your servlets.

    Yous may determine that, in some cases, information technology is better to flush the response early to display information in the customer before the page has completed; for example, to display a imprint advertisement while some time-consuming folio content is calculated. Conversely, you may desire to increment the size of the buffer used by the servlet engine to accommodate a larger response earlier flushing the response. You tin can manipulate the size of the response buffer by using the related methods of the javax.servlet.ServletResponse interface. For more data, meet the Servlet ii.4 specification.

    The default value of the WebLogic Server response buffer is 12K and the buffer size is internally calculated in terms of CHUNK_SIZE where CHUNK_SIZE = 4088 bytes; if the user sets 5Kb the server rounds the request up to the nearest multiple of CHUNK_SIZE which is 2. and the buffer is ready to 8176 bytes.


Retrieving Client Input

The HTTP servlet API provides a interface for retrieving user input from Web pages.

An HTTP request from a Web browser can contain more than the URL, such as information nearly the client, the browser, cookies, and user query parameters. Utilize query parameters to carry user input from the browser. Use the GET method appends parameters to the URL address, and the POST method includes them in the HTTP asking torso.

HTTP servlets need not deal with these details; data in a asking is bachelor through the HttpServletRequest object and can be accessed using the request.getParameter() method, regardless of the send method.

Read the following for more detailed information about the ways to ship query parameters from the customer:

  • Encode the parameters directly into the URL of a link on a page. This approach uses the GET method for sending parameters. The parameters are appended to the URL after a ? grapheme. Multiple parameters are separated by a & character. Parameters are always specified in name=value pairs then the order in which they are listed is not important. For example, yous might include the post-obit link in a Web page, which sends the parameter colour with the value royal to an HTTP servlet called ColorServlet:
  • <a href=
       "http://localhost:7001/myWebApp/ColorServlet?color=purple">
       Click Hither For Majestic!</a>
  • Manually enter the URL, with query parameters, into the browser location field. This is equivalent to clicking the link shown in the previous example.
  • Query the user for input with an HTML course. The contents of each user input field on the form are sent as query parameters when the user clicks the form's Submit button. Specify the method used past the course to send the query parameters (Postal service or Go) in the <FORM> tag using the METHOD="GET|Post" aspect.

Query parameters are always sent in name = value pairs, and are accessed through the HttpServletRequest object. You can obtain an Enumeration of all parameter names in a query, and fetch each parameter value by using its parameter name. A parameter usually has only one value, but information technology tin also hold an array of values. Parameter values are always interpreted as Strings, so you may need to cast them to a more appropriate type.

The following sample from a service() method examines query parameter names and their values from a form. Note that request is the HttpServletRequest object.

          Enumeration params = request.getParameterNames();
String paramName = nada;
String[] paramValues = zero;

while (params.hasMoreElements()) {
paramName = (String) params.nextElement();
paramValues = asking.getParameterValues(paramName);
System.out.println("\nParameter name is " + paramName);
for (int i = 0; i < paramValues.length; i++) {
System.out.println(", value " + i + " is " +
paramValues[i].toString());
}
}

Note: Any time you lot print data that a user has supplied, Oracle recommends that you remove any HTML special characters that a user might have entered. If y'all do not remove these characters, your Web site could be exploited by cross-site scripting. For more information, refer to Securing Client Input in Servlets.

Methods for Using the HTTP Request

This section defines the methods of the javax.servlet.HttpServletRequest interface that yous can use to get data from the request object. You should keep the post-obit limitations in mind:

  • You cannot read asking parameters using whatever of the getParameter() methods described in this section and then try to read the request with the getInputStream() method.
  • You cannot read the asking with getInputStream() and and so attempt to read asking parameters with one of the getParameter() methods.

If you attempt either of the preceding procedures, an illegalStateException is thrown.

You lot can use the post-obit methods of javax.servlet.HttpServeletRequest to remember data from the request object:

HttpServletRequest.getMethod()

Allows you to determine the asking method, such equally Become or Mail service.

HttpServletRequest.getQueryString()

Allows you to access the query string. (The remainder of the requested URL, following the ? character.)

HttpServletRequest.getParameter()

Returns the value of a parameter.

HttpServletRequest.getParameterNames()

Returns an assortment of parameter names.

HttpServletRequest.getParameterValues()

Returns an array of values for a parameter.

HttpServletRequest.getInputStream()

Reads the body of the request as binary data. If y'all call this method later reading the request parameters with getParameter(), getParameterNames(), or getParameterValues(), an illegalStateException is thrown.

Example: Retrieving Input by Using Query Parameters

In this instance, the HelloWorld2.coffee servlet example is modified to accept a username as a query parameter, in guild to display a more personal greeting. The service() method is shown here.

List 9-1 Retrieving Input with the service() Method

public void service(HttpServletRequest req,
HttpServletResponse res)
throws IOException
{
Cord proper name, paramName[];
if ((paramName = req.getParameterValues("proper noun"))
!= null) {
proper noun = paramName[0];
}
else {
name = defaultName;
}

// Set the content type first
res.setContentType("text/html");
// Obtain a PrintWriter as an output stream
PrintWriter out = res.getWriter();

out.impress("<html><head><championship>" +
"Howdy World!" + </title></head>");
out.impress("<body><h1>");
out.print(defaultGreeting + " " + proper noun + "!");
out.print("</h1></torso></html>");
}

The getParameterValues() method retrieves the value of the proper noun parameter from the HTTP query parameters. You recall these values in an assortment of blazon String. A unmarried value for this parameter is returned and is assigned to the first chemical element in the name assortment. If the parameter is not present in the query data, null is returned; in this example, name is assigned to the default name that was read from the <init-param> by the init() method.

Do not base your servlet code on the assumption that parameters are included in an HTTP request. The getParameter() method has been deprecated; as a issue, yous might exist tempted to shorthand the getParameterValues() method by tagging an array subscript to the terminate. However, this method tin return cipher if the specified parameter is not available, resulting in a NullPointerException.

For case, the following code triggers a NullPointerException:

String myStr = req.getParameterValues("paramName")[0];

Instead, use the post-obit code:

if ((String myStr[] =          
req.getParameterValues("paramName"))!=null) {
// At present you can employ the myStr[0];
}
else {
// paramName was not in the query parameters!
}

Securing Client Input in Servlets

The ability to retrieve and render user-supplied data can present a security vulnerability called cross-site scripting, which tin exist exploited to steal a user'south security authorisation. For a detailed description of cantankerous-site scripting, refer to "Understanding Malicious Content Mitigation for Web Developers" (a CERT security advisory) at http://www.cert.org/tech_tips/malicious_code_mitigation.html.

To remove the security vulnerability, before you render data that a user has supplied, scan the information for any of the HTML special characters in Table 9-one. If you notice whatsoever special characters, supercede them with their HTML entity or graphic symbol reference. Replacing the characters prevents the browser from executing the user-supplied data equally HTML.

Table 9-1 HTML Special Characters that Must Be Replaced

Replace this special character:

With this entity/character reference:

<

&lt;

>

&gt;

(

&40;

)

&41;

#

&35;

&

&38;

Using a WebLogic Server Utility Method

WebLogic Server provides the weblogic.servlet.security.Utils.encodeXSS() method to replace the special characters in user-supplied data. To use this method, provide the user-supplied data as input. For example, to secure the user-supplied data in Listing 9-1, supplant the following line:
out.print(defaultGreeting + " " + name + "!");

with the post-obit:
out.impress(defaultGreeting + " " +
weblogic.security.servlet.encodeXSS(name) + "!");

To secure an entire awarding, you must use the encodeXSS() method each fourth dimension you lot return user-supplied data. While the previous case in Listing 9-ane is an obvious location in which to utilise the encodeXSS() method, Table nine-2 describes other locations to consider.

Table 9-two Code that Returns User-Supplied Information

Folio Type

User-Supplied Information

Example

Error folio

Erroneous input string, invalid URL, username

An mistake folio that says "username is not permitted access."

Status page

Username, summary of input from previous pages

A summary page that asks a user to ostend input from previous pages.

Database display

Data presented from a database

A page that displays a listing of database entries that take been previously entered by a user.


Using Cookies in a Servlet

A cookie is a slice of data that the server asks the client browser to save locally on the user's disk. Each time the browser visits the same server, it sends all cookies relevant to that server with the HTTP request. Cookies are useful for identifying clients equally they return to the server.

Each cookie has a name and a value. A browser that supports cookies by and large allows each server domain to store upward to 20 cookies of upwardly to 4k per cookie.

Setting Cookies in an HTTP Servlet

To set a cookie on a browser, create the cookie, give it a value, and add it to the HttpServletResponse object that is the second parameter in your servlet's service method. For instance:

Cookie myCookie = new Cookie("ChocolateChip", "100");
myCookie.setMaxAge(Integer.MAX_VALUE);
response.addCookie(myCookie);

This examples shows how to add a cookie called ChocolateChip with a value of 100 to the browser client when the response is sent. The expiration of the cookie is prepare to the largest possible value, which effectively makes the cookie last forever. Considering cookies take only string-blazon values, you should cast to and from the desired type that you desire to shop in the cookie. When using EJBs, a common exercise is to use the home handle of an EJB instance for the cookie value and to store the user's details in the EJB for later on reference.

Retrieving Cookies in an HTTP Servlet

You can remember a cookie object from the HttpServletRequest that is passed to your servlet as an statement to the service() method. The cookie itself is presented as a javax.servlet.http.Cookie object.

In your servlet code, you tin think all the cookies sent from the browser by calling the getCookies() method. For case:

Cookie[] cookies = asking.getCookies();

This method returns an array of all cookies sent from the browser, or aught if no cookies were sent by the browser. Your servlet must process the array in order to detect the correct named cookie. You lot can get the name of a cookie using the Cookie.getName() method. It is possible to have more than that i cookie with the aforementioned proper name, just different path attributes. If your servlets set multiple cookies with the aforementioned names, but different path attributes, you too need to compare the cookies by using the Cookie.getPath() method. The following code illustrates how to admission the details of a cookie sent from the browser. It assumes that all cookies sent to this server have unique names, and that you are looking for a cookie called ChocolateChip that may have been set previously in a browser client.

Cookie[] cookies = asking.getCookies();
boolean cookieFound = false;

for(int i=0; i < cookies.length; i++) {
thisCookie = cookies[i];
if (thisCookie.getName().equals("ChocolateChip")) {
cookieFound = truthful;
suspension;
}
}

if (cookieFound) {
// We found the cookie! At present get its value
int cookieOrder = String.parseInt(thisCookie.getValue());
}

Using Cookies That Are Transmitted past Both HTTP and HTTPS

Because HTTP and HTTPS requests are sent to different ports, some browsers may not include the cookie sent in an HTTP asking with a subsequent HTTPS request (or vice-versa). This may cause new sessions to be created when servlet requests alternate betwixt HTTP and HTTPS. To ensure that all cookies fix past a specific domain are sent to the server every time a request in a session is made, fix the cookie-domain chemical element to the name of the domain. The cookie-domain element is a sub-element of the session-descriptor element in the WebLogic-specific deployment descriptor weblogic.xml. For case:

<session-descriptor>
<cookie-domain>mydomain.com</cookie-domain>
</session-descriptor>

The cookie-domain element instructs the browser to include the proper cookie(s) for all requests to hosts in the domain specified by mydomain.com. For more information almost this property or configuring session cookies, see Setting Up Session Management.

Awarding Security and Cookies

Using cookies that enable automated account access on a automobile is convenient, just tin can be undesirable from a security perspective. When designing an awarding that uses cookies, follow these guidelines:

  • Do non presume that a cookie is e'er right for a user. Sometimes machines are shared or the same user may desire to admission a dissimilar account.
  • Permit your users to brand a choice about leaving cookies on the server. On shared machines, users may non want to leave automatic logins for their account. Practice non assume that users know what a cookie is; instead, ask a question like:
  • Automatically login from this computer?

  • Always inquire for passwords from users logging on to obtain sensitive information. Unless a user requests otherwise, you can shop this preference and the password in the user'due south session information. Configure the session cookie to expire when the user quits the browser.

Response Caching

The cache filter works similarly to the enshroud tag with the post-obit exceptions:

  • It caches on a page level (or included page) instead of a JSP fragment level.
  • Instead of declaring the caching parameters inside the certificate you tin can declare the parameters in the configuration of the Web application.

The cache filter has some default behavior that the cache tag does not for pages that were not included from another folio. The enshroud filter automatically caches the response headers Content-Type and Last-Modified. When it receives a request that results in a buried page it compares the If-Modified-Since request header to the Last-Modified response header to determine whether it needs to really serve the content or if information technology tin send an 302 SC_NOT_MODIFED status with an empty content instead.

The following example shows how to annals a cache filter to enshroud all the HTML pages in a Web application using the filter element of the J2EE standard deployment descriptor, web.xml.

<filter>

<filter-name>HTML</filter-proper noun>

<filter-class>weblogic.enshroud.filter.CacheFilter</filter-class>

</filter>

<filter-mapping>

<filter-name>HTML</filter-name>

<url-pattern>*.html</url-blueprint>

</filter-mapping>

The enshroud system uses soft references for storing the cache. So the garbage collector might or might non reclaim the enshroud depending on how recently the cache was created or accessed. It will articulate the soft references in guild to avoid throwing an OutOfMemoryError.

Initialization Parameters

To brand sure that if the web pages were updated at some bespeak you got the new copies into the cache, you could add a timeout to the filter. Using the init-params you lot tin can set many of the same parameters that you can set for the cache tag:

The initialization parameters are

  • Name This is the name of the cache. It defaults to the asking URI for compatibility with *.extension URL patterns.
  • Timeout This is the amount of fourth dimension since the last cache update that the filter waits until trying to update the content in the enshroud again. The default unit is seconds but you can also specify it in units of ms (milliseconds), south (seconds), chiliad (minutes), h (hours), or d (days).
  • Scope The telescopic of the enshroud tin can be whatsoever one of request, session, application, or cluster. Request scope is sometimes useful for looping constructs in the folio and not much else. The scope defaults to application. To utilize cluster scope you must fix the ClusterListener.
  • Cardinal This specifies that the cache is further specified not only by the proper noun only also by values of various entries in scopes. These are specified simply like the keys in the CacheTag although you practice non have page scope available.
  • Vars These are the variables calculated by the page that y'all want to cache. Typically this is used with servlets that pull information out of the database based on input parameters.
  • Size This limits the number of unlike unique fundamental values cached. It defaults to infinity.

The post-obit example shows where the init-parameter is located in the filter lawmaking.

<filter>

<filter-name>HTML</filter-proper name>

<filter-form>weblogic.cache.filter.CacheFilter</filter-class>

<init-param>

  • Max-cache-size This limits the size of an element added to the cache. It defaults to 64k.

Using WebLogic Services from an HTTP Servlet

When you write an HTTP servlet, you take access to many rich features of WebLogic Server, such as JNDI, EJB, JDBC, and JMS.

The following documents provide additional information about these features:

  • Programming WebLogic EJB
  • Programming WebLogic JDBC
  • Programming WebLogic JNDI
  • Programming WebLogic JMS

Accessing Databases

WebLogic Server supports the employ of Java Database Connectivity (JDBC) from server-side Java classes, including servlets. JDBC allows you to execute SQL queries from a Java class and to process the results of those queries. For more information on JDBC and WebLogic Server, meet Using WebLogic JDBC.

You can utilize JDBC in servlets every bit described in the following sections:

  • Connecting to a Database Using a DataSource Object.
  • Connecting Directly to a Database Using a JDBC Driver.

Connecting to a Database Using a DataSource Object

A DataSource is a server-side object that references a connectedness pool. The connection pool registration defines the JDBC commuter, database, login, and other parameters associated with a database connectedness. You create DataSource objects and connection pools through the Administration Console. Using a DataSource object is recommended when creating J2EE-compliant applications.

Using a DataSource in a Servlet

  1. Register a connection pool using the Administration Panel. For more information, see "JDBC Data Source: Configuration: Connection Puddle"
  2. Register a DataSource object that points to the connectedness pool.
  3. Await upwardly the DataSource object in the JNDI tree. For instance:
  4. // Go a context for the JNDI wait upwards
    ctx = new InitialContext(ht);
    // Wait up the DataSource object
    javax.sql.DataSource ds
    = (javax.sql.DataSource) ctx.lookup ("myDataSource");
  5. Employ the DataSource to create a JDBC connectedness. For example:
  6. java.sql.Connection conn = ds.getConnection();
  7. Apply the connection to execute SQL statements. For example:
  8. Statement stmt = conn.createStatement();
    stmt.execute("select * from emp");

Connecting Directly to a Database Using a JDBC Driver

Connecting directly to a database is the to the lowest degree efficient way of making a database connection considering a new database connection must be established for each request. Yous tin can use whatever JDBC driver to connect to your database. Oracle provides JDBC drivers for Oracle and Microsoft SQL Server. For more information, meet Programming WebLogic JDBC.


Threading Issues in HTTP Servlets

When y'all pattern a servlet, you should consider how the servlet is invoked past WebLogic Server under high load. Information technology is inevitable that more than one customer will striking your servlet simultaneously. Therefore, write your servlet lawmaking to guard against sharing violations on shared resources or instance variables.

It is recommended that shared-resource issues be handled on an individual servlet footing. Consider the post-obit guidelines:

  • Wherever possible, avoid synchronization, because it causes subsequent servlet requests to bottleneck until the current thread completes.
  • Ascertain variables that are specific to each servlet asking within the scope of the service methods. Local scope variables are stored on the stack and, therefore, are not shared by multiple threads running within the same method, which avoids the need to be synchronized.
  • Access to external resource should be synchronized on a Class level, or encapsulated in a transaction.

Dispatching Requests to Another Resource

This department provides an overview of commonly used methods for dispatching requests from a servlet to another resource.

A servlet tin pass on a request to another resource, such as a servlet, JSP, or HTML page. This procedure is referred to every bit request dispatching. When you acceleration requests, you utilise either the include() or frontwards() method of the RequestDispatcher interface.

For a complete give-and-take of request dispatching, see section 8.two of the Servlet 2.4 specification (see ) from Sun Microsystems.

By using the RequestDispatcher, y'all can avoid sending an HTTP-redirect response back to the customer. The RequestDispatcher passes the HTTP request to the requested resource.

To dispatch a request to a item resource:

  1. Get a reference to a ServletContext:
  2. ServletContext sc = getServletConfig().getServletContext();
  3. Await upward the RequestDispatcher object using one of the following methods:
    • RequestDispatcher rd = sc.getRequestDispatcher(String path);
    • path should exist relative to the root of the Web Application.

    • RequestDispatcher rd = sc.getNamedDispatcher(String name);
    • Replace name with the proper name assigned to the servlet in the J2EE standard Spider web Application deployment descriptor, spider web.xml, with the <servlet-proper noun> element.

    • RequestDispatcher rd =  ServletRequest.getRequestDispatcher(String path);
    • This method returns a RequestDispatcher object and is like to the ServletContext.getRequestDispatcher(Cord path) method except that it allows the path specified to be relative to the electric current servlet. If the path begins with a / grapheme it is interpreted to be relative to the Web Awarding.

      You can obtain a RequestDispatcher for whatsoever HTTP resources within a Web Awarding, including HTTP Servlets, JSP pages, or evidently HTML pages by requesting the appropriate URL for the resource in the getRequestDispatcher() method. Use the returned RequestDispatcher object to frontwards the asking to another servlet.

  4. Forward or include the request using the advisable method:
    • rd.forrad(request,response);
    • rd.include(request,response);
    • These methods are discussed in the next ii sections.

Forwarding a Request

Once yous have the correct RequestDispatcher, your servlet forwards a request using the RequestDispatcher.frontwards() method, passing HTTPServletRequest and HTTPServletResponse as arguments. If you telephone call this method when output has already been sent to the client an IllegalStateException is thrown. If the response buffer contains pending output that has not been committed, the buffer is reset.

The servlet must not attempt to write whatever previous output to the response. If the servlet retrieves the ServletOutputStream or the PrintWriter for the response before forwarding the request, an IllegalStateException is thrown.

All other output from the original servlet is ignored subsequently the asking has been forwarded.

If you are using any type of authentication, a forwarded request, by default, does not require the user to be re-authenticated. Yous can change this behavior to require authentication of a forwarded request by adding the check-auth-on-forrard/ element to the container-descriptor chemical element of the WebLogic-specific deployment descriptor, weblogic.xml. For example:

<container-descriptor>
    <cheque-auth-on-forwards/>
</container-descriptor>

Including a Request

Your servlet can include the output from another resource by using the RequestDispatcher.include() method, and passing HTTPServletRequest and HTTPServletResponse every bit arguments. When you include output from another resource, the included resource has access to the asking object.

The included resources can write data back to the ServletOutputStream or Writer objects of the response object and and then can either add together data to the response buffer or call the affluent() method on the response object. Whatsoever attempt to gear up the response status code or to fix any HTTP header data from the included servlet response is ignored.

In effect, you lot can employ the include() method to mimic a "server-side-include" of another HTTP resource from your servlet code.

RequestDispatcher and Filters

The Servlet 2.iii Specification from Sun Microsystems did not specify whether filters should be applied on forwards and includes. The Servlet ii.4 specification clarifies this by introducing a new dispatcher chemical element in the web.xml deployment descriptor. Using this dispatcher element, you can configure a filter-mapping to exist applied on REQUEST/Frontwards/INCLUDE/ERROR. In WebLogic Server viii.1, the default was REQUEST+FORWARD+INCLUDE. For the sometime DTD-based deployment descriptors, the default value has non been inverse in society to preserve backward compatibility. For the new descriptors (schema based) the default is REQUEST.

You can change the default behavior of dispatched requests past setting the filter-dispatched-requests-enabled element in weblogic.xml. This element controls whether or not filters are practical to dispatched (include/forward) requests. The default value for former DTD-based deployment descriptors is true. The default for the new schema-based descriptors is false

For more information about RequestDispatcher and filters, see section 6.2.5 of the Servlet 2.iv specification. For more data about writing and configuring filters for WebLogic Server, come across Filters.


Proxying Requests to Another Web Server

The following sections discuss how to proxy HTTP requests to another Web server:

  • Overview of Proxying Requests to Another Web Server
  • Setting Upward a Proxy to a Secondary Web Server
  • Sample Deployment Descriptor for the Proxy Servlet

Overview of Proxying Requests to Some other Spider web Server

When yous use WebLogic Server equally your primary Web server, yous may also want to configure WebLogic Server to laissez passer on, or proxy, certain requests to a secondary Web server, such as Netscape Enterprise Server, Apache, or Microsoft Internet Information Server. Any asking that gets proxied is redirected to a specific URL.You tin can fifty-fifty proxy to another Spider web server on a different machine.You proxy requests based on the URL of the incoming asking.

The HttpProxyServlet (provided as function of the distribution) takes an HTTP asking, redirects it to the proxy URL, and sends the response to the client's browser dorsum through WebLogic Server. To use the HttpProxyServlet, you lot must configure it in a Web Application and deploy that Web Application on the WebLogic Server that is redirecting requests.

Setting Up a Proxy to a Secondary Web Server

To gear up upwardly a proxy to a secondary HTTP server:

  1. Register the proxy servlet in your Web Application deployment descriptor (run into Sample web.xml for Apply with ProxyServlet). The Web Application must be the default Web Application of the server example that is responding to requests. The class proper noun for the proxy servlet is weblogic.servlet.proxy.HttpProxyServlet.
  2. Define an initialization parameter for the ProxyServlet with a <param-name> of redirectURL and a <param-value> containing the URL of the server to which proxied requests should exist directed.
  3. Optionally, define the following <KeyStore> initialization parameters to use two-mode SSL with your ain identity certificate and central. If no <KeyStore> is specified in the deployment descriptor, the proxy will presume i-style SSL.
    • <KeyStore> – The key store location in your Web application.
    • <KeyStoreType> – The central store type. If it is not defined, the default type volition be used instead.
    • <PrivateKeyAlias> – The private cardinal alias.
    • <KeyStorePasswordProperties> – A property file in your Web application that defines encrypted passwords to access the central store and private primal alias. The file contents looks like this:
    • KeyStorePassword={3DES}i4+50LCKenQO8BBvlsXTrg\=\=
      PrivateKeyPassword={3DES}a4TcG4mtVVBRKtZwH3p7yA\=\=

      You must use the weblogic.security.Encrypt command-line utility to encrypt the password. For more information on the Encrypt utility, as well every bit the CertGen, and der2pem utilities, see Using the WebLogic Server Coffee Utilities in the WebLogic Server Command Reference.

  4. Map the ProxyServlet to a <url-pattern>. Specifically, map the file extensions yous wish to proxy, for example *.jsp, or *.html. Utilise the <servlet-mapping> element in the web.xml Web Application deployment descriptor.
  5. If you fix the <url-blueprint> to "/", then whatsoever request that cannot exist resolved past WebLogic Server is proxied to the remote server. However, you must also specifically map the following extensions: *.jsp, *.html, and *.html if you want to proxy files ending with those extensions.

  6. Deploy the Web Application on the WebLogic Server instance that redirects incoming requests.

Sample Deployment Descriptor for the Proxy Servlet

The following is an sample of a Web applications deployment descriptor for using the ProxyServlet.

Listing 9-2 Sample web.xml for Use with ProxyServlet

<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://coffee.sunday.com/xml/ns/j2ee"
xmlns:j2ee="http://java.sun.com/xml/ns/j2ee"
xmlns:xsd="http://world wide web.w3.org/2001/XMLSchema"
elementFormDefault="qualified"
attributeFormDefault="unqualified"
version="ii.iv">
<spider web-app>
<servlet>
  <servlet-proper name>ProxyServlet</servlet-proper noun>
  <servlet-course>weblogic.servlet.proxy.HttpProxyServlet</servlet-class>
  <init-param>
    <param-name>redirectURL</param-proper noun>
    <param-value>http://server:port</param-value>
  </init-param>
<init-param>
<param-name>KeyStore</param-name>
<param-value>/mykeystore</param-value>
</init-param>
<init-param>
<param-name>KeyStoreType</param-name>
<param-value>jks</param-value>
</init-param>
<init-param>
<param-name>PrivateKeyAlias</param-name>
<param-value>passalias</param-value>
</init-param>
<init-param>
<param-name>KeyStorePasswordProperties</param-name>
<param-value>mykeystore.backdrop</param-value>
</init-param>
<servlet-mapping>
  <servlet-proper noun>ProxyServlet</servlet-proper name>
  <url-pattern>/</url-pattern>
</servlet-mapping>
<servlet-mapping>
  <servlet-name>ProxyServlet</servlet-name>
  <url-pattern>*.jsp</url-design>
</servlet-mapping>
<servlet-mapping>
  <servlet-name>ProxyServlet</servlet-proper noun>
  <url-blueprint>*.htm</url-pattern>
</servlet-mapping>
<servlet-mapping>
  <servlet-proper noun>ProxyServlet</servlet-name>
  <url-pattern>*.html</url-pattern>
</servlet-mapping>

Clustering Servlets

Clustering servlets provides failover and load balancing benefits. To deploy a servlet in a WebLogic Server cluster, deploy the Spider web Application containing the servlet on all servers in the cluster.

For information on requirements for clustering servlets, and to understand the connexion and failover processes for requests that are routed to clustered servlets, come across "Replication and Failover for Servlets and JSPs" in Using WebLogic Server Clusters.

Notation: Automated failover for servlets requires that the servlet session state be replicated in memory. For instructions, run across "Configure In-Retention HTTP Replication" in Using WebLogic Server Clusters.

For information on the load balancing support that a WebLogic Server cluster provides for servlets, and for related planning and configuration considerations for architects and administrators, meet "Load Balancing for Servlets and JSPs" in Using WebLogic Server Clusters.


Referencing a Servlet in a Web Application

The URL used to reference a servlet in a Web Application is constructed as follows:

                      http://myHostName:port/myContextPath/myRequest/?myRequestParameters        

The components of this URL are divers as follows:

myHostName

The DNS proper name mapped to the Spider web Server defined in the WebLogic Server Administration Console.

This portion of the URL can be replaced with host:port, where host is the name of the machine running WebLogic Server and port is the port at which WebLogic Server is listening for requests.

port

The port at which WebLogic Server is listening for requests. The Servlet can communicate with the proxy only through the listenPort on the Server mBean and the SSL mBean.

myContextPath

The name of the context root which is specified in the weblogic.xml file, or the uri of the web module which is specified in the config.xml file.

myRequest

The name of the servlet every bit defined in the spider web.xml file.

myRequestParameters

Optional HTTP request parameters encoded in the URL, which tin exist read by an HTTP servlet.


URL Blueprint Matching

WebLogic Server provides the user with the ability to implement a URL matching utility which does not conform to the J2EE rules for matching. The utility must be configured in the weblogic.xml deployment descriptor rather than the web.xml deployment descriptor used for the configuration of the default implementation of URLMatchMap.

To exist used with WebLogic Server, the URL matching utility must implement the following interface:

Packet weblogic.servlet.utils;

public interface URLMapping {

public void put(Cord pattern, Object value);

public Object get(String uri);

public void remove(String pattern)

public void setDefault(Object defaultObject);

public Object getDefault();

public void setCaseInsensitive(boolean ci);

public boolean isCaseInsensitive();

public int size();

public Object[] values();

public String[] keys();

}


The SimpleApacheURLMatchMap Utility

The included SimpleApacheURLMatchMap utility is non J2EE specific. It can be configured in the weblogic.xml deployment descriptor file and allows the user to specify Apache style pattern matching rather than the default URL pattern matching provided in the web.xml deployment descriptor. For more than information, see url-lucifer-map.


A Time to come Response Model for HTTP Servlets

In general, WebLogic Server processes incoming HTTP requests and the response is returned immediately to the client. Such connections are handled synchronously by the same thread. However, some HTTP requests may crave longer processing time. Database connection, for example, may create longer response times. Handling these requests synchronously causes the thread to be held, waiting until the request is processed and the response sent.

To avert this hung-thread scenario, WebLogic Server provides 2 classes that handle HTTP requests asynchronously past de-coupling the response from the thread that handles the incoming request. The post-obit sections describe these classes.

Abstruse Asynchronous Servlet

The Abstract Asynchronous Servlet enables you to handle incoming requests and servlet responses with different threads. This class explicitly provides a amend general framework for handling the response than the Future Response Servlet, including thread handling.

You implement the Abstruse Asynchronous Servlet by extending the weblogic.servlet.http.AbstractAsyncServlet.coffee form. This class provides the following abstract methods that you must override in your extended class.

doRequest

This method processes the servlet request. The following code example demonstrates how to override this method.

Listing nine-3 Overriding doRequest in AbstractAsynchServlet.java

public boolean doRequest(RequestResponseKey rrk)          
      throws ServletException, IOException {
      HttpServletRequest req = rrk.getRequest();
      HttpServletResponse res = rrk.getResponse();

      if (req.getParameter("immediate") != cypher) {
            res.setContentType("text/html");
            PrintWriter out = res.getWriter();
            out.println("Hello World Immediately!");
            return fake ;
      }
      else {
            TimerManagerFactory.getTimerManagerFactory()
            .getDefaultTimerManager().schedule
            (new TimerListener() {
                  public void timerExpired(Timer timer)
                        {attempt {
                              AbstractAsyncServlet.notify(rrk, zilch);
                        }
                        catch (Exception e) {
                              due east.printStackTrace();
                        }
                  }
            }, 2000);
      return true;
      }
}

doResponse

This method processes the servlet response.

Note: The servlet instance that processed the doRequest() method used to handle the original incoming request method will not necessarily be the 1 to process the doResponse() method.

If an exception occurs during processing, the container returns an mistake to the client. The following code case demonstrates how to override this method.

Listing nine-4 Overriding doResponse() in AbstractAsyncServlet.java

public void doResponse (RequestResponseKey rrk, Object context)
   throws ServletException, IOException
      {
      HttpServletRequest req = rrk.getRequest();
      HttpServletResponse res = rrk.getResponse();

      res.setContentType("text/html");
      PrintWriter out = res.getWriter();
      out.println("Hello World!");
}

doTimeOut

This method sends a servlet response error when the notify() method is non called within the timeout period.

Annotation: The servlet instance that candy the doRequest() method used to handle the original incoming asking method volition not necessarily be the ane to process the doTimeOut() method.

List 9-v Overriding doTimeOut() in AbstractAsyncServlet.java

public void doTimeout (RequestResponseKey rrk)
      throws ServletException, IOException
{
      HttpServletRequest req = rrk.getRequest();
      HttpServletResponse res = rrk.getResponse();

      res.setContentType("text/html");
      PrintWriter out = res.getWriter();
      out.println("Timeout!");
}

Hereafter Response Servlet

Although Oracle recommends using the Abstruse Asynchronous Servlet, you lot tin can also use the Future Response Servlet to handle servlet responses with a different thread than the one that handles the incoming request. You enable this servlet past extending weblogic.servlet.FutureResponseServlet.java, which gives you full control over how the response is handled and allows more control over thread handling. Even so, using this class to avert hung threads requires y'all to provide nearly of the code.

The exact implementation depends on your needs, merely you must override the service() method of this class at a minimum. The following example shows how you can override the service method.

Listing ix-6 Overriding the service() method of FutureResponseServlet.java

          public void service(HttpServletRequest req, FutureServletResponse rsp)
throws IOException, ServletException {
if(req.getParameter("immediate") != zippo){
PrintWriter out = rsp.getWriter();
out.println("Immediate response!");
rsp.send();
} else {
Timer myTimer = new Timer();
MyTimerTask mt = new MyTimerTask(rsp, myTimer);
myTimer.schedule(mt, 100);
}
}

individual static form MyTimerTask extends TimerTask{
private FutureServletResponse rsp;
Timer timer;
MyTimerTask(FutureServletResponse rsp, Timer timer){
this.rsp = rsp;
this.timer = timer;
}
public void run(){
try{
PrintWriter out = rsp.getWriter();
out.println("Delayed Response");
rsp.send();
timer.abolish();
}
take hold of(IOException e){
due east.printStackTrace();
}
}
}


morrisonwhicagoers.blogspot.com

Source: https://docs.oracle.com/cd/E13222_01/wls/docs103/webapp/progservlet.html

Post a Comment for "Servlet if Value Is Return and Start Over Again"