<HTML> <HEAD> <TITLE>Using Parameterized Constructors</TITLE> </HEAD> <BODY> <H1>Using Parameterized Constructors</H1> <%! javax.servlet.jsp.JspWriter localOut; class a { a() throws java.io.IOException { localOut.println("In a\"s constructor...<BR>"); } } class b extends a { b(String s) throws java.io.IOException { localOut.println("In b\"s String constructor...<BR>"); localOut.println(s); } } %> <% localOut = out; b obj = new b("Hello from JSP!<BR>"); %> </BODY> </HTML>
Showing posts with label jsp and servlets. Show all posts
Showing posts with label jsp and servlets. Show all posts
Saturday, 17 December 2011
JSP Examples Tutorial - Using Parameterized Constructors
JSP Examples Tutorial - Using Inheritance in JSP
<HTML> <HEAD> <TITLE>Using Inheritance</TITLE> </HEAD> <BODY> <H1>Using Inheritance</H1> <%! javax.servlet.jsp.JspWriter localOut; class BaseClass { public void start() throws java.io.IOException { localOut.println("Starting...<BR>"); } } class DerivedClass extends BaseClass { public void drive() throws java.io.IOException { localOut.println("Deriving...<BR>"); } } %> <% localOut = out; out.println("Creating an DerivedClass...<BR>"); DerivedClass a = new DerivedClass(); a.start(); a.drive(); %> </BODY> </HTML>
JSP Examples Tutorial - Using Abstract Classes in JSP
<HTML> <HEAD> <TITLE>Using Abstract Classes</TITLE> </HEAD> <BODY> <H1>Using Abstract Classes</H1> <%! javax.servlet.jsp.JspWriter localOut; abstract class a { abstract String getText() throws java.io.IOException; public void printem() throws java.io.IOException { localOut.println(getText()); } } class b extends a { String getText() throws java.io.IOException { return "Hello from JSP!"; } } %> <% localOut = out; b bObject = new b(); bObject.printem(); %> </BODY> </HTML>
JSP Examples Tutorial - Runtime Polymorphism
<HTML> <HEAD> <TITLE>Runtime Polymorphism</TITLE> </HEAD> <BODY> <H1>Runtime Polymorphism</H1> <%! javax.servlet.jsp.JspWriter localOut; class BaseClass { public void print() throws java.io.IOException { localOut.println("Hello from BaseClass...<BR>"); } } class DerivedClass1 extends BaseClass { public void print() throws java.io.IOException { localOut.println("Hello from DerivedClass1...<BR>"); } } class DerivedClass2 extends BaseClass { public void print() throws java.io.IOException { localOut.println("Hello from DerivedClass2...<BR>"); } } class DerivedClass3 extends BaseClass { public void print() throws java.io.IOException { localOut.println("Hello from DerivedClass3...<BR>"); } } %> <% localOut = out; BaseClass a1 = new BaseClass(); DerivedClass1 b1 = new DerivedClass1(); DerivedClass2 c1 = new DerivedClass2(); DerivedClass3 d1 = new DerivedClass3(); BaseClass baseClassVariable; baseClassVariable = a1; baseClassVariable.print(); baseClassVariable = b1; baseClassVariable.print(); baseClassVariable = c1; baseClassVariable.print(); baseClassVariable = d1; baseClassVariable.print(); %> </BODY> </HTML>
JSP Examples Tutorial - Overriding Methods in derived class
<HTML> <HEAD> <TITLE>Overriding Methods in derived class</TITLE> </HEAD> <BODY> <H1>Overriding Methods</H1> <%! javax.servlet.jsp.JspWriter localOut; class BaseClass { public void print() throws java.io.IOException { localOut.println("print in base...<BR>"); } } class DerivedClass extends BaseClass { public void print() throws java.io.IOException { localOut.println("print in Derived class...<BR>"); } } %> <% localOut = out; out.println("Creating an animal object...<BR>"); BaseClass a = new BaseClass(); a.print(); out.println(); out.println("Creating a trout object...<BR>"); DerivedClass t = new DerivedClass(); t.print(); %> </BODY> </HTML>
JSP Examples Tutorial - Overriding Methods in derived class
<HTML> <HEAD> <TITLE>Overriding Methods in derived class</TITLE> </HEAD> <BODY> <H1>Overriding Methods</H1> <%! javax.servlet.jsp.JspWriter localOut; class BaseClass { public void print() throws java.io.IOException { localOut.println("print in base...<BR>"); } } class DerivedClass extends BaseClass { public void print() throws java.io.IOException { localOut.println("print in Derived class...<BR>"); } } %> <% localOut = out; out.println("Creating an animal object...<BR>"); BaseClass a = new BaseClass(); a.print(); out.println(); out.println("Creating a trout object...<BR>"); DerivedClass t = new DerivedClass(); t.print(); %> </BODY> </HTML>
JSP Examples Tutorial - Overloading Methods
<HTML> <HEAD> <TITLE>Overloading Methods</TITLE> </HEAD> <BODY> <H1>Overloading Methods</H1> <%! javax.servlet.jsp.JspWriter localOut; void printText() throws java.io.IOException { localOut.println("Hello!<BR>"); } void printText(String s) throws java.io.IOException { localOut.println(s + "<BR>"); } %> <% localOut = out; printText(); printText("Hello from JSP!"); %> </BODY> </HTML>
JSP Examples Tutorial - Creating a Java Interface
<HTML> <HEAD> <TITLE>Creating a Java Interface</TITLE> </HEAD> <BODY> <H1>Creating a Java Interface</H1> <%! javax.servlet.jsp.JspWriter localOut; interface Printem { void printText() throws java.io.IOException; } class a implements Printem { public void printText() throws java.io.IOException { localOut.println("Hello from JSP!"); } } %> <% localOut = out; a printer = new a(); printer.printText(); %> </BODY> </HTML>
JSP Examples Tutorial - Calling Superclass Constructors
<HTML> <HEAD> <TITLE>Calling Superclass Constructors</TITLE> </HEAD> <BODY> <H1>Calling Superclass Constructors</H1> <%! javax.servlet.jsp.JspWriter localOut; class a { a() throws java.io.IOException { localOut.println("In a\"s constructor...<BR>"); } } class b extends a { b() throws java.io.IOException { localOut.println("In b\"s constructor...<BR>"); } } %> <% localOut = out; b obj = new b(); %> </BODY> </HTML>
What Is a JSP Pages?
A JSP page is a text-based document that contains two types of text: static template data, which can be expressed in any text-based format, such as HTML, SVG, WML, and XML; and JSP elements, which construct dynamic content. A syntax card and reference for the JSP elements are available at:
http://java.sun.com/products/jsp/technical.html#syntax
The source code for this example is in the
j2eetutorial/examples/src/web/date directory created when you unzip the tutorial bundle. The JSP page index.jsp used to create the form appears below; it is a typical mixture of static HTML markup and JSP elements. If you have developed Web pages, you are probably familiar with the HTML document structure statements (<head>, <body>, and so on) and the HTML statements that create a form (<form>) and a menu (<select>). The lines in bold in the example code contain the following types of JSP constructs:- Directives (<%@ page ... %>) import classes in the
java.utilpackage and theMyLocalesclass, and set the content type returned by the page. - The jsp:useBean element creates an object containing a collection of locales and initializes a variable that points to that object.
- Scriptlets (<% ... %> ) retrieve the value of the
localerequest parameter, iterate over a collection of locale names, and conditionally insert HTML text into the output. - Expressions (<%= ... %>) insert the value of the locale name into the response.
- The jsp:include element sends a request to another page (
date.jsp) and includes the response in the response from the calling page.<%@ page import="java.util.*,MyLocales" %> <%@ page contentType="text/html; charset=ISO-8859-5" %> <html> <head><title>Localized Dates</title></head> <body bgcolor="white"> <jsp:useBean id="locales" scope="application" class="MyLocales"/> <form name="localeForm" action="index.jsp" method="post"> <b>Locale:</b> <select name=locale> <% String selectedLocale = request.getParameter("locale"); Iterator i = locales.getLocaleNames().iterator(); while (i.hasNext()) { String locale = (String)i.next(); if (selectedLocale != null && selectedLocale.equals(locale)) { %> <option selected><%=locale%></option> <% } else { %> <option><%=locale%></option> <% } } %> </select> <input type="submit" name="Submit" value="Get Date"> </form> <jsp:include page="date.jsp"/> </body> </html>
- Go to
j2eetutorial/examplesand build the example by executingant date. - Create a J2EE application called
DateApp. - Create the WAR and add the Web components to the
DateAppapplication.- Select File
New
Web Component.
- Select
DateAppfrom the Create New WAR File In Application combo box. - Enter
DateWARin the WAR Display Name field. - Click Edit.
- Navigate to
j2eetutorial/examples/build/web/date. Selectindex.jsp,date.jsp,MyDate.class, andMyLocales.classand click Add. Then click Finish. - Click Next.
- Click JSP In The Web Component radio button, and then click Next.
- Select
index.jspfrom the JSP Filename combo box. Click Finish.
- Select File
- Enter the context root.
- Deploy the application.
- Invoke the URL
http://<host>:8000/datein a browser.
JavaServer Pages Technology
JavaServer Pages (JSP) technology allows you to easily create Web content that has both static and dynamic components. JSP technology projects all the dynamic capabilities of Java Servlet technology but provides a more natural approach to creating static content. The main features of JSP technology are
Thursday, 15 December 2011
Creating Polite Long-Running Methods
The final step in providing a clean shutdown is to make any long-running methods behave politely. Methods that might run for a long time should check the value of the field that notifies them of shutdowns and should interrupt their work, if necessary.
public void doPost(...) {
...
for(i = 0; ((i < lotsOfStuffToDo) &&
!isShuttingDown()); i++) {
try {
partOfLongRunningOperation(i);
} catch (InterruptedException e) {
...
}
}
}See Notifying Methods to Shut DownNotifying Methods to Shut Down in Servlets
See Tracking Service Request
To ensure a clean shutdown, your
destroy method should not release any shared resources until all of the service requests have completed. One part of doing this is to check the service counter. Another part is to notify the long-running methods that it is time to shut down. For this notification, another field is required. The field should have the usual access methods:public class ShutdownExample extends HttpServlet {
private boolean shuttingDown;
...
//Access methods for shuttingDown
protected synchronized void setShuttingDown(boolean flag) {
shuttingDown = flag;
}
protected synchronized boolean isShuttingDown() {
return shuttingDown;
}
}
public void destroy() {
/* Check to see whether there are still service methods /*
/* running, and if there are, tell them to stop. */
if (numServices() > 0) {
setShuttingDown(true);
}
/* Wait for the service methods to stop. */
while(numServices() > 0) {
try {
Thread.sleep(interval);
} catch (InterruptedException e) {
}
}
} Finalizing a Servlet
When a servlet container determines that a servlet should be removed from service (for example, when a container wants to reclaim memory resources, or when it is being shut down), it calls the
destroy method of the Servlet interface. In this method, you release any resources the servlet is using and save any persistent state. The following destroy method releases the database object created in the init method described in Initializing a Servlet:public void destroy() {
bookDB = null;
}
All of a servlet's
service methods should be complete when a servlet is removed. The server tries to ensure this completion by calling the destroy method only after all service requests have returned or after a server-specific grace period, whichever comes first.If your servlet has potentially long-running service requests, use the techniques described below to do the following:
- Keep track of how many threads are currently running the
servicemethod. - Provide a clean shutdown by having the
destroymethod notify long-running threads of the shutdown and wait for them to complete. - Have the long-running methods poll periodically to check for shutdown and, if necessary, stop working, clean up, and return.
Accessing the Web Context
The context in which Web components execute is an object that implements the
ServletContext interface. You retrieve the Web context with the getServletContext method. The Web context provides methods for accessing:- Initialization parameters
- Resources associated with the Web context
- Object-valued attributes
- Logging capabilities
The Web context is used by the Duke's Bookstore filters
filters.HitCounterFilter and OrderFilter, discussed in the section Filtering Requests and Responses. The filters store a counter as a context attribute. Recall from Controlling Concurrent Access to Shared Resources that the counter's access methods are synchronized to prevent incompatible operations by servlets that are running concurrently. A filter retrieves the counter object with the context's getAttribute method. The incremented value of the counter is recorded with the context's log method.public final class HitCounterFilter implements Filter {
private FilterConfig filterConfig = null;
public void doFilter(ServletRequest request,
ServletResponse response, FilterChain chain)
throws IOException, ServletException {
...
StringWriter sw = new StringWriter();
PrintWriter writer = new PrintWriter(sw);
ServletContext context = filterConfig.
getServletContext();
Counter counter = (Counter)context.
getAttribute("hitCounter");
...
writer.println("The number of hits is: " +
counter.incCounter());
...
context.log(sw.getBuffer().toString());
...
}
}Invoking Other Web Resources
Web components can invoke other Web resources in two ways: indirect and direct. A Web component indirectly invokes another Web resource when it embeds in content returned to a client a URL that points to another Web component. In the Duke's Bookstore application, most Web components contain embedded URLs that point to other Web components. For example,
ShowCartServlet indirectly invokes the CatalogServlet through the embedded URL /bookstore1/catalog.A Web component can also directly invoke another resource while it is executing. There are two possibilities: it can include the content of another resource, or it can forward a request to another resource.
To invoke a resource available on the server that is running a Web component, you must first obtain a
RequestDispatcher object using the getRequestDispatcher("URL") method.You can get a
RequestDispatcher object from either a request or the Web context; however, the two methods have slightly different behavior. The method takes the path to the requested resource as an argument. A request can take a relative path (that is, one that does not begin with a /), but the Web context requires an absolute path. If the resource is not available, or if the server has not implemented a RequestDispatcher object for that type of resource, getRequestDispatcher will return null. Your servlet should be prepared to deal with this condition.Read more on Web Resource
Transferring Control to Another Web Component
In some applications, you might want to have one Web component do preliminary processing of a request and have another component generate the response. For example, you might want to partially process a request and then transfer to another component depending on the nature of the request.
To transfer control to another Web component, you invoke the
forward method of a RequestDispatcher. When a request is forwarded, the request URL is set to the path of the forwarded page. If the original URL is required for any processing, you can save it as a request attribute. The Dispatcher servlet, used by a version of the Duke's Bookstore application described in the section A Template Tag Library, saves the path information from the original URL, retrieves a RequestDispatcher from the request, and then forwards to the JSP page template.jsp.public class Dispatcher extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response) {
request.setAttribute("selectedScreen",
request.getServletPath());
RequestDispatcher dispatcher = request.
getRequestDispatcher("/template.jsp");
if (dispatcher != null)
dispatcher.forward(request, response);
}
public void doPost(HttpServletRequest request,
...
}
Filtering Requests and Responses
A filter is an object that can transform the header or content or both of a request or response. Filters differ from Web components in that they usually do not themselves create a response. Instead, a filter provides functionality that can be "attached" to any kind of Web resource. As a consequence, a filter should not have any dependencies on a Web resource for which it is acting as a filter, so that it can be composable with more than one type of Web resource. The main tasks that a filter can perform are as follows:
- Query the request and act accordingly.
- Block the request-and-response pair from passing any further.
- Modify the request headers and data. You do this by providing a customized version of the request.
- Modify the response headers and data. You do this by providing a customized version of the response.
- Interact with external resources.
Applications of filters include authentication, logging, image conversion, data compression, encryption, tokenizing streams, and XML transformations.
You can configure a Web resource to be filtered by a chain of zero, one, or more filters in a specific order. This chain is specified when the Web application containing the component is deployed and is instantiated when a Web container loads the component.
- Programming the filter
- Programming customized requests and responses
- Specifying the filter chain for each Web resource
Programming Filters
The filtering API is defined by the
Filter, FilterChain, and FilterConfig interfaces in the javax.servlet package. You define a filter by implementing the Filter interface. The most important method in this interface is the doFilter method, which is passed request, response, and filter chain objects. This method can perform the following actions:- Examine the request headers.
- Customize the request object if it wishes to modify request headers or data.
- Customize the response object if it wishes to modify response headers or data.
- Invoke the next entity in the filter chain. If the current filter is the last filter in the chain that ends with the target Web component or static resource, the next entity is the resource at the end of the chain; otherwise, it is the next filter that was configured in the WAR. It invokes the next entity by calling the
doFiltermethod on the chain object (passing in the request and response it was called with, or the wrapped versions it may have created). Alternatively, it can choose to block the request by not making the call to invoke the next entity. In the latter case, the filter is responsible for filling out the response. - Examine response headers after it has invoked the next filter in the chain.
- Throw an exception to indicate an error in processing.
In addition to
doFilter, you must implement the init and destroy methods. The init method is called by the container when the filter is instantiated. If you wish to pass initialization parameters to the filter, you retrieve them from the FilterConfig object passed to init.The Duke's Bookstore application uses the filters
HitCounterFilter and OrderFilter to increment and log the value of a counter when the entry and receipt servlets are accessed.In the
doFilter method, both filters retrieve the servlet context from the filter configuration object so that they can access the counters stored as context attributes. After the filters have completed application-specific processing, they invoke doFilter on the filter chain object passed into the original doFilter method. The elided code is discussed in the next section.public final class HitCounterFilter implements Filter {
private FilterConfig filterConfig = null;
public void init(FilterConfig filterConfig)
throws ServletException {
this.filterConfig = filterConfig;
}
public void destroy() {
this.filterConfig = null;
}
public void doFilter(ServletRequest request,
ServletResponse response, FilterChain chain)
throws IOException, ServletException {
if (filterConfig == null)
return;
StringWriter sw = new StringWriter();
PrintWriter writer = new PrintWriter(sw);
Counter counter = (Counter)filterConfig.
getServletContext().
getAttribute("hitCounter");
writer.println();
writer.println("===============");
writer.println("The number of hits is: " +
counter.incCounter());
writer.println("===============");
// Log the resulting string
writer.flush();
filterConfig.getServletContext().
log(sw.getBuffer().toString());
...
chain.doFilter(request, wrapper);
...
}
}
Programming Customized Requests and Responses
There are many ways for a filter to modify a request or response. For example, a filter could add an attribute to the request or insert data in the response. In the Duke's Bookstore example,
HitCounterFilter inserts the value of the counter into the response.A filter that modifies a response must usually capture the response before it is returned to the client. The way to do this is to pass a stand-in stream to the servlet that generates the response. The stand-in stream prevents the servlet from closing the original response stream when it completes and allows the filter to modify the servlet's response.
To pass this stand-in stream to the servlet, the filter creates a response wrapper that overrides the
getWriter or getOutputStream method to return this stand-in stream. The wrapper is passed to the doFilter method of the filter chain. Wrapper methods default to calling through to the wrapped request or response object. This approach follows the well-known Wrapper or Decorator pattern described in Design Patterns: Elements of Reusable Object-Oriented Software (Addison-Wesley, 1995). The following sections describe how the hit counter filter described earlier and other types of filters use wrappers.To override request methods, you wrap the request in an object that extends
ServletRequestWrapper or HttpServletRequestWrapper. To override response methods, you wrap the response in an object that extends ServletResponseWrapper or HttpServletResponseWrapper.HitCounterFilter wraps the response in a CharResponseWrapper. The wrapped response is passed to the next object in the filter chain, which is BookStoreServlet.BookStoreServlet writes its response into the stream created by CharResponseWrapper. When chain.doFilter returns, HitCounterFilter retrieves the servlet's response fromPrintWriter and writes it to a buffer. The filter inserts the value of the counter into the buffer, resets the content length header of the response, and finally writes the contents of the buffer to the response stream.PrintWriter out = response.getWriter(); CharResponseWrapper wrapper = new CharResponseWrapper( (HttpServletResponse)response); chain.doFilter(request, wrapper);CharArrayWriter caw = new CharArrayWriter(); caw.write(wrapper.toString().substring(0, wrapper.toString().indexOf("</body>")-1)); caw.write("<p>\n<center>" + messages.getString("Visitor") + "<font color='red'>" + counter.getCounter() + "</font></center>"); caw.write("\n</body></html>"); response.setContentLength(caw.toString().length()); out.write(caw.toString());out.close(); public class CharResponseWrapper extends HttpServletResponseWrapper { private CharArrayWriter output; public String toString() { return output.toString(); } public CharResponseWrapper(HttpServletResponse response){ super(response); output = new CharArrayWriter(); } public PrintWriter getWriter(){ return new PrintWriter(output); } }
Specifying Filter Mappings
A Web container uses filter mappings to decide how to apply filters to Web resources. A filter mapping matches a filter to a Web component by name or to Web resources by URL pattern. The filters are invoked in the order in which filter mappings appear in the filter mapping list of a WAR. You specify a filter mapping list for a WAR in the
deploytool Filter Mapping inspector (seeFilter Mapping).Table 10-7 contains the filter mapping list for the Duke's Bookstore application. The filters are matched by servlet name and each filter chain contains only one filter.
| Servlet Name | Filter |
|---|---|
BookStoreServlet | HitCounterFilter |
ReceiptServlet | OrderFilter |
You can map a filter to one or more Web resources, and you can map more than one filter to a Web resource. This is illustrated in Figure 10-4, where filter F1 is mapped to servlets S1, S2, and S3, filter F2 is mapped to servlet S2, and filter F3 is mapped to servlets S1 and S2.
Recall that a filter chain is one of the objects passed to the
doFilter method of a filter. This chain is formed indirectly via filter mappings. The order of the filters in the chain is the same as the order in which filter mappings appear in the Web application deployment descriptor.When a filter is mapped to servlet S1, the Web container invokes the
doFilter method of F1. The doFilter method of each filter in S1's filter chain is invoked by the preceding filter in the chain via the chain.doFilter method. Since S1's filter chain contains filters F1 and F3, F1's call to chain.doFilter invokes the doFilter method of filter F3. When F3's doFiltermethod completes, control returns to F1's doFilter method.
Subscribe to:
Posts (Atom)


