Saturday, July 2, 2011

JSP & Servlets

Java Servlets

Servlets are Java technology's answer to CGI programming. They are programs that run on a Web server and build Web pages. Building Web pages on the fly is useful (and commonly done) for a number of reasons:
  • The Web page is based on data submitted by the user. For example the results pages from search engines are generated this way, and programs that process orders for e-commerce sites do this as well.
  • The data changes frequently. For example, a weather-report or news headlines page might build the page dynamically, perhaps returning a previously built page if it is still up to date.
  • The Web page uses information from corporate databases or other such sources. For example, you would use this for making a Web page at an on-line store that lists current prices and number of items in stock.
Servlets don't have a main method & they are under the control of a container. Server sends the request to the container & then the container call for the correct servlet.
In order to get the service of a servlet you need to import following containers to your java file. 
import javax.servlet.http.* 
import javax.servlet.*

A Servlet has two methods.
Http.ServletRequest - this object is passed as arguments to servlets's service methods such as doGet, doPost
Http.ServletResponse - this object is passed as arguments to servlets's service methods such as doGet, doPost.


Java Server Pages

Java Server Pages (JSP) is a technology that lets you mix regular, static HTML with dynamically-generated HTML. Many Web pages that are built by CGI programs are mostly static, with the dynamic part limited to a few small locations. But most CGI variations, including servlets, make you generate the entire page via your program, even though most of it is always the same. JSP lets you create the two parts separately.
 Here's an example:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD><TITLE>Welcome to Our Store</TITLE></HEAD>
<BODY>
<H1>Welcome to JSP</H1>
<SMALL>Welcome,
<!-- User name is "New User" for first-time visitors --> 
<% out.println(Utils.getUserNameFromCookie(request)); %>
To access your account settings, click
<A HREF="Account-Settings.html">here.</A></SMALL>
<P>
Regular HTML for all the rest of the on-line store's Web page.
</BODY></HTML>
In the next post let me tell you about JSP/Servlet communication. Stay tuned :) 



No comments:

Post a Comment