In this section we are going to implement insert data, delete data, and update data using with JDBC database and also using of JavaScript.
Step 1: Create employee form (EmployeeInformation.jsp) .
In this step first of all create Employee information form and retrieved employee id from database using with JDBC database.
Here is the code EmployeeInformation.jsp
<%@ page language="java" import="java.lang.*" import="java.sql.*" %>
<html>
<body border="1" bgcolor="pink" width="650">
<%
Connection con = null;
String url = "jdbc:mysql://192.168.10.211:3306/";
String db = "amar";
String driver = "com.mysql.jdbc.Driver";
String userName ="amar";
String password="amar123";
Class.forName(driver);
con = DriverManager.getConnection(url+db,userName,password);
Statement stmt=null;
%>
<form method="GET" ACTION="ProcessAction.jsp">
<h3> <P ALIGN="CENTER"> <FONT SIZE=5> EMPLOYEE INFORMATION </FONT> </P> </h3> </br> </br>
<br>
<br>
<table callspacing=5 cellpadding=5 bgcolor="lightblue" colspan=2 rowspan=2 align="center">
<tr>
<td> <font size=5> Enter Employee ID </td>
<td> <input type="TEXT" ID="id" name="empid"> </font>
<select name="empIds" onchange="document.getElementById('id').value=this.options[this.selectedIndex].text"> <option>Select One</option>
<%
String rec="SELECT empid,empname FROM Employee ORDER BY empid";
try {
stmt=con.createStatement();
ResultSet rs=stmt.executeQuery(rec);
while(rs.next())
{
%>
<option><%= rs.getInt(1)%></option>
<%}
}
catch(Exception e){
System.out.println(e);
}
%>
</select>
</font> </td>
</tr>
<tr>
<td> <font size=5> Enter Employee Name </td>
<td><input type="text" name="empname"> </font> </td>
</tr>
<tr> <font size=5> <B>
<td><input type="RADIO" name="r1" VALUE="add" >Insert </td>
</tr>
<tr>
<td><input type="RADIO" name="r1" VALUE="del" >Delete </td>
</tr>
<tr>
<td><input type="RADIO" name="r1" VALUE="mod" >Modify </td>
</tr>
</font> </b>
<tr> <td><input type="SUBMIT" VALUE="Submit">
<input type="RESET" value="Reset"> </TD>
</tr>
</body>
</html>
Step 2 : Create "ProcessAction.jsp" for Process the Data and forward according to user requirement.
In this step first of all we will create ProcessAction.jsp for getting all string value using with getParameter() method and forward on different page like JSPInsertAction.jsp, ClearAction.jsp, and update.jsp.
<%@ page language="java" %>
<%@ page import="java.lang.*" %>
<%@ page import="java.sql.*" %>
<%
String str=request.getParameter("r1");
String name=request.getParameter("empname");
String code=request.getParameter("empid");
if(str.equals("add")) {
%>
<jsp:forward page="JSPInsertAction.jsp"/>
<%
}
else if(str.equals("del")) {
%>
<jsp:forward page="ClearAction.jsp" />
<%
}
else if(str.equals("mod")) {
%>
<jsp:forward page="update.jsp" />
<%
}
else {
%>
<jsp:forward page="Noresponse.html" />
<%
}
%>
Step 3: Create data insert action page ("JSPInsertAction.jsp").
This code using for insert data into database by using JDBC database. When you will select same employee id and employee name then massage will display employee id already exit in database.
<%@ page language="java" import="java.lang.*" import="java.sql.*" %>
<HTML>
<BODY>
<FORM NAME="f1" ACTION="EmplyeeInformation.jsp">
<%
Connection con = null;
String url = "jdbc:mysql://192.168.10.211:3306/";
String db = "amar";
String driver = "com.mysql.jdbc.Driver";
String userName ="amar";
String password="amar123";
String str=request.getParameter("r1");
String empname=request.getParameter("empname");
String code=request.getParameter("empid");
int ent=0;
String failed="";
try{
String click="SELECT COUNT(*) FROM Employee WHERE empid='"+code+"' and empname='"+empname+"'";
Class.forName(driver);
con = DriverManager.getConnection(url+db,userName,password);
Statement stmt=null;
stmt=con.createStatement();
ResultSet ok = stmt.executeQuery(click);
while(ok.next()) {
ent=ok.getInt(1);
}
if(ent==0) {
String insertQry = "insert Employee values('"+code+"','"+empname+"')";
int val = stmt.executeUpdate(insertQry);
%>
<script language="javascript">
alert("Insertion successful");
document.location="EmplyeeInformation.jsp";
</script>
<%
}
if(ent==1) {
%>
<script language="javascript">
alert("This Emp ID already Exists");
document.location="EmplyeeInformation.jsp";
</script>
<%
}
stmt.close();
con.close();
}
catch(Exception e) {
out.println(e.toString());
}
%>
</FORM>
</BODY>
</HTML>
Step 4: Create data deletion code from database ("ClearAction.jsp").
In this step you will learn how to delete data from database. When, you will select employee id and employee name then select delete radio button after selecting delete radio button when you will click on submit button then data will successfully delete from database.
<%@ page language="java" import="java.lang.*" import="java.sql.*" %>
<%
Connection con = null;
String url = "jdbc:mysql://192.168.10.211:3306/";
String db = "amar";
String driver = "com.mysql.jdbc.Driver";
String userName ="amar";
String password="amar123";
String str=request.getParameter("r1");
String name=request.getParameter("empname");
String code=request.getParameter("empid");
int EmpID=Integer.parseInt(code);
try {
Class.forName(driver);
con = DriverManager.getConnection(url+db,userName,password);
String sql = "delete from Employee where empid= ?";
PreparedStatement stmt=null;
stmt=con.prepareStatement(sql);
stmt.setInt(1,EmpID);
int erase=stmt.executeUpdate();
if(erase==0) { %>
<script language="javascript">
alert("Deletion successful");
</script>
<%
}
if(erase==1) { %>
<script language="javascript">
alert("Deletion successful");
</script>
<%
}
stmt.close();
con.close();
out.println("Data delete successfully from database.");
}
catch(Exception e) {
out.println(e);
}
%>
Step 5: Create update data code ("update.jsp").
In this step you will learn, how to modify data in database by using JDBC database.
<%@ page language="java" import="java.lang.*" import="java.sql.*" %>
<HTML>
<BODY>
<%
Connection con = null;
String url = "jdbc:mysql://192.168.10.211:3306/";
String db = "amar";
String driver = "com.mysql.jdbc.Driver";
String userName ="amar";
String password="amar123";
String rep=request.getParameter("empname");
String code=(String)request.getParameter("empid");
int ID=Integer.parseInt(code);
try {
Class.forName(driver);
con = DriverManager.getConnection(url+db,userName,password);
String rec="UPDATE Employee SET empname='"+rep+"' where empid='"+ID+"'";
Statement stmt=null;
stmt=con.createStatement();
int mod=stmt.executeUpdate(rec);
if(mod==0) { %>
<script language="javascript">
alert("This Emp ID already Exists");
</script>
<%
}
if(mod==1) { %>
<script language="javascript">
alert("Record Updated Successfully");
</script>
<%
}
con.commit();
stmt.close();
con.close();
}
catch(Exception e) { %>
<script language="javascript">
alert("Please Enter New Name");
document.location="EmplyeeInformation.jsp";
</script>
<%
}
%>
</BODY>
</HTML>
Popular Posts
-
Now I will show you how to retrieve the data posted from a HTML file in a JSP page. Consider an html page that prompts the user to enter his...
-
Accessing the Standard CGI Variables: To build the successful web application, you often need to know a lot about the environment in which ...
-
INTRODUCTION TO 'C': C is a programming language developed at AT & T's Bell laboratories of USA in 1972.it was designed by d...
-
SQL aliases can be used with database tables and with database table columns, depending on task you are performing. SQL column aliases are u...
-
Learning about Events (Continue) Lets program the Form_Load event. "MsgBox" is Visual Basic command that launch a message box. for...
-
Steps to follow: 1. Write Person.java as shown below in Code-11.3.a under polypackage directory. (You are welcome to do this work using eit...
-
The Command Button's KeyPress, KeyDown and KeyUp Events The events that will be mentioned in the following pages are commonly used, and ...
-
The SQL AVG aggregate function selects the average value for certain table column. Have a look at the SQL AVG syntax: SELECT AVG(Column1) FR...
-
package interfaceexercise; // Define an interface with three abstract methods. // Any class that implements this interface has to // impleme...
-
We will use the Customers table to illustrate the SQL LIKE clause usage: FirstName LastName Email DOB Phone John Smith John.Smith@yaho...
Monday, June 1, 2009
Retrieving the data posted to a JSP file from HTML file
Now I will show you how to retrieve the data posted from a HTML file in a JSP page. Consider an html page that prompts the user to enter his/her name, let's call it getname.htm. Here is the code of the html file:
<html>
<head>
<title>Enter your name</title>
</head>
<body>
<p> </p>
<form method="POST" action="showname.jsp">
<p><font color="#800000" size="5">Enter your name:</font><input type
="text" name="username" size="20"></p>
<p><input type="submit" value="Submit" name="B1"></p>
</form>
</body>
</html>
The target of form is "showname.jsp", which displays the name entered by the user. To retrieve the value entered by the user we uses the
request.getParameter("username");
code.
Here is the code of "showname.jsp" file:
<%@page contentType="text/html" %>
<!--
http://www.roseindia.net/jsp
-->
<html>
<body>
<p><font size="6">Welcome : <%=request.getParam
eter("username")%></font></p>
</body>
</html>
<html>
<head>
<title>Enter your name</title>
</head>
<body>
<p> </p>
<form method="POST" action="showname.jsp">
<p><font color="#800000" size="5">Enter your name:</font><input type
="text" name="username" size="20"></p>
<p><input type="submit" value="Submit" name="B1"></p>
</form>
</body>
</html>
The target of form is "showname.jsp", which displays the name entered by the user. To retrieve the value entered by the user we uses the
request.getParameter("username");
code.
Here is the code of "showname.jsp" file:
<%@page contentType="text/html" %>
<!--
http://www.roseindia.net/jsp
-->
<html>
<body>
<p><font size="6">Welcome : <%=request.getParam
eter("username")%></font></p>
</body>
</html>
Reading Request Information
When an HTTP client such as web browser sends a request to a wen server, along with the request it also sends some HTTP variables like Remote address, Remote host, Content type etc. In some cases these variables are useful to the programmers. So here is the code of the jsp file which prints the HTTP request information:
<%@page contentType="text/html" import="java.util.*" %>
<!--
http://www.roseindia.net/jsp
-->
<html>
<body>
<p><font size="5" color="#800000">Request Information:</font></p>
<div align="left">
<table border="0" cellpadding="0" cellspacing="0" width="70%" bgcolor="#EEFFCA">
<tr>
<td width="33%"><b><font color="#800000">Request Method:</font></b></td>
<td width="67%"><font color="#FF0000"><%=request.getMethod()%></font></td>
</tr>
<tr>
<td width="33%"><b><font color="#800000">Request URI:</font></b></td>
<td width="67%"><font color="#FF0000"><%=request.getRequestURI()%></font></td>
</tr>
<tr>
<td width="33%"><b><font color="#800000">Request Protocol:</font></b></td>
<td width="67%"><font color="#FF0000"><%=request.getProtocol()%></font></td>
</tr>
<tr>
<td width="33%"><b><font color="#800000">Path Info:</font></b></td>
<td width="67%"><font color="#FF0000"><%=request.getPathInfo()%></font></td>
</tr>
<tr>
<td width="33%"><b><font color="#800000">Path translated:</font></b></td>
<td width="67%"><font color="#FF0000"><%=request.getPathTranslated()%></font></td>
</tr>
<tr>
<td width="33%"><b><font color="#800000">Query String:</font></b></td>
<td width="67%"><font color="#FF0000"><%=request.getQueryString()%></font></td>
</tr>
<tr>
<td width="33%"><b><font color="#800000">Content length:</font></b></td>
<td width="67%"><font color="#FF0000"><%=request.getContentLength()%></font></td>
</tr>
<tr>
<td width="33%"><b><font color="#800000">Content type:</font></b></td>
<td width="67%"><font color="#FF0000"><%=request.getContentType()%></font></td>
</tr>
<tr>
<td width="33%"><b><font color="#800000">Server name:</font></b></td>
<td width="67%"><font color="#FF0000"><%=request.getServerName()%></font></td>
</tr>
<tr>
<td width="33%"><b><font color="#800000">Server port:</font></b></td>
<td width="67%"><font color="#FF0000"><%=request.getServerPort()%></font></td>
</tr>
<tr>
<td width="33%"><b><font color="#800000">Remote user:</font></b></td>
<td width="67%"><font color="#FF0000"><%=request.getRemoteUser()%></font></td>
</tr>
<tr>
<td width="33%"><b><font color="#800000">Remote address:</font></b></td>
<td width="67%"><font color="#FF0000"><%=request.getRemoteAddr()%></font></td>
</tr>
<tr>
<td width="33%"><b><font color="#800000">Remote host:</font></b></td>
<td width="67%"><font color="#FF0000"><%=request.getRemoteHost()%></font></td>
</tr>
<tr>
<td width="33%"><b><font color="#800000">Authorization scheme:</font></b></td>
<td width="67%"><font color="#FF0000"><%=request.getAuthType()%></font></td>
</tr>
</table>
</div>
</body>
</html>
<%@page contentType="text/html" import="java.util.*" %>
<!--
http://www.roseindia.net/jsp
-->
<html>
<body>
<p><font size="5" color="#800000">Request Information:</font></p>
<div align="left">
<table border="0" cellpadding="0" cellspacing="0" width="70%" bgcolor="#EEFFCA">
<tr>
<td width="33%"><b><font color="#800000">Request Method:</font></b></td>
<td width="67%"><font color="#FF0000"><%=request.getMethod()%></font></td>
</tr>
<tr>
<td width="33%"><b><font color="#800000">Request URI:</font></b></td>
<td width="67%"><font color="#FF0000"><%=request.getRequestURI()%></font></td>
</tr>
<tr>
<td width="33%"><b><font color="#800000">Request Protocol:</font></b></td>
<td width="67%"><font color="#FF0000"><%=request.getProtocol()%></font></td>
</tr>
<tr>
<td width="33%"><b><font color="#800000">Path Info:</font></b></td>
<td width="67%"><font color="#FF0000"><%=request.getPathInfo()%></font></td>
</tr>
<tr>
<td width="33%"><b><font color="#800000">Path translated:</font></b></td>
<td width="67%"><font color="#FF0000"><%=request.getPathTranslated()%></font></td>
</tr>
<tr>
<td width="33%"><b><font color="#800000">Query String:</font></b></td>
<td width="67%"><font color="#FF0000"><%=request.getQueryString()%></font></td>
</tr>
<tr>
<td width="33%"><b><font color="#800000">Content length:</font></b></td>
<td width="67%"><font color="#FF0000"><%=request.getContentLength()%></font></td>
</tr>
<tr>
<td width="33%"><b><font color="#800000">Content type:</font></b></td>
<td width="67%"><font color="#FF0000"><%=request.getContentType()%></font></td>
</tr>
<tr>
<td width="33%"><b><font color="#800000">Server name:</font></b></td>
<td width="67%"><font color="#FF0000"><%=request.getServerName()%></font></td>
</tr>
<tr>
<td width="33%"><b><font color="#800000">Server port:</font></b></td>
<td width="67%"><font color="#FF0000"><%=request.getServerPort()%></font></td>
</tr>
<tr>
<td width="33%"><b><font color="#800000">Remote user:</font></b></td>
<td width="67%"><font color="#FF0000"><%=request.getRemoteUser()%></font></td>
</tr>
<tr>
<td width="33%"><b><font color="#800000">Remote address:</font></b></td>
<td width="67%"><font color="#FF0000"><%=request.getRemoteAddr()%></font></td>
</tr>
<tr>
<td width="33%"><b><font color="#800000">Remote host:</font></b></td>
<td width="67%"><font color="#FF0000"><%=request.getRemoteHost()%></font></td>
</tr>
<tr>
<td width="33%"><b><font color="#800000">Authorization scheme:</font></b></td>
<td width="67%"><font color="#FF0000"><%=request.getAuthType()%></font></td>
</tr>
</table>
</div>
</body>
</html>
JSP date example
<%@page contentType="text/html" import="java.util.*" %>
<!--
http://www.roseindia.net/jsp
-->
<html>
<body>
<p> </p>
<div align="center">
<center>
<table border="0" cellpadding="0" cellspacing
="0" width="460" bgcolor="#EEFFCA">
<tr>
<td width="100%"><font size="6" color
="#008000"> Date Example</font></td>
</tr>
<tr>
<td width="100%"><b> Current Date
and time is: <font color="#FF0000">
<%= new java.util.Date() %>
</font></b></td>
</tr>
</table>
</center>
</div>
</body>
</html>
The heart of this example is Date() function of the java.util package which returns the current data and time.
In the JSP Declaratives
<%@page contentType="text/html" import="java.util.*" %>
we are importing the java.util package and following JSP Expression code
<%= new java.util.Date() %>
<!--
http://www.roseindia.net/jsp
-->
<html>
<body>
<p> </p>
<div align="center">
<center>
<table border="0" cellpadding="0" cellspacing
="0" width="460" bgcolor="#EEFFCA">
<tr>
<td width="100%"><font size="6" color
="#008000"> Date Example</font></td>
</tr>
<tr>
<td width="100%"><b> Current Date
and time is: <font color="#FF0000">
<%= new java.util.Date() %>
</font></b></td>
</tr>
</table>
</center>
</div>
</body>
</html>
The heart of this example is Date() function of the java.util package which returns the current data and time.
In the JSP Declaratives
<%@page contentType="text/html" import="java.util.*" %>
we are importing the java.util package and following JSP Expression code
<%= new java.util.Date() %>
INTRODUCTION TO JSP SCRIPTLETS
Syntax of JSP Scriptles are:
<%
//java codes
%>
JSP Scriptlets begins with <% and ends %> .We can embed any amount of java code in the JSP Scriptlets. JSP Engine places these code in the _jspService() method. Variables available to the JSP Scriptlets are:
* request:
request represents the clients request and is a subclass of HttpServletRequest. Use this variable to retrieve the data submitted along the request.
Example:
<%
//java codes
String userName=null;
userName=request.getParameter("userName");
%>
* response:
response is subclass of HttpServletResponse.
* session:
session represents the HTTP session object associated with the request.
* out:
out is an object of output stream and is used to send any output to the client.
Other variable available to the scriptlets are pageContext, application,config and exception.
INTRODUCTION TO JSP EXPRESSIONS
Syntax of JSP Expressions are:
<%="Any thing" %>
JSP Expressions start with
Syntax of JSP Scriptles are with <%= and ends with %>. Between these this you can put anything and that will converted to the String and that will be displayed.
Example:
<%="Hello World!" %>
Above code will display 'Hello World!'.
<%
//java codes
%>
JSP Scriptlets begins with <% and ends %> .We can embed any amount of java code in the JSP Scriptlets. JSP Engine places these code in the _jspService() method. Variables available to the JSP Scriptlets are:
* request:
request represents the clients request and is a subclass of HttpServletRequest. Use this variable to retrieve the data submitted along the request.
Example:
<%
//java codes
String userName=null;
userName=request.getParameter("userName");
%>
* response:
response is subclass of HttpServletResponse.
* session:
session represents the HTTP session object associated with the request.
* out:
out is an object of output stream and is used to send any output to the client.
Other variable available to the scriptlets are pageContext, application,config and exception.
INTRODUCTION TO JSP EXPRESSIONS
Syntax of JSP Expressions are:
<%="Any thing" %>
JSP Expressions start with
Syntax of JSP Scriptles are with <%= and ends with %>. Between these this you can put anything and that will converted to the String and that will be displayed.
Example:
<%="Hello World!" %>
Above code will display 'Hello World!'.
INTRODUCTION TO JSP DECLARATIVES
Syntax of JSP Declaratives are:
<%!
//java codes
%>
JSP Declaratives begins with <%! and ends %> with .We can embed any amount of java code in the JSP Declaratives. Variables and functions defined in the declaratives are class level and can be used anywhere in the JSP page.
<%@page contentType="text/html" %>
<html>
<body>
<%!
int cnt=0;
private int getCount(){
//increment cnt and return the value
cnt++;
return cnt;
}
%>
<p>Values of Cnt are:</p>
<p><%=getCount()%></p>
<p><%=getCount()%></p>
<p><%=getCount()%></p>
<p><%=getCount()%></p>
<p><%=getCount()%></p>
<p><%=getCount()%></p>
</body>
</html>
<%!
//java codes
%>
JSP Declaratives begins with <%! and ends %> with .We can embed any amount of java code in the JSP Declaratives. Variables and functions defined in the declaratives are class level and can be used anywhere in the JSP page.
<%@page contentType="text/html" %>
<html>
<body>
<%!
int cnt=0;
private int getCount(){
//increment cnt and return the value
cnt++;
return cnt;
}
%>
<p>Values of Cnt are:</p>
<p><%=getCount()%></p>
<p><%=getCount()%></p>
<p><%=getCount()%></p>
<p><%=getCount()%></p>
<p><%=getCount()%></p>
<p><%=getCount()%></p>
</body>
</html>
Sunday, May 31, 2009
INTRODUCTION TO JSP TAGS
In this lesson we will learn about the various tags available in JSP with suitable examples. In JSP tags can be devided into 4 different types. These are:
1. Directives
In the directives we can import packages, define error handling pages or the session information of the JSP page.
2. Declarations
This tag is used for defining the functions and variables to be used in the JSP.
3. Scriplets
In this tag we can insert any amount of valid java code and these codes are placed in _jspService method by the JSP engine.
4. Expressions
We can use this tag to output any data on the generated page. These data are automatically converted to string and printed on the output stream.
Now we will examine each tags in details with examples. DIRECTIVES
Syntax of JSP directives is:
<%@directive attribute="value" %>
Where directive may be:
1. page: page is used to provide the information about it.
Example: <%@page language="java" %>
2. include: include is used to include a file in the JSP page.
Example: <%@ include file="/header.jsp" %>
3. taglib: taglib is used to use the custom tags in the JSP pages (custom tags allows us to defined our own tags).
Example:<%@ taglib uri="tlds/taglib.tld" prefix="mytag" %>
and attribute may be:
1. language="java"
This tells the server that the page is using the java language. Current JSP specification supports only java language.
Example: <%@page language="java" %>
2. extends="mypackage.myclass"
This attribute is used when we want to extend any class. We can use comma(,) to import more than one packages.
Example:<%@page language="java" import="java.sql.*,mypackage.myclass" %>
3. session="true"
When this value is true session data is available to the JSP page otherwise not. By default this value is true.
Example: <%@page language="java" session="true" %>
4. errorPage="error.jsp"
errorPage is used to handle the un-handled exceptions in the page.
Example: <%@page language="java" session="true" errorPage="error.jsp" %>
5. contentType="text/html;charset=ISO-8859-1"
Use this attribute to set the mime type and character set of the JSP.
Example: <%@page language="java" session="true" contentType="text/html;charset=ISO-8859-1" %>
1. Directives
In the directives we can import packages, define error handling pages or the session information of the JSP page.
2. Declarations
This tag is used for defining the functions and variables to be used in the JSP.
3. Scriplets
In this tag we can insert any amount of valid java code and these codes are placed in _jspService method by the JSP engine.
4. Expressions
We can use this tag to output any data on the generated page. These data are automatically converted to string and printed on the output stream.
Now we will examine each tags in details with examples. DIRECTIVES
Syntax of JSP directives is:
<%@directive attribute="value" %>
Where directive may be:
1. page: page is used to provide the information about it.
Example: <%@page language="java" %>
2. include: include is used to include a file in the JSP page.
Example: <%@ include file="/header.jsp" %>
3. taglib: taglib is used to use the custom tags in the JSP pages (custom tags allows us to defined our own tags).
Example:<%@ taglib uri="tlds/taglib.tld" prefix="mytag" %>
and attribute may be:
1. language="java"
This tells the server that the page is using the java language. Current JSP specification supports only java language.
Example: <%@page language="java" %>
2. extends="mypackage.myclass"
This attribute is used when we want to extend any class. We can use comma(,) to import more than one packages.
Example:<%@page language="java" import="java.sql.*,mypackage.myclass" %>
3. session="true"
When this value is true session data is available to the JSP page otherwise not. By default this value is true.
Example: <%@page language="java" session="true" %>
4. errorPage="error.jsp"
errorPage is used to handle the un-handled exceptions in the page.
Example: <%@page language="java" session="true" errorPage="error.jsp" %>
5. contentType="text/html;charset=ISO-8859-1"
Use this attribute to set the mime type and character set of the JSP.
Example: <%@page language="java" session="true" contentType="text/html;charset=ISO-8859-1" %>
JSP Actions
In this section we will explain you about JSP Action tags and in the next section we will explain the uses of these tags with examples. We will also show how to use JSP Action Tags in the JSP application.
What is JSP Actions?
Servlet container provides many built in functionality to ease the development of the applications. Programmers can use these functions in JSP applications. The JSP Actions tags enables the programmer to use these functions. The JSP Actions are XML tags that can be used in the JSP page.
Here is the list of JSP Actions:
* jsp:include
The jsp:include action work as a subroutine, the Java servlet temporarily passes the request and response to the specified JSP/Servlet. Control is then returned back to the current JSP page.
* jsp:param
The jsp:param action is used to add the specific parameter to current request. The jsp:param tag can be used inside a jsp:include, jsp:forward or jsp:params block.
* jsp:forward
The jsp:forward tag is used to hand off the request and response to another JSP or servlet. In this case the request never return to the calling JSP page.
* jsp:plugin
In older versions of Netscape Navigator and Internet Explorer; different tags is used to embed applet. The jsp:plugin tag actually generates the appropriate HTML code the embed the Applets correctly.
* jsp:fallback
The jsp:fallback tag is used to specify the message to be shown on the browser if applets is not supported by browser.
Example:
<jsp:fallback>
</jsp:fallback>
* jsp:getProperty
The jsp:getPropertyB is used to get specified property from the JavaBean object.
* jsp:setProperty
The jsp:setProperty tag is used to set a property in the JavaBean object.
* jsp:useBean
The jsp:useBean tag is used to instantiate an object of Java Bean or it can re-use existing java bean object.
In the next sections we will learn how to use these JSP Actions (JSP Action tags).
What is JSP Actions?
Servlet container provides many built in functionality to ease the development of the applications. Programmers can use these functions in JSP applications. The JSP Actions tags enables the programmer to use these functions. The JSP Actions are XML tags that can be used in the JSP page.
Here is the list of JSP Actions:
* jsp:include
The jsp:include action work as a subroutine, the Java servlet temporarily passes the request and response to the specified JSP/Servlet. Control is then returned back to the current JSP page.
* jsp:param
The jsp:param action is used to add the specific parameter to current request. The jsp:param tag can be used inside a jsp:include, jsp:forward or jsp:params block.
* jsp:forward
The jsp:forward tag is used to hand off the request and response to another JSP or servlet. In this case the request never return to the calling JSP page.
* jsp:plugin
In older versions of Netscape Navigator and Internet Explorer; different tags is used to embed applet. The jsp:plugin tag actually generates the appropriate HTML code the embed the Applets correctly.
* jsp:fallback
The jsp:fallback tag is used to specify the message to be shown on the browser if applets is not supported by browser.
Example:
<jsp:fallback>
Unable to load applet
</jsp:fallback>
* jsp:getProperty
The jsp:getPropertyB is used to get specified property from the JavaBean object.
* jsp:setProperty
The jsp:setProperty tag is used to set a property in the JavaBean object.
* jsp:useBean
The jsp:useBean tag is used to instantiate an object of Java Bean or it can re-use existing java bean object.
In the next sections we will learn how to use these JSP Actions (JSP Action tags).
JSP ARCHITECTURE
JSP pages are high level extension of servlet and it enable the developers to embed java code in html pages. JSP files are finally compiled into a servlet by the JSP engine. Compiled servlet is used by the engine to serve the requests.
javax.servlet.jsp package defines two interfaces:
*
JSPPage
*
HttpJspPage
These interfaces defines the three methods for the compiled JSP page. These methods are:
* jspInit()
* jspDestroy()
* _jspService(HttpServletRequest request,HttpServletResponse response)
In the compiled JSP file these methods are present. Programmer can define jspInit() and jspDestroy() methods, but the _jspService(HttpServletRequest request,HttpServletResponse response) method is generated by the JSP engine.
javax.servlet.jsp package defines two interfaces:
*
JSPPage
*
HttpJspPage
These interfaces defines the three methods for the compiled JSP page. These methods are:
* jspInit()
* jspDestroy()
* _jspService(HttpServletRequest request,HttpServletResponse response)
In the compiled JSP file these methods are present. Programmer can define jspInit() and jspDestroy() methods, but the _jspService(HttpServletRequest request,HttpServletResponse response) method is generated by the JSP engine.
Tutorials - Java Server Pages Technology
Java Server Pages
JavaServer Pages (JSP) technology is the Java platform technology for delivering dynamic content to web clients in a portable, secure and well-defined way. The JavaServer Pages specification extends the Java Servlet API to provide web application developers
with a robust framework for creating dynamic web content on the server using HTML, and XML templates, and Java code, which is secure, fast, and independent of server platforms. JSP has been built on top of the Servlet API and utilizes Servlet semantics. JSP has become the preferred request handler and response mechanism. Although JSP technology is going to be a powerful successor to basic Servlets, they have an evolutionary relationship and can be used in a cooperative and complementary manner.
Servlets are powerful and sometimes they are a bit cumbersome when it comes to generating complex HTML. Most servlets contain a little code that handles application logic and a lot more code that handles output formatting. This can make it difficult to separate and reuse portions of the code when a different output format is needed. For these reasons, web application developers turn towards JSP as their preferred servlet environment.
Evolution of Web Applications
Over the last few years, web server applications have evolved from static to dynamic applications. This evolution became necessary due to some deficiencies in earlier web site design. For example, to put more of business processes on the web, whether in business-to-consumer (B2C) or business-to-business (B2B) markets, conventional web site design technologies are not enough. The main issues, every developer faces when developing web applications, are:
1. Scalability - a successful site will have more users and as the number of users is increasing fastly, the web applications have to scale correspondingly.
2. Integration of data and business logic - the web is just another way to conduct business, and so it should be able to use the same middle-tier and data-access code.
3. Manageability - web sites just keep getting bigger and we need some viable mechanism to manage the ever-increasing content and its interaction with business systems.
4. Personalization - adding a personal touch to the web page becomes an essential factor to keep our customer coming back again. Knowing their preferences, allowing them to configure the information they view, remembering their past transactions or frequent search keywords are all important in providing feedback and interaction from what is otherwise a fairly one-sided conversation.
Apart from these general needs for a business-oriented web site, the necessity for new technologies to create robust, dynamic and compact server-side web applications has been realized. The main characteristics of today's dynamic web server applications are as follows:
1. Serve HTML and XML, and stream data to the web client
2. Separate presentation, logic and data
3. Interface to databases, other Java applications, CORBA, directory and mail services
4. Make use of application server middleware to provide transactional support.
5. Track client sessions
Now let us have a look on the role of Java technology and platform in this regard.
Java's Role for Server Applications
Sun Microsystems, having consulted many expert partners from other related IT industries, has come out with a number of open APIs for the technologies and services on server side. This collection of APIs is named as Java 2 Enterprise Edition (J2EE). The J2EE specification provides a platform for enterprise applications, with full API support for enterprise code and guarantees of portability between server implementations. Also it brings a clear division between code which deals with presentation, business logic and data.
The J2EE specification meets the needs of web applications because it provides:
1. Rich interaction with a web server via servlets and built-in support for sessions available in both servlets and EJBs.
2. The use of EJBs to mirror the user interaction with data by providing automatic session and transaction support to EJBs operating in the EJB server.
3. Entity EJBs to represent data as an object and seamless integration with the Java data access APIs
4. Flexible template-based output using JSP and XML
This family of APIs mean that the final web page can be generated from a user input request, which was processed by a servlet or JSP and a session EJB, which represents the user's session with the server, using data extracted from a database and put into an entity EJB. Thus, the Java revolution of portable code and open APIs is married with an evolution in existing products such as database, application, mail and web servers. The wide availability of products to run Java applications on the server has made this a fast-moving and very competitive market, but the essential compatibility through specifications, standard APIs and class libraries has held. This makes server-side Java a very exciting area.
JavaServer Pages - An Overview
The JavaServer Pages 1.2 specification provides web developers with a framework to build applications containing dynamic web content such as HTML, DHTML, XHTML and XML. A JSP page is a text based document containing static HTML and dynamic actions which describe how to process a response to the client in a more powerful and flexible manner. Most of a JSP file is plain HTML but it also has, interspersed with it, special JSP tags.
There are many JSP tags such as:
* JSP directive denoted by <%@,
2. scriplets indicated by <% ... %> tags and
* directive includes the contents of the file sample.html in the response at that point.
To process a JSP file, we need a JSP engine that can be connected with a web server or can be accommodated inside a web server. Firstly when a web browser seeks a JSP file through an URL from the web server, the web server recognizes the .jsp file extension in the URL requested by the browser and understands that the requested resource is a JavaServer Page. Then the web server passes the request to the JSP engine. The JSP page is then translated into a Java class, which is then compiled into a servlet.
This translation and compilation phase occurs only when the JSP file is requested for the first time, or if it undergoes any changes to the extent of getting retranslated and recompiled. For each additional request of the JSP page thereafter, the request directly goes to the servlet byte code, which is already in memory. Thus when a request comes for a servlet, an init() method is called when the Servlet is first loaded into the virtual machine, to perform any global initialization that every request of the servlet will need. Then the individual requests are sent to a service() method, where the response is put together. The servlet creates a new thread to run service() method for each request. The request from the browser is converted into a Java object of type HttpServletRequest, which is passed to the Servlet along with an HttpServletResponse object that is used to send the response back to the browser. The servlet code performs the operations specified by the JSP elements in the .jsp file.
The Components of JSPs
JSP syntax is almost similar to XML syntax. The following general rules are applicable to all JSP tags.
1. Tags have either a start tag with optional attributes, an optional body, and a matching end tag or they have an empty tag possibly with attributes.
2. Attribute values in the tag always appear quoted. The special strings ' and " can be used if quotes are a part of the attribute value itself.
Any whitespace within the body text of a document is not significant, but is preserved, which means that any whitespace in the JSP being translated is read and preserved during translation into a servlet.
The character \ can be used as an escape character in a tag, for instance, to use the % character, \% can be used.
JavaServer Pages are text files that combine standard HTML and new scripting tags. JSPs look like HTML, but they get compiled into Java servlets the first time they are invoked. The resulting servlet is a combination of HTML from the JSP file and embedded dynamic content specified by the new tags. Everything in a JSP page can be divided into two categories:
1. Elements that are processed on the server
2. Template data or everything other than elements, that the engine processing the JSP engines.
Element data or that part of the JSP which is processed on the server, can be classified into the following categories:
1. Directives
2. Scripting elements
3. Standard actions
JSP directives serve as messages to the JSP container from the JSP. They are used to set global values such as class declaration, methods to be implemented, output content type, etc. They do not produce any output to the client. All directives have scope of the entire JSP file. That is, a directive affects the whole JSP file, and only that JSP file. Directives are characterized by the @ character within the tag and the general syntax is:
The three directives are page, include and taglib.
Scripting elements are used to include scripting code (Java code) within the JSP. They allow to declare variables and methods, include arbitrary scripting code and evaluate an expression. The three types of scripting element are: Declaration, Scriptlets and Expressions.
A declaration is a block of Java code in a JSP that is used to define class-wide variables and methods in the generated class file. Declarations are initialized when the JSP page is initialized and have class scope. Anything defined in a declaration is available throughout the JSP, to other declarations, expressions or code.
A scriptlet consists of one or more valid Java statements. A scriptlet is a block of Java code that is executed at request-processing time. A scriptlet is enclosed between "<%" and "%>". What the scriptlet actually does depends on the code, and it can produce output into the output stream to the client. Multiple scriptlets are combined in the compiled class in the order in which they appear in the JSP. Scriptlets like any other Java code block or method, can modify objects inside them as a result of method invocations.
An expression is a shorthand notation for a scriptlet that outputs a value in the response stream back to the client. When the expression is evaluated, the result is converted to a string and displayed, An expression is enclosed within <%= and %> "<%=" and "%>". If any part of expression is an object, the conversion is done using the toString() method of the object.
Standard actions are specific tags that affect the runtime behavior of the JSP and affect the response sent back to the client. The JSP specification lists some standard action types to be provided by all containers, irrespective of the implementation. Standard actions provide page authors with some basic functionality to exploit; the vendor is free to provide other actions to enhance behavior.
How JSP and JSP Container function
A JSP page is executed in a JSP container or a JSP engine, which is installed in a web server or in a application server. When a client asks for a JSP page the engine wraps up the request and delivers it to the JSP page along with a response object. The JSP page processes the request and modifies the response object to incorporate the communication with the client. The container or the engine, on getting the response, wraps up the responses from the JSP page and delivers it to the client. The underlying layer for a JSP is actually a servlet implementation. The abstractions of the request and response are the same as the ServletRequest and ServletResponse respectively. If the protocol used is HTTP, then the corresponding objects are HttpServletRequest and HttpServletResponse.
The first time the engine intercepts a request for a JSP, it compiles this translation unit (the JSP page and other dependent files) into a class file that implements the servlet protocol. If the dependent files are other JSPs they are compiled into their own classes. The servlet class generated at the end of the translation process must extend a superclass that is either
1. specified by the JSP author through the use of the extends attribute in the page directive or
2. is a JSP container specific implementation class that implements javax.servlet.jsp.JspPage interface and provides some basic page specific behavior.
Since most JSP pages use HTTP, their implementation classes must actually implement the javax.servlet.jsp.HttpJspPage interface, which is a sub interface of javax.servlet.jsp.JspPage.
The javax.servlet.jsp.JspPage interface contains two methods:
1. public void jspInit() - This method is invoked when the JSP is initialized and the page authors are free to provide initialization of the JSP by implementing this method in their JSPs.
2. public void jspDestroy() - This method is invoked when the JSP is about to be destroyed by the container. Similar to above, page authors can provide their own implementation.
The javax.servlet.jsp.HttpJspPage interface contains one method:
public void _jspService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
This method generated by the JSP container is invoked, every time a request comes to the JSP. The request is processed and the JSP generates appropriate response. This response is taken by the container and passed back to the client.
JSP Architecture
There are two basic ways of using the JSP technology. They are the client/server (page-centric) 2-tier approach and the N-tier approach (dispatcher).
The Page-Centric Approach
Applications built using a client-server (2-tier) approach consist of one or more application programs running on client machines and connecting to a server-based application to work. With the arrival of Servlets technology, 2-tier applications could also be developed using Java programming language. This model allows JSPs or Servlets direct access to some resource such as database or legacy application to service a client's request. The JSP page is where the incoming request is intercepted, processed and the response sent back to the client. JSPs differ from Servlets in this scenario by providing clean code, separating code from the content by placing data access in EJBs. Even though this model makes application development easier, it does not scale up well for a large number of simultaneous clients as it entails a significant amount of request processing to be performed and each request must establish or share a potentially scarce/expensive connection to the resource in question.
Page-view - This basic architecture involves direct request invocations to a server page with embedded Java code, and markup tags which dynamically generate output for substitution within the HTML. This approach has been blessed a number of benefits. It is very straightforward and is a low-overhead approach from a developerment perspective. All the Java code may be embedded within the HTML, so changes are confined to a very limited area, reducing complexity drastically.
The big trade-off here is in the level of sophistication. As the scale of the system grows, some limitations begin to surface, such as bloating of business logic code in the page instead of factoring forward to a mediating Servlet or factoring back to a worker bean. It is a fact that utilizing a Servlet and helper beans helps to separate developer roles more cleanly and improves the potential for code reuse.
Page-view with bean - This pattern is used when the above architecture becomes too cluttered with business-related code and data access code. The Java code representing the business logic and simple data storage implementation in the previous model moves from the JSP to the JavaBean worker. This refactoring leaves a much cleaner JSP with limited Java code, which can be comfortably owned by an individual in a web-production role, since it encapsulates mostly markup tags.
The Dispatcher Approach
In this approach, a Servlet or JSP acts as a mediator or controller, delegating requests to JSP pages and JavaBeans. There are three different architectures. They are mediator-view, mediator-composite view and service to workers.
In an N-tier application, the server side of the architecture is broken up into multiple tiers. In this case, the application is composed of multiple tiers, where the middle tier, the JSP, interacts with the back end resources via another object or EJBs component. The Enterprise JavaBeans server and the EJB provide managed access to resources, support transactions and access to underlying security mechanisms, thus addressing the resource sharing and performance issues of the 2-tier approach.
The first step in N-tiered application design should be identifying the correct objects and their interaction and the second step is identifying the JSPs or Servlets. These are divided into two categories.
Front end JSPs or Servlets manage application flow and business logic evaluation. They act as a point to intercept the HTTP requests coming from the users. They provide a single entry point to an application, simplifying security management and making application state easier to maintain.
Presentation JSPs or Servlets generate HTML or XML with their main purpose in life being presentation of dynamic content. They contain only presentation and rendering logic.
These categories resemble to the Modal-View design pattern, where the front-end components is the model and the presentation component the view. In this approach, JSPs are used to generate the presentation layer and either JSPs or Servlets to perform process-intensive tasks. The front-end component acts as the controller and is in charge of the request processing and the creation of any beans or objects used by the presentation JSP, as well as deciding, depending on the user's actions, which JSP to forward this request to. There is no processing logic within the presentation JSP itself and it simply responsible for retrieving any objects or beans that may have been previously created by the Servlet and extracting the dynamic content for insertion within static templates.
Benefits of JSP
One of the main reasons why the JavaServer Pages technology has evolved into what it is today and it is still evolving is the overwhelming technical need to simplify application design by separating dynamic content from static template display data. Another benefit of utilizing JSP is that it allows to more cleanly separate the roles of web application/HTML designer from a software developer. The JSP technology is blessed with a number of exciting benefits, which are chronicled as follows:
1. The JSP technology is platform independent, in its dynamic web pages, its web servers, and its underlying server components. That is, JSP pages perform perfectly without any hassle on any platform, run on any web server, and web-enabled application server. The JSP pages can be accessed from any web server.
2. The JSP technology emphasizes the use of reusable components. These components can be combined or manipulated towards developing more purposeful components and page design. This definitely reduces development time apart from the At development time, JSPs are very different from Servlets, however, they are precompiled into Servlets at run time and executed by a JSP engine which is installed on a Web-enabled application server such as BEA WebLogic and IBM WebSphere.
Conclusion
JSP and Servlets are gaining rapid acceptance as means to provide dynamic content on the Internet. With full access to the Java platform, running from the server in a secure manner, the application possibilities are almost limitless. When JSPs are used with Enterprise JavaBeans technology, e-commerce and database resources can be further enhanced to meet an enterprise's needs for web applications providing secure transactions in an open platform. J2EE technology as a whole makes it easy to develop, deploy and use web server applications instead of mingling with other technologies such as CGI and ASP. There are many tools for facilitating quick web software development and to easily convert existing server-side technologies to JSP and Servlets.
Many application server vendors are aggressively deploying JSP within their products. This results in developing robust e-commerce applications as JSP provides XML functionality and scalability. By providing a clear separation between content and coding, JSP solves many problems attached with existing server-side applications.
JavaServer Pages (JSP) technology is the Java platform technology for delivering dynamic content to web clients in a portable, secure and well-defined way. The JavaServer Pages specification extends the Java Servlet API to provide web application developers
with a robust framework for creating dynamic web content on the server using HTML, and XML templates, and Java code, which is secure, fast, and independent of server platforms. JSP has been built on top of the Servlet API and utilizes Servlet semantics. JSP has become the preferred request handler and response mechanism. Although JSP technology is going to be a powerful successor to basic Servlets, they have an evolutionary relationship and can be used in a cooperative and complementary manner.
Servlets are powerful and sometimes they are a bit cumbersome when it comes to generating complex HTML. Most servlets contain a little code that handles application logic and a lot more code that handles output formatting. This can make it difficult to separate and reuse portions of the code when a different output format is needed. For these reasons, web application developers turn towards JSP as their preferred servlet environment.
Evolution of Web Applications
Over the last few years, web server applications have evolved from static to dynamic applications. This evolution became necessary due to some deficiencies in earlier web site design. For example, to put more of business processes on the web, whether in business-to-consumer (B2C) or business-to-business (B2B) markets, conventional web site design technologies are not enough. The main issues, every developer faces when developing web applications, are:
1. Scalability - a successful site will have more users and as the number of users is increasing fastly, the web applications have to scale correspondingly.
2. Integration of data and business logic - the web is just another way to conduct business, and so it should be able to use the same middle-tier and data-access code.
3. Manageability - web sites just keep getting bigger and we need some viable mechanism to manage the ever-increasing content and its interaction with business systems.
4. Personalization - adding a personal touch to the web page becomes an essential factor to keep our customer coming back again. Knowing their preferences, allowing them to configure the information they view, remembering their past transactions or frequent search keywords are all important in providing feedback and interaction from what is otherwise a fairly one-sided conversation.
Apart from these general needs for a business-oriented web site, the necessity for new technologies to create robust, dynamic and compact server-side web applications has been realized. The main characteristics of today's dynamic web server applications are as follows:
1. Serve HTML and XML, and stream data to the web client
2. Separate presentation, logic and data
3. Interface to databases, other Java applications, CORBA, directory and mail services
4. Make use of application server middleware to provide transactional support.
5. Track client sessions
Now let us have a look on the role of Java technology and platform in this regard.
Java's Role for Server Applications
Sun Microsystems, having consulted many expert partners from other related IT industries, has come out with a number of open APIs for the technologies and services on server side. This collection of APIs is named as Java 2 Enterprise Edition (J2EE). The J2EE specification provides a platform for enterprise applications, with full API support for enterprise code and guarantees of portability between server implementations. Also it brings a clear division between code which deals with presentation, business logic and data.
The J2EE specification meets the needs of web applications because it provides:
1. Rich interaction with a web server via servlets and built-in support for sessions available in both servlets and EJBs.
2. The use of EJBs to mirror the user interaction with data by providing automatic session and transaction support to EJBs operating in the EJB server.
3. Entity EJBs to represent data as an object and seamless integration with the Java data access APIs
4. Flexible template-based output using JSP and XML
This family of APIs mean that the final web page can be generated from a user input request, which was processed by a servlet or JSP and a session EJB, which represents the user's session with the server, using data extracted from a database and put into an entity EJB. Thus, the Java revolution of portable code and open APIs is married with an evolution in existing products such as database, application, mail and web servers. The wide availability of products to run Java applications on the server has made this a fast-moving and very competitive market, but the essential compatibility through specifications, standard APIs and class libraries has held. This makes server-side Java a very exciting area.
JavaServer Pages - An Overview
The JavaServer Pages 1.2 specification provides web developers with a framework to build applications containing dynamic web content such as HTML, DHTML, XHTML and XML. A JSP page is a text based document containing static HTML and dynamic actions which describe how to process a response to the client in a more powerful and flexible manner. Most of a JSP file is plain HTML but it also has, interspersed with it, special JSP tags.
There are many JSP tags such as:
* JSP directive denoted by <%@,
2. scriplets indicated by <% ... %> tags and
* directive includes the contents of the file sample.html in the response at that point.
To process a JSP file, we need a JSP engine that can be connected with a web server or can be accommodated inside a web server. Firstly when a web browser seeks a JSP file through an URL from the web server, the web server recognizes the .jsp file extension in the URL requested by the browser and understands that the requested resource is a JavaServer Page. Then the web server passes the request to the JSP engine. The JSP page is then translated into a Java class, which is then compiled into a servlet.
This translation and compilation phase occurs only when the JSP file is requested for the first time, or if it undergoes any changes to the extent of getting retranslated and recompiled. For each additional request of the JSP page thereafter, the request directly goes to the servlet byte code, which is already in memory. Thus when a request comes for a servlet, an init() method is called when the Servlet is first loaded into the virtual machine, to perform any global initialization that every request of the servlet will need. Then the individual requests are sent to a service() method, where the response is put together. The servlet creates a new thread to run service() method for each request. The request from the browser is converted into a Java object of type HttpServletRequest, which is passed to the Servlet along with an HttpServletResponse object that is used to send the response back to the browser. The servlet code performs the operations specified by the JSP elements in the .jsp file.
The Components of JSPs
JSP syntax is almost similar to XML syntax. The following general rules are applicable to all JSP tags.
1. Tags have either a start tag with optional attributes, an optional body, and a matching end tag or they have an empty tag possibly with attributes.
2. Attribute values in the tag always appear quoted. The special strings ' and " can be used if quotes are a part of the attribute value itself.
Any whitespace within the body text of a document is not significant, but is preserved, which means that any whitespace in the JSP being translated is read and preserved during translation into a servlet.
The character \ can be used as an escape character in a tag, for instance, to use the % character, \% can be used.
JavaServer Pages are text files that combine standard HTML and new scripting tags. JSPs look like HTML, but they get compiled into Java servlets the first time they are invoked. The resulting servlet is a combination of HTML from the JSP file and embedded dynamic content specified by the new tags. Everything in a JSP page can be divided into two categories:
1. Elements that are processed on the server
2. Template data or everything other than elements, that the engine processing the JSP engines.
Element data or that part of the JSP which is processed on the server, can be classified into the following categories:
1. Directives
2. Scripting elements
3. Standard actions
JSP directives serve as messages to the JSP container from the JSP. They are used to set global values such as class declaration, methods to be implemented, output content type, etc. They do not produce any output to the client. All directives have scope of the entire JSP file. That is, a directive affects the whole JSP file, and only that JSP file. Directives are characterized by the @ character within the tag and the general syntax is:
The three directives are page, include and taglib.
Scripting elements are used to include scripting code (Java code) within the JSP. They allow to declare variables and methods, include arbitrary scripting code and evaluate an expression. The three types of scripting element are: Declaration, Scriptlets and Expressions.
A declaration is a block of Java code in a JSP that is used to define class-wide variables and methods in the generated class file. Declarations are initialized when the JSP page is initialized and have class scope. Anything defined in a declaration is available throughout the JSP, to other declarations, expressions or code.
A scriptlet consists of one or more valid Java statements. A scriptlet is a block of Java code that is executed at request-processing time. A scriptlet is enclosed between "<%" and "%>". What the scriptlet actually does depends on the code, and it can produce output into the output stream to the client. Multiple scriptlets are combined in the compiled class in the order in which they appear in the JSP. Scriptlets like any other Java code block or method, can modify objects inside them as a result of method invocations.
An expression is a shorthand notation for a scriptlet that outputs a value in the response stream back to the client. When the expression is evaluated, the result is converted to a string and displayed, An expression is enclosed within <%= and %> "<%=" and "%>". If any part of expression is an object, the conversion is done using the toString() method of the object.
Standard actions are specific tags that affect the runtime behavior of the JSP and affect the response sent back to the client. The JSP specification lists some standard action types to be provided by all containers, irrespective of the implementation. Standard actions provide page authors with some basic functionality to exploit; the vendor is free to provide other actions to enhance behavior.
How JSP and JSP Container function
A JSP page is executed in a JSP container or a JSP engine, which is installed in a web server or in a application server. When a client asks for a JSP page the engine wraps up the request and delivers it to the JSP page along with a response object. The JSP page processes the request and modifies the response object to incorporate the communication with the client. The container or the engine, on getting the response, wraps up the responses from the JSP page and delivers it to the client. The underlying layer for a JSP is actually a servlet implementation. The abstractions of the request and response are the same as the ServletRequest and ServletResponse respectively. If the protocol used is HTTP, then the corresponding objects are HttpServletRequest and HttpServletResponse.
The first time the engine intercepts a request for a JSP, it compiles this translation unit (the JSP page and other dependent files) into a class file that implements the servlet protocol. If the dependent files are other JSPs they are compiled into their own classes. The servlet class generated at the end of the translation process must extend a superclass that is either
1. specified by the JSP author through the use of the extends attribute in the page directive or
2. is a JSP container specific implementation class that implements javax.servlet.jsp.JspPage interface and provides some basic page specific behavior.
Since most JSP pages use HTTP, their implementation classes must actually implement the javax.servlet.jsp.HttpJspPage interface, which is a sub interface of javax.servlet.jsp.JspPage.
The javax.servlet.jsp.JspPage interface contains two methods:
1. public void jspInit() - This method is invoked when the JSP is initialized and the page authors are free to provide initialization of the JSP by implementing this method in their JSPs.
2. public void jspDestroy() - This method is invoked when the JSP is about to be destroyed by the container. Similar to above, page authors can provide their own implementation.
The javax.servlet.jsp.HttpJspPage interface contains one method:
public void _jspService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
This method generated by the JSP container is invoked, every time a request comes to the JSP. The request is processed and the JSP generates appropriate response. This response is taken by the container and passed back to the client.
JSP Architecture
There are two basic ways of using the JSP technology. They are the client/server (page-centric) 2-tier approach and the N-tier approach (dispatcher).
The Page-Centric Approach
Applications built using a client-server (2-tier) approach consist of one or more application programs running on client machines and connecting to a server-based application to work. With the arrival of Servlets technology, 2-tier applications could also be developed using Java programming language. This model allows JSPs or Servlets direct access to some resource such as database or legacy application to service a client's request. The JSP page is where the incoming request is intercepted, processed and the response sent back to the client. JSPs differ from Servlets in this scenario by providing clean code, separating code from the content by placing data access in EJBs. Even though this model makes application development easier, it does not scale up well for a large number of simultaneous clients as it entails a significant amount of request processing to be performed and each request must establish or share a potentially scarce/expensive connection to the resource in question.
Page-view - This basic architecture involves direct request invocations to a server page with embedded Java code, and markup tags which dynamically generate output for substitution within the HTML. This approach has been blessed a number of benefits. It is very straightforward and is a low-overhead approach from a developerment perspective. All the Java code may be embedded within the HTML, so changes are confined to a very limited area, reducing complexity drastically.
The big trade-off here is in the level of sophistication. As the scale of the system grows, some limitations begin to surface, such as bloating of business logic code in the page instead of factoring forward to a mediating Servlet or factoring back to a worker bean. It is a fact that utilizing a Servlet and helper beans helps to separate developer roles more cleanly and improves the potential for code reuse.
Page-view with bean - This pattern is used when the above architecture becomes too cluttered with business-related code and data access code. The Java code representing the business logic and simple data storage implementation in the previous model moves from the JSP to the JavaBean worker. This refactoring leaves a much cleaner JSP with limited Java code, which can be comfortably owned by an individual in a web-production role, since it encapsulates mostly markup tags.
The Dispatcher Approach
In this approach, a Servlet or JSP acts as a mediator or controller, delegating requests to JSP pages and JavaBeans. There are three different architectures. They are mediator-view, mediator-composite view and service to workers.
In an N-tier application, the server side of the architecture is broken up into multiple tiers. In this case, the application is composed of multiple tiers, where the middle tier, the JSP, interacts with the back end resources via another object or EJBs component. The Enterprise JavaBeans server and the EJB provide managed access to resources, support transactions and access to underlying security mechanisms, thus addressing the resource sharing and performance issues of the 2-tier approach.
The first step in N-tiered application design should be identifying the correct objects and their interaction and the second step is identifying the JSPs or Servlets. These are divided into two categories.
Front end JSPs or Servlets manage application flow and business logic evaluation. They act as a point to intercept the HTTP requests coming from the users. They provide a single entry point to an application, simplifying security management and making application state easier to maintain.
Presentation JSPs or Servlets generate HTML or XML with their main purpose in life being presentation of dynamic content. They contain only presentation and rendering logic.
These categories resemble to the Modal-View design pattern, where the front-end components is the model and the presentation component the view. In this approach, JSPs are used to generate the presentation layer and either JSPs or Servlets to perform process-intensive tasks. The front-end component acts as the controller and is in charge of the request processing and the creation of any beans or objects used by the presentation JSP, as well as deciding, depending on the user's actions, which JSP to forward this request to. There is no processing logic within the presentation JSP itself and it simply responsible for retrieving any objects or beans that may have been previously created by the Servlet and extracting the dynamic content for insertion within static templates.
Benefits of JSP
One of the main reasons why the JavaServer Pages technology has evolved into what it is today and it is still evolving is the overwhelming technical need to simplify application design by separating dynamic content from static template display data. Another benefit of utilizing JSP is that it allows to more cleanly separate the roles of web application/HTML designer from a software developer. The JSP technology is blessed with a number of exciting benefits, which are chronicled as follows:
1. The JSP technology is platform independent, in its dynamic web pages, its web servers, and its underlying server components. That is, JSP pages perform perfectly without any hassle on any platform, run on any web server, and web-enabled application server. The JSP pages can be accessed from any web server.
2. The JSP technology emphasizes the use of reusable components. These components can be combined or manipulated towards developing more purposeful components and page design. This definitely reduces development time apart from the At development time, JSPs are very different from Servlets, however, they are precompiled into Servlets at run time and executed by a JSP engine which is installed on a Web-enabled application server such as BEA WebLogic and IBM WebSphere.
Conclusion
JSP and Servlets are gaining rapid acceptance as means to provide dynamic content on the Internet. With full access to the Java platform, running from the server in a secure manner, the application possibilities are almost limitless. When JSPs are used with Enterprise JavaBeans technology, e-commerce and database resources can be further enhanced to meet an enterprise's needs for web applications providing secure transactions in an open platform. J2EE technology as a whole makes it easy to develop, deploy and use web server applications instead of mingling with other technologies such as CGI and ASP. There are many tools for facilitating quick web software development and to easily convert existing server-side technologies to JSP and Servlets.
Many application server vendors are aggressively deploying JSP within their products. This results in developing robust e-commerce applications as JSP provides XML functionality and scalability. By providing a clear separation between content and coding, JSP solves many problems attached with existing server-side applications.
Saturday, May 30, 2009
Example Using Scripting Elements and Directives
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Using JavaServer Pages</TITLE>
<META NAME="author" CONTENT="Marty Hall -- hall@apl.jhu.edu">
<META NAME="keywords"
CONTENT="JSP,JavaServer Pages,servlets">
<META NAME="description"
CONTENT="A quick example of the four main JSP tags.">
<LINK REL=STYLESHEET
HREF="My-Style-Sheet.css"
TYPE="text/css">
</HEAD>
<BODY BGCOLOR="#FDF5E6" TEXT="#000000" LINK="#0000EE"
VLINK="#551A8B" ALINK="#FF0000">
<CENTER>
<TABLE BORDER=5 BGCOLOR="#EF8429">
<TR><TH CLASS="TITLE">
Using JavaServer Pages</TABLE>
</CENTER>
<P>
Some dynamic content created using various JSP mechanisms:
<UL>
<LI><B>Expression.</B><BR>
Your hostname: <%= request.getRemoteHost() %>.
<LI><B>Scriptlet.</B><BR>
<% out.println("Attached GET data: " +
request.getQueryString()); %>
<LI><B>Declaration (plus expression).</B><BR>
<%! private int accessCount = 0; %>
Accesses to page since server reboot: <%= ++accessCount %>
<LI><B>Directive (plus expression).</B><BR>
<%@ page import = "java.util.*" %>
Current date: <%= new Date() %>
</UL>
</BODY>
</HTML>
Here's a typical result:
<HTML>
<HEAD>
<TITLE>Using JavaServer Pages</TITLE>
<META NAME="author" CONTENT="Marty Hall -- hall@apl.jhu.edu">
<META NAME="keywords"
CONTENT="JSP,JavaServer Pages,servlets">
<META NAME="description"
CONTENT="A quick example of the four main JSP tags.">
<LINK REL=STYLESHEET
HREF="My-Style-Sheet.css"
TYPE="text/css">
</HEAD>
<BODY BGCOLOR="#FDF5E6" TEXT="#000000" LINK="#0000EE"
VLINK="#551A8B" ALINK="#FF0000">
<CENTER>
<TABLE BORDER=5 BGCOLOR="#EF8429">
<TR><TH CLASS="TITLE">
Using JavaServer Pages</TABLE>
</CENTER>
<P>
Some dynamic content created using various JSP mechanisms:
<UL>
<LI><B>Expression.</B><BR>
Your hostname: <%= request.getRemoteHost() %>.
<LI><B>Scriptlet.</B><BR>
<% out.println("Attached GET data: " +
request.getQueryString()); %>
<LI><B>Declaration (plus expression).</B><BR>
<%! private int accessCount = 0; %>
Accesses to page since server reboot: <%= ++accessCount %>
<LI><B>Directive (plus expression).</B><BR>
<%@ page import = "java.util.*" %>
Current date: <%= new Date() %>
</UL>
</BODY>
</HTML>
Here's a typical result:
request,response,out,session,application,config,pageContext,page
request
This is the HttpServletRequest associated with the request, and lets you look at the request parameters (via getParameter), the request type (GET, POST, HEAD, etc.), and the incoming HTTP headers (cookies, Referer, etc.). Strictly speaking, request is allowed to be a subclass of ServletRequest other than HttpServletRequest, if the protocol in the request is something other than HTTP. This is almost never done in response
This is the HttpServletResponse associated with the response to the client. Note that, since the output stream (see out below) is buffered, it is legal to set HTTP status codes and response headers, even though this is not permitted in regular servlets once any output has been sent to the client.
out
This is the PrintWriter used to send output to the client. However, in order to make the response object (see the previous section) useful, this is a buffered version of PrintWriter called JspWriter. Note that you can adjust the buffer size, or even turn buffering off, through use of the buffer attribute of the page directive. This was discussed in Section 5. Also note that out is used almost exclusively in scriptlets, since JSP expressions automatically get placed in the output stream, and thus rarely need to refer to out explicitly.
session
This is the HttpSession object associated with the request. Recall that sessions are created automatically, so this variable is bound even if there was no incoming session reference. The one exception is if you use the session attribute of the page directive (see Section 5) to turn sessions off, in which case attempts to reference the session variable cause errors at the time the JSP page is translated into a servlet.
application
This is the ServletContext as obtained via getServletConfig().getContext().
config
This is the ServletConfig object for this page.
pageContext
JSP introduced a new class called PageContext to encapsulate use of server-specific features like higher performance JspWriters. The idea is that, if you access them through this class rather than directly, your code will still run on "regular" servlet/JSP engines.
page
This is simply a synonym for this, and is not very useful in Java. It was created as a placeholder for the time when the scripting language could be something other than Java.
This is the HttpServletRequest associated with the request, and lets you look at the request parameters (via getParameter), the request type (GET, POST, HEAD, etc.), and the incoming HTTP headers (cookies, Referer, etc.). Strictly speaking, request is allowed to be a subclass of ServletRequest other than HttpServletRequest, if the protocol in the request is something other than HTTP. This is almost never done in response
This is the HttpServletResponse associated with the response to the client. Note that, since the output stream (see out below) is buffered, it is legal to set HTTP status codes and response headers, even though this is not permitted in regular servlets once any output has been sent to the client.
out
This is the PrintWriter used to send output to the client. However, in order to make the response object (see the previous section) useful, this is a buffered version of PrintWriter called JspWriter. Note that you can adjust the buffer size, or even turn buffering off, through use of the buffer attribute of the page directive. This was discussed in Section 5. Also note that out is used almost exclusively in scriptlets, since JSP expressions automatically get placed in the output stream, and thus rarely need to refer to out explicitly.
session
This is the HttpSession object associated with the request. Recall that sessions are created automatically, so this variable is bound even if there was no incoming session reference. The one exception is if you use the session attribute of the page directive (see Section 5) to turn sessions off, in which case attempts to reference the session variable cause errors at the time the JSP page is translated into a servlet.
application
This is the ServletContext as obtained via getServletConfig().getContext().
config
This is the ServletConfig object for this page.
pageContext
JSP introduced a new class called PageContext to encapsulate use of server-specific features like higher performance JspWriters. The idea is that, if you access them through this class rather than directly, your code will still run on "regular" servlet/JSP engines.
page
This is simply a synonym for this, and is not very useful in Java. It was created as a placeholder for the time when the scripting language could be something other than Java.
Predefined Variables
To simplify code in JSP expressions and scriptlets, you are supplied with eight automatically defined variables, sometimes called implicit objects. The available variables are request, response, out, session, application, config, pageContext, and page. Details for each are given below.
The JSP include Directive
This directive lets you include files at the time the JSP page is translated into a servlet. The directive looks like this:
<%@ include file="relative url" %>
The URL specified is normally interpreted relative to the JSP page that refers to it, but, as with relative URLs in general, you can tell the system to interpret the URL relative to the home directory of the Web server by starting the URL with a forward slash. The contents of the included file are parsed as regular JSP text, and thus can include static HTML, scripting elements, directives, and actions.
For example, many sites include a small navigation bar on each page. Due to problems with HTML frames, this is usually implemented by way of a small table across the top of the page or down the left-hand side, with the HTML repeated for each page in the site. The include directive is a natural way of doing this, saving the developers from the maintenance nightmare of actually copying the HTML into each separate file. Here's some representative code:
Servlet Tutorial: JavaServer Pages (JSP) 1.0
HREF="Site-Styles.css"
TYPE="text/css">
<%@ include file="/navbar.html" %>
Note that since the include directive inserts the files at the time the page is translated, if the navigation bar changes, you need to re-translate all the JSP pages that refer to it. This is a good compromise in a situation like this, since the navigation bar probably changes infrequently, and you want the inclusion process to be as efficient as possible. If, however, the included files changed more often, you could use the jsp:include action instead. This includes the file at the time the JSP page is requested, and is discussed in the tutorial
<%@ include file="relative url" %>
The URL specified is normally interpreted relative to the JSP page that refers to it, but, as with relative URLs in general, you can tell the system to interpret the URL relative to the home directory of the Web server by starting the URL with a forward slash. The contents of the included file are parsed as regular JSP text, and thus can include static HTML, scripting elements, directives, and actions.
For example, many sites include a small navigation bar on each page. Due to problems with HTML frames, this is usually implemented by way of a small table across the top of the page or down the left-hand side, with the HTML repeated for each page in the site. The include directive is a natural way of doing this, saving the developers from the maintenance nightmare of actually copying the HTML into each separate file. Here's some representative code:
HREF="Site-Styles.css"
TYPE="text/css">
<%@ include file="/navbar.html" %>
Note that since the include directive inserts the files at the time the page is translated, if the navigation bar changes, you need to re-translate all the JSP pages that refer to it. This is a good compromise in a situation like this, since the navigation bar probably changes infrequently, and you want the inclusion process to be as efficient as possible. If, however, the included files changed more often, you could use the jsp:include action instead. This includes the file at the time the JSP page is requested, and is discussed in the tutorial
The JSP page Directive
The page directive lets you define one or more of the following case-sensitive attributes:
* import="package.class" or import="package.class1,...,package.classN". This lets you specify what packages should be imported. For example:
<%@ page import="java.util.*" %>
The import attribute is the only one that is allowed to appear multiple times.
* contentType="MIME-Type" or
contentType="MIME-Type; charset=Character-Set"
This specifies the MIME type of the output. The default is text/html. For example, the directive
<%@ page contentType="text/plain" %>
has the same effect as the scriptlet
<% response.setContentType("text/plain"); %>
* isThreadSafe="true|false". A value of true (the default) indicates normal servlet processing, where multiple requests can be processed simultaneously with a single servlet instance, under the assumption that the author synchronized access to instance variables. A value of false indicates that the servlet should implement SingleThreadModel, with requests either delivered serially or with simultaneous requests being given separate servlet instances.
* session="true|false". A value of true (the default) indicates that the predefined variable session (of type HttpSession) should be bound to the existing session if one exists, otherwise a new session should be created and bound to it. A value of false indicates that no sessions will be used, and attempts to access the variable session will result in errors at the time the JSP page is translated into a servlet.
* buffer="sizekb|none". This specifies the buffer size for the JspWriter out. The default is server-specific, but must be at least 8kb.
* autoflush="true|false". A value of true, the default, indicates that the buffer should be flushed when it is full. A value of false, rarely used, indicates that an exception should be thrown when the buffer overflows. A value of false is illegal when also using buffer="none".
* extends="package.class". This indicates the superclass of servlet that will be generated. Use this with extreme caution, since the server may be using a custom superclass already.
* info="message". This defines a string that can be retrieved via the getServletInfo method.
* errorPage="url". This specifies a JSP page that should process any Throwables thrown but not caught in the current page.
* isErrorPage="true|false". This indicates whether or not the current page can act as the error page for another JSP page. The default is false.
* language="java". At some point, this is intended to specify the underlying language being used. For now, don't bother with this since java is both the default and the only legal choice.
The XML syntax for defining directives is
For example, the XML equivalent of
<%@ page import="java.util.*" %>
is
* import="package.class" or import="package.class1,...,package.classN". This lets you specify what packages should be imported. For example:
<%@ page import="java.util.*" %>
The import attribute is the only one that is allowed to appear multiple times.
* contentType="MIME-Type" or
contentType="MIME-Type; charset=Character-Set"
This specifies the MIME type of the output. The default is text/html. For example, the directive
<%@ page contentType="text/plain" %>
has the same effect as the scriptlet
<% response.setContentType("text/plain"); %>
* isThreadSafe="true|false". A value of true (the default) indicates normal servlet processing, where multiple requests can be processed simultaneously with a single servlet instance, under the assumption that the author synchronized access to instance variables. A value of false indicates that the servlet should implement SingleThreadModel, with requests either delivered serially or with simultaneous requests being given separate servlet instances.
* session="true|false". A value of true (the default) indicates that the predefined variable session (of type HttpSession) should be bound to the existing session if one exists, otherwise a new session should be created and bound to it. A value of false indicates that no sessions will be used, and attempts to access the variable session will result in errors at the time the JSP page is translated into a servlet.
* buffer="sizekb|none". This specifies the buffer size for the JspWriter out. The default is server-specific, but must be at least 8kb.
* autoflush="true|false". A value of true, the default, indicates that the buffer should be flushed when it is full. A value of false, rarely used, indicates that an exception should be thrown when the buffer overflows. A value of false is illegal when also using buffer="none".
* extends="package.class". This indicates the superclass of servlet that will be generated. Use this with extreme caution, since the server may be using a custom superclass already.
* info="message". This defines a string that can be retrieved via the getServletInfo method.
* errorPage="url". This specifies a JSP page that should process any Throwables thrown but not caught in the current page.
* isErrorPage="true|false". This indicates whether or not the current page can act as the error page for another JSP page. The default is false.
* language="java". At some point, this is intended to specify the underlying language being used. For now, don't bother with this since java is both the default and the only legal choice.
The XML syntax for defining directives is
For example, the XML equivalent of
<%@ page import="java.util.*" %>
is
JSP Directives
A JSP directive affects the overall structure of the servlet class. It usually has the following form:
<%@ directive attribute="value" %>
However, you can also combine multiple attribute settings for a single directive, as follows:
<%@ directive attribute1="value1"
attribute2="value2"
...
attributeN="valueN" %>
There are two main types of directive: page, which lets you do things like import classes, customize the servlet superclass, and the like; and include, which lets you insert a file into the servlet class at the time the JSP file is translated into a servlet. The specification also mentions the taglib directive, which is not supported in JSP version 1.0, but is intended to let JSP authors define their own tags. It is expected that this will be the main new contribution of JSP 1.1.
<%@ directive attribute="value" %>
However, you can also combine multiple attribute settings for a single directive, as follows:
<%@ directive attribute1="value1"
attribute2="value2"
...
attributeN="valueN" %>
There are two main types of directive: page, which lets you do things like import classes, customize the servlet superclass, and the like; and include, which lets you insert a file into the servlet class at the time the JSP file is translated into a servlet. The specification also mentions the taglib directive, which is not supported in JSP version 1.0, but is intended to let JSP authors define their own tags. It is expected that this will be the main new contribution of JSP 1.1.
JSP Declarations
A JSP declaration lets you define methods or fields that get inserted into the main body of the servlet class (outside of the service method processing the request). It has the following form:
<%! Java Code %>
Since declarations do not generate any output, they are normally used in conjunction with JSP expressions or scriptlets. For example, here is a JSP fragment that prints out the number of times the current page has been requested since the server booted (or the servlet class was changed and reloaded):
<%! private int accessCount = 0; %>
Accesses to page since server reboot:
<%= ++accessCount %>
As with scriptlets, if you want to use the characters "%>", enter "%\>" instead. Finally, note that the XML equivalent of <%! Code %> is
Code
<%! Java Code %>
Since declarations do not generate any output, they are normally used in conjunction with JSP expressions or scriptlets. For example, here is a JSP fragment that prints out the number of times the current page has been requested since the server booted (or the servlet class was changed and reloaded):
<%! private int accessCount = 0; %>
Accesses to page since server reboot:
<%= ++accessCount %>
As with scriptlets, if you want to use the characters "%>", enter "%\>" instead. Finally, note that the XML equivalent of <%! Code %> is
Code
JSP Scriptlets
If you want to do something more complex than insert a simple expression, JSP scriptlets let you insert arbitrary code into the servlet method that will be built to generate the page. Scriptlets have the following form:
<% Java Code %>
Scriptlets have access to the same automatically defined variables as expressions. So, for example, if you want output to appear in the resultant page, you would use the out variable.
<%
String queryData = request.getQueryString();
out.println("Attached GET data: " + queryData);
%>
Note that code inside a scriptlet gets inserted exactly as written, and any static HTML (template text) before or after a scriptlet gets converted to print statements. This means that scriptlets need not contain complete Java statements, and blocks left open can affect the static HTML outside of the scriptlets. For example, the following JSP fragment, containing mixed template text and scriptlets
<% if (Math.random() < 0.5) { %>
Have a nice day!
<% } else { %>
Have a lousy day!
<% } %>
will get converted to something like:
if (Math.random() < 0.5) {
out.println("Have a nice day!");
} else {
out.println("Have a lousy day!");
}
If you want to use the characters "%>" inside a scriptlet, enter "%\>" instead. Finally, note that the XML equivalent of <% Code %> is
Code
<% Java Code %>
Scriptlets have access to the same automatically defined variables as expressions. So, for example, if you want output to appear in the resultant page, you would use the out variable.
<%
String queryData = request.getQueryString();
out.println("Attached GET data: " + queryData);
%>
Note that code inside a scriptlet gets inserted exactly as written, and any static HTML (template text) before or after a scriptlet gets converted to print statements. This means that scriptlets need not contain complete Java statements, and blocks left open can affect the static HTML outside of the scriptlets. For example, the following JSP fragment, containing mixed template text and scriptlets
<% if (Math.random() < 0.5) { %>
Have a nice day!
<% } else { %>
Have a lousy day!
<% } %>
will get converted to something like:
if (Math.random() < 0.5) {
out.println("Have a nice day!");
} else {
out.println("Have a lousy day!");
}
If you want to use the characters "%>" inside a scriptlet, enter "%\>" instead. Finally, note that the XML equivalent of <% Code %> is
Code
JSP Expressions
A JSP expression is used to insert Java values directly into the output. It has the following form:
<%= Java Expression %>
The Java expression is evaluated, converted to a string, and inserted in the page. This evaluation is performed at run-time (when the page is requested), and thus has full access to information about the request. For example, the following shows the date/time that the page was requested:
Current time: <%= new java.util.Date() %>
To simplify these expressions, there are a number of predefined variables that you can use. These implicit objects are discussed in more detail later, but for the purpose of expressions, the most important ones are:
* request, the HttpServletRequest;
* response, the HttpServletResponse;
* session, the HttpSession associated with the request (if any); and
* out, the PrintWriter (a buffered version of type JspWriter) used to send output to the client.
Here's an example:
Your hostname: <%= request.getRemoteHost() %>
Finally, note that XML authors can use an alternative syntax for JSP expressions:
Java Expression
Remember that XML elements, unlike HTML ones, are case sensitive. So be sure to use lowercase.
<%= Java Expression %>
The Java expression is evaluated, converted to a string, and inserted in the page. This evaluation is performed at run-time (when the page is requested), and thus has full access to information about the request. For example, the following shows the date/time that the page was requested:
Current time: <%= new java.util.Date() %>
To simplify these expressions, there are a number of predefined variables that you can use. These implicit objects are discussed in more detail later, but for the purpose of expressions, the most important ones are:
* request, the HttpServletRequest;
* response, the HttpServletResponse;
* session, the HttpSession associated with the request (if any); and
* out, the PrintWriter (a buffered version of type JspWriter) used to send output to the client.
Here's an example:
Your hostname: <%= request.getRemoteHost() %>
Finally, note that XML authors can use an alternative syntax for JSP expressions:
Java Expression
Remember that XML elements, unlike HTML ones, are case sensitive. So be sure to use lowercase.
JSP Scripting Elements
JSP scripting elements let you insert Java code into the servlet that will be generated from the current JSP page. There are three forms:
1. Expressions of the form <%= expression %> that are evaluated and inserted into the output,
2. Scriptlets of the form <% code %> that are inserted into the servlet's service method, and
3. Declarations of the form <%! code %> that are inserted into the body of the servlet class, outside of any existing methods.
Each of these is described in more detail below.
1. Expressions of the form <%= expression %> that are evaluated and inserted into the output,
2. Scriptlets of the form <% code %> that are inserted into the servlet's service method, and
3. Declarations of the form <%! code %> that are inserted into the body of the servlet class, outside of any existing methods.
Each of these is described in more detail below.
Template Text: Static HTML
In many cases, a large percent of your JSP page just consists of static HTML, known as template text. In all respects except one, this HTML looks just like normal HTML, follows all the same syntax rules, and is simply "passed through" to the client by the servlet created to handle the page. Not only does the HTML look normal, it can be created by whatever tools you already are using for building Web pages. For example, I used Allaire's HomeSite for most of the JSP pages in this tutorial.
The one minor exception to the "template text is passed straight through" rule is that, if you want to have "<%" in the output, you need to put "<\%" in the template text.
The one minor exception to the "template text is passed straight through" rule is that, if you want to have "<%" in the output, you need to put "<\%" in the template text.
OVERVIEW
JavaServer Pages (JSP) lets you separate the dynamic part of your pages from the static HTML. You simply write the regular HTML in the normal manner, using whatever Web-page-building tools you normally use. You then enclose the code for the dynamic parts in special tags, most of which start with "<%" and end with "%>". For example, here is a section of a JSP page that results in something like "Thanks for ordering Core Web Programming" for a URL of http://host/OrderConfirmation.jsp?title=Core+Web+Programming:
Thanks for ordering
<%= request.getParameter("title") %>
You normally give your file a .jsp extension, and typically install it in any place you could place a normal Web page. Although what you write often looks more like a regular HTML file than a servlet, behind the scenes, the JSP page just gets converted to a normal servlet, with the static HTML simply being printed to the output stream associated with the servlet's service method. This is normally done the first time the page is requested, and developers can simply request the page themselves when first installing it if they want to be sure that the first real user doesn't get a momentary delay when the JSP page is translated to a servlet and the servlet is compiled and loaded. Note also that many Web servers let you define aliases that so that a URL that appears to reference an HTML file really points to a servlet or JSP page.
Aside from the regular HTML, there are three main types of JSP constructs that you embed in a page: scripting elements, directives, and actions. Scripting elements let you specify Java code that will become part of the resultant servlet, directives let you control the overall structure of the servlet, and actions let you specify existing components that should be used, and otherwise control the behavior of the JSP engine. To simplify the scripting elements, you have access to a number of predefined variables such as request in the snippet above.
Note that this tutorial covers version 1.0 of the JSP specification. JSP has changed dramatically since version 0.92, and although these changes were almost entirely for the better, you should note that version 1.0 JSP pages are almost totally incompatible with the earlier JSP engines. Note that this JSP tutorial is part of a larger tutorial on servlets and JSP at http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/.
Thanks for ordering
<%= request.getParameter("title") %>
You normally give your file a .jsp extension, and typically install it in any place you could place a normal Web page. Although what you write often looks more like a regular HTML file than a servlet, behind the scenes, the JSP page just gets converted to a normal servlet, with the static HTML simply being printed to the output stream associated with the servlet's service method. This is normally done the first time the page is requested, and developers can simply request the page themselves when first installing it if they want to be sure that the first real user doesn't get a momentary delay when the JSP page is translated to a servlet and the servlet is compiled and loaded. Note also that many Web servers let you define aliases that so that a URL that appears to reference an HTML file really points to a servlet or JSP page.
Aside from the regular HTML, there are three main types of JSP constructs that you embed in a page: scripting elements, directives, and actions. Scripting elements let you specify Java code that will become part of the resultant servlet, directives let you control the overall structure of the servlet, and actions let you specify existing components that should be used, and otherwise control the behavior of the JSP engine. To simplify the scripting elements, you have access to a number of predefined variables such as request in the snippet above.
Note that this tutorial covers version 1.0 of the JSP specification. JSP has changed dramatically since version 0.92, and although these changes were almost entirely for the better, you should note that version 1.0 JSP pages are almost totally incompatible with the earlier JSP engines. Note that this JSP tutorial is part of a larger tutorial on servlets and JSP at http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/.
Monday, April 13, 2009
Generating the Server Response: HTTP Status Codes
Generating the Server Response: HTTP Status Codes :
When a Web server responds to the request from the browser or other Web client, the response typically consists of a status line, some response headers, a blank line, and the document
Specifying Status Codes
As described above, the HTTP response status line consists of the HTTP version, a status code, and an associated message. Since the message is directly associated with the status code and the HTTP version is determined by the server, all the servlet needs to do is to set status code. The way to do that is by the setStatus method of the HttpServletResponse.
The setStatus method takes the int (the status code) as an argument, but instead of using explicit numbers, it is clearer and more reliable to use the constants defined in HttpServletResponse. The name of each constant is derived from standard HTTP 1.1 message for each constant, all uppercase with a prefix of SC(for Status Code) and spaces changed to underscores. Thus, since the message for 404 is Not Found, the equivalent constant in the HttpServletResponse is SC_NOT_FOUND There are two exceptions however. For some odd reason the constant for code 302 is derived from the HTTP 1.0 message, not the HTTP 1.1 message, and the constant for the code 307 is missing altogether.
Setting the status code does not always mean that you don't need to the return a document. For example, although most servers will generate the small "File Not Found" message for 404 responses, a servlets might want to customize this response. However, if you do this, you need to be sure to call response.setStatus before sending any content via PrintWriter.
Although the general method of setting status codes is simply to the call response.setStatus(int), there are two common cases where a shortcut method in the HttpServletResponse is provided. The sendError method generates the 404 response along with a short message formatted inside an HTML document. And the sendRedirect method generates the 302 response along with a Location header indicating the URL of the new document.
HTTP 1.1 Status Codes and Their Meaning
Following is the list of all the available HTTP 1.1 status codes, along with their associated message and interpretation. You should be cautious in using status codes that are available only in HTTP 1.1, since many browsers still only support HTTP 1.0. If you do use the status codes specific to HTTP 1.1, in most cases you want to either explicitly check the HTTP version of request (via the getProtocol method of the HttpServletRequest) or reserve it for situations when no HTTP 1.0 status code would be particularly meaningful to the client anyhow.
When a Web server responds to the request from the browser or other Web client, the response typically consists of a status line, some response headers, a blank line, and the document
Specifying Status Codes
As described above, the HTTP response status line consists of the HTTP version, a status code, and an associated message. Since the message is directly associated with the status code and the HTTP version is determined by the server, all the servlet needs to do is to set status code. The way to do that is by the setStatus method of the HttpServletResponse.
The setStatus method takes the int (the status code) as an argument, but instead of using explicit numbers, it is clearer and more reliable to use the constants defined in HttpServletResponse. The name of each constant is derived from standard HTTP 1.1 message for each constant, all uppercase with a prefix of SC(for Status Code) and spaces changed to underscores. Thus, since the message for 404 is Not Found, the equivalent constant in the HttpServletResponse is SC_NOT_FOUND There are two exceptions however. For some odd reason the constant for code 302 is derived from the HTTP 1.0 message, not the HTTP 1.1 message, and the constant for the code 307 is missing altogether.
Setting the status code does not always mean that you don't need to the return a document. For example, although most servers will generate the small "File Not Found" message for 404 responses, a servlets might want to customize this response. However, if you do this, you need to be sure to call response.setStatus before sending any content via PrintWriter.
Although the general method of setting status codes is simply to the call response.setStatus(int), there are two common cases where a shortcut method in the HttpServletResponse is provided. The sendError method generates the 404 response along with a short message formatted inside an HTML document. And the sendRedirect method generates the 302 response along with a Location header indicating the URL of the new document.
HTTP 1.1 Status Codes and Their Meaning
Following is the list of all the available HTTP 1.1 status codes, along with their associated message and interpretation. You should be cautious in using status codes that are available only in HTTP 1.1, since many browsers still only support HTTP 1.0. If you do use the status codes specific to HTTP 1.1, in most cases you want to either explicitly check the HTTP version of request (via the getProtocol method of the HttpServletRequest) or reserve it for situations when no HTTP 1.0 status code would be particularly meaningful to the client anyhow.
100 Continue Continue with partial request. (New in HTTP 1.1) |
101 Switching Protocols
Server will comply with Upgrade header and change to different protocol. (New in HTTP 1.1) |
200 OK
Everything's fine; document follows for GET and POST requests. This is the default for servlets; if you don't use setStatus, you'll get this. |
201 Created
Server created a document; the Location header indicates its URL. |
202 Accepted Request is being acted upon, but processing is not completed. |
203 Non-Authoritative Information Document is being returned normally, but some of the response headers might be incorrect since a document copy is being used. (New in HTTP 1.1) |
204 No Content
No new document; browser should continue to display previous document. This is a useful if the user periodically reloads a page and you can determine that the previous page is already up to date. However, this does not work for pages that are automatically reloaded via the Refresh response header or the equivalent header, since returning this status code stops future reloading. JavaScript-based automatic reloading could still work in such a case, though |
205 Reset Content
No new document, but browser should reset document view. Used to force browser to clear CGI form fields. (New in HTTP 1.1) |
206 Partial Content
Client sent a partial request with a Range header, and server has fulfilled it. (New in HTTP 1.1) |
300 Multiple Choices
Document requested can be found several places; they'll be listed in the returned document. If server has a preferred choice, it should be listed in the Location response header. |
301 Moved Permanently
Requested document is elsewhere, and the URL for it is given in the Location response header. Browsers should automatically follow the link to the new URL. |
302 Found
Similar to 301, except that the new URL should be interpreted as a temporary replacement, not a permanent one. Note: the message was "Moved Temporarily" in HTTP 1.0, and the constant in HttpServletResponse is SC_MOVED_TEMPORARILY, not SC_FOUND.Very useful header, since browsers automatically follow the link to the new URL. This status code is so useful that there is a special method for it, sendRedirect. Using response.sendRedirect(url) has a couple of advantages over doing response.setStatus(response.SC_MOVED_TEMPORARILY) and response.setHeader("Location", url). First, it is easier. Second, with sendRedirect, the servlet automatically builds a page containing the link (to show to older browsers that don't automatically follow redirects). Finally, sendRedirect can handle relative URLs, automatically translating them to absolute ones. Note that this status code is sometimes used interchangeably with 301. some servers will send 301 and others will send 302. Technically, browsers are only supposed to automatically follow the redirection if the original request was GET. See the 307 header for details. |
Accessing the Standard CGI Variables
Accessing the Standard CGI Variables:
To build the successful web application, you often need to know a lot about the environment in which it is running.
You may need to find out about server that is executing your servlets or the specifics of the client that is sending requests. And no matter what kind of environment the application is running in, you most certainly need the information about the requests that the application is handling.
Advantages of Using Servlets Over CGI
* Stronger type checking. In other words, more help from compiler in catching errors. A CGI program uses one function to retrieve its environment variable. Many errors cannot be found until they cause runtime problem. Let's look at how both a CGI program and servlets find the port on which its server is running.
A CGI script written in Perl call: $port = $ENV{'SERVER_PORT'}; port is an untyped variable. A CGI program written in C call: The chance for accidental errors is also high. The environment variable name could be misspelled or the data type might not match what the environment variable returns.
A servlet, on the other hand, call:
int port = req.getServerPort()
This eliminates a lot of the accidental errors because the compiler can guarantee there are no misspellings and each return type is as it should be.
*
Delayed calculation. When the server launches a CGI program, the value for each and every environment variable must be precalculated and passed, whether the CGI program uses it or not. A server launching the servlets has the option to improve performance by delaying these calculations and performing them on demand as needed.
*
More interaction with server. Once the CGI program begins execution, it is untethered from its server. The only communication path available to program is its standard output. A servlet, however, can also work with the server. As discussed in the last chapter, a servlet operates either within the server (when possible) or as connected process outside the server (when necessary). Using this connectivity, a servlet can make ad hoc requests for calculated the information that only the server can provide. For example, a servlet can have its server do arbitrary path translation, taking into consideration the server's aliases and virtual paths.
CGI Environment Variables and the Corresponding Servlet Methods
To build the successful web application, you often need to know a lot about the environment in which it is running.
You may need to find out about server that is executing your servlets or the specifics of the client that is sending requests. And no matter what kind of environment the application is running in, you most certainly need the information about the requests that the application is handling.
Advantages of Using Servlets Over CGI
* Stronger type checking. In other words, more help from compiler in catching errors. A CGI program uses one function to retrieve its environment variable. Many errors cannot be found until they cause runtime problem. Let's look at how both a CGI program and servlets find the port on which its server is running.
A CGI script written in Perl call: $port = $ENV{'SERVER_PORT'}; port is an untyped variable. A CGI program written in C call: The chance for accidental errors is also high. The environment variable name could be misspelled or the data type might not match what the environment variable returns.
A servlet, on the other hand, call:
int port = req.getServerPort()
This eliminates a lot of the accidental errors because the compiler can guarantee there are no misspellings and each return type is as it should be.
*
Delayed calculation. When the server launches a CGI program, the value for each and every environment variable must be precalculated and passed, whether the CGI program uses it or not. A server launching the servlets has the option to improve performance by delaying these calculations and performing them on demand as needed.
*
More interaction with server. Once the CGI program begins execution, it is untethered from its server. The only communication path available to program is its standard output. A servlet, however, can also work with the server. As discussed in the last chapter, a servlet operates either within the server (when possible) or as connected process outside the server (when necessary). Using this connectivity, a servlet can make ad hoc requests for calculated the information that only the server can provide. For example, a servlet can have its server do arbitrary path translation, taking into consideration the server's aliases and virtual paths.
CGI Environment Variables and the Corresponding Servlet Methods
CGI Environment Variable | HTTP Servlet Method |
SERVER_NAME | req.getServerName() |
SERVER_SOFTWARE | getServletContext().getServerInfo() |
SERVER_PROTOCOL | req.getProtocol() |
SERVER_PORT | req.getServerPort() |
REQUEST_METHOD | req.getMethod() |
PATH_INFO | req.getPathInfo() |
PATH_TRANSLATED | req.getPathTranslated() |
SCRIPT_NAME | req.getServletPath() |
DOCUMENT_ROOT | req.getRealPath("/") |
Sunday, April 12, 2009
Handling the Client Request: HTTP Request Headers
*When the HTTP client (e.g. a browser) sends a request, it is required to supply a request line (usually GET or POST).
* If it wants to, it can also send the number of headers, all of which are optional except for Content-Length, which is required only for POST requests
HTTP Request Header Methods Available in Servlets
General:
-getHeader (header name is not case sensitive)
-getHeaderNames
-getHeaders
Specialized
-getCookies
-getAuthType and getRemoteUser
-getContentLength
-getContentType
-getMethod
-getRequestURI
-getQueryString
-getDateHeader
-getIntHeader
-Related info
-getProtocol
An Overview of Request Headers
When the HTTP client (e.g. a browser) sends a request, it is required to supply a request line (usually GET or POST). If it wants to, it can also send the number of headers, all of which are optional except for Content-Length, which is required only for POST requests. Here are the most common headers:
* Accept The MIME types that the browser prefers.
* Accept-Charset The character set that the browser expects.
*
Accept-Encoding The types of data encodings (such as gzip) that the browser knows how to decode. Servlet can explicitly check for gzip support and return gzipped HTML pages to browsers that support them, setting the Content-Encoding response header to indicate that they are gzipped. In many cases, this can reduce page download times by a factor of five or ten.
*
Accept-Language The language the browser is expecting, in case the server has versions in more than the one language.
*
Authorization Authorization info, usually in response to the WWW-Authenticate header from the server.
*
Connection Use persistent connection? If a servlet get a Keep-Alive value here, or gets a request line indicating HTTP 1.1 (where persistent connections are the default), it may be able to take advantage of persistent connections, saving significant time for Web pages that include several small pieces (images or applet classes). To do this, it needs to send the Content-Length header in the response, which is most easily accomplished by writing into a ByteArrayOutputStream, then looking up the size just before writing it out.
*
Content-Length (for POST messages, how much the data is attached)
*
Cookie (one of most important headers; see separate section in this tutorial on handling cookies)
*
From (email address of the requester; only used by Web spiders and other custom clients, not by browsers)
* Host (host and the port as listed in the original URL)
*
If-Modified-Since (only return documents newer than this, otherwise send the 304 "Not Modified" response)
*
Pragma (the no-cache value indicates that the server should return the fresh document, even if it is a proxy with a local copy)
*
Referer (the URL of the page containing the link the user followed to get to the current page)
*
User-Agent (type of the browser, useful if servlet is returning browser-specific content)
*
UA-Pixels, UA-Color, UA-OS, UA-CPU (nonstandard header sent by some Internet Explorer versions, indicating screen size, color depth, operating system, and cpu type used by the browser's system)
Reading Request Headers from Servlets
Reading headers is the very straightforward; just call the getHeader method of the HttpServletRequest, which returns a String if the header was supplied on this request, null otherwise. However, there are the couple of headers that are so commonly used that they have special access methods. The getCookies method returns contents of the Cookie header, parsed and stored in an array of Cookie objects. See the separate section of this tutorial on cookies. The getAuthType and getRemoteUser methods break Authorization header into its component pieces. The getDateHeader and getIntHeader methods read the specified header and then convert them to Date and int values, respectively.
Rather than looking up one of the particular header, you can use the getHeaderNames to get an Enumeration of all header names received on this particular request.
Finally, in addition to looking up request headers, you can get information on the main request line itself. The getMethod method returns the main request method (normally GET or POST, but things like HEAD, PUT, and DELETE are possible). The getRequestURI method returns URI (the part of the URL that came after the host and port, but before the form data). The getRequestProtocol returns third part of the request line, which is generally "HTTP/1.0" or "HTTP/1.1".
* If it wants to, it can also send the number of headers, all of which are optional except for Content-Length, which is required only for POST requests
HTTP Request Header Methods Available in Servlets
General:
-getHeader (header name is not case sensitive)
-getHeaderNames
-getHeaders
Specialized
-getCookies
-getAuthType and getRemoteUser
-getContentLength
-getContentType
-getMethod
-getRequestURI
-getQueryString
-getDateHeader
-getIntHeader
-Related info
-getProtocol
An Overview of Request Headers
When the HTTP client (e.g. a browser) sends a request, it is required to supply a request line (usually GET or POST). If it wants to, it can also send the number of headers, all of which are optional except for Content-Length, which is required only for POST requests. Here are the most common headers:
* Accept The MIME types that the browser prefers.
* Accept-Charset The character set that the browser expects.
*
Accept-Encoding The types of data encodings (such as gzip) that the browser knows how to decode. Servlet can explicitly check for gzip support and return gzipped HTML pages to browsers that support them, setting the Content-Encoding response header to indicate that they are gzipped. In many cases, this can reduce page download times by a factor of five or ten.
*
Accept-Language The language the browser is expecting, in case the server has versions in more than the one language.
*
Authorization Authorization info, usually in response to the WWW-Authenticate header from the server.
*
Connection Use persistent connection? If a servlet get a Keep-Alive value here, or gets a request line indicating HTTP 1.1 (where persistent connections are the default), it may be able to take advantage of persistent connections, saving significant time for Web pages that include several small pieces (images or applet classes). To do this, it needs to send the Content-Length header in the response, which is most easily accomplished by writing into a ByteArrayOutputStream, then looking up the size just before writing it out.
*
Content-Length (for POST messages, how much the data is attached)
*
Cookie (one of most important headers; see separate section in this tutorial on handling cookies)
*
From (email address of the requester; only used by Web spiders and other custom clients, not by browsers)
* Host (host and the port as listed in the original URL)
*
If-Modified-Since (only return documents newer than this, otherwise send the 304 "Not Modified" response)
*
Pragma (the no-cache value indicates that the server should return the fresh document, even if it is a proxy with a local copy)
*
Referer (the URL of the page containing the link the user followed to get to the current page)
*
User-Agent (type of the browser, useful if servlet is returning browser-specific content)
*
UA-Pixels, UA-Color, UA-OS, UA-CPU (nonstandard header sent by some Internet Explorer versions, indicating screen size, color depth, operating system, and cpu type used by the browser's system)
Reading Request Headers from Servlets
Reading headers is the very straightforward; just call the getHeader method of the HttpServletRequest, which returns a String if the header was supplied on this request, null otherwise. However, there are the couple of headers that are so commonly used that they have special access methods. The getCookies method returns contents of the Cookie header, parsed and stored in an array of Cookie objects. See the separate section of this tutorial on cookies. The getAuthType and getRemoteUser methods break Authorization header into its component pieces. The getDateHeader and getIntHeader methods read the specified header and then convert them to Date and int values, respectively.
Rather than looking up one of the particular header, you can use the getHeaderNames to get an Enumeration of all header names received on this particular request.
Finally, in addition to looking up request headers, you can get information on the main request line itself. The getMethod method returns the main request method (normally GET or POST, but things like HEAD, PUT, and DELETE are possible). The getRequestURI method returns URI (the part of the URL that came after the host and port, but before the form data). The getRequestProtocol returns third part of the request line, which is generally "HTTP/1.0" or "HTTP/1.1".
Sunday, April 5, 2009
Handling the Client Request:Form Data
# When the user submits form, his information is sent to the corresponding servlet file because we've set the ACTION attribute to point to the servlet.
* The form can use the GET method or POST method.
* In GET method, if the user enter the name "Inigo Montoya," the request URL is http://server:8080/servlet/Hello?name=Inigo+Montoya in the form of querystring which is visible to the user.
* The space in the name is specially encoded as a plus sign by the browser because URLs cannot contain space.
* A servlet's HttpServletRequest object gives it access to form data in its query string.
Difference between GET and POST Method
When the user enters information in a form and clicks Submit , there are two ways the information can be sent from browser to server: in the URL, or within the body of the HTTP request.
The GET method, which was used in example earlier, appends name/value pairs to the URL. Unfortunately, the length of URL is limited, so this method only works if there are only a few parameters. The URL could be truncated if the form uses a large number of parameter or if the parameters contain large amounts of data. Also, parameters passed on URL are visible in the address field of the browsernot the best place for a password to be displayed.
The alternative to the GET method is POST method. This method packages the name/value pairs inside the body of HTTP request, which makes for a cleaner URL and imposes no size limitation on the forms output. It is more secure.
Overriding service, doGet, and doPost
When a request is made, Servlet Engine hands on the incoming data to the Servlet engine, which processes the request, including form data, cookies, session information, and URL name-value pairs, into an object of type HttpServletRequest called the request object. Client metadata is encapsulated as the object of type HttpServletResponse and is called the response object. The Servlet engine passes both objects as parameters to Servlets service() method.
The default service() method in an HTTP servlets routes the request to another method based on the HTTP transfer method (POST, GET, etc.) For example, HTTP POST requests are routed to doPost() method, HTTP GET requests are routed to the doGet() method, and so on. This enables the Servlet to perform different processing on request data depending on the transfer method. Since routing takes place in service(), you generally do not override service() in an HTTP Servlet. Instead, override doGet() and/or doPost(), etc., depending on type of request you expect.
The automatic routing in an HTTP Servlets is based simply on a call to request.getMethod(), which provides the HTTP transfer method. In Servlets Engine, request data is already preprocessed into a name-value list by the time the Servlet sees the data, so you could simply override the service() method in an HTTP Servlet without losing any functionality. However, this does make the Servlet less portable, since it is now dependent on preprocessed request data.
You must override service() method (for generic Servlets) or the doGet() and/or doPost() methods (for HTTP servlets) to perform the tasks needed to answer the request. Very often, this means accessing EJBs to perform the business transactions, collating the needed information (in the request object or in a JDBC ResultSet object), and then passing the newly generated content to the JSP for formatting and delivery back to the client.
Most operations that involve the forms use either a GET or a POST operation, so for most servlets you override either doGet() or doPost(). Note that you can implement both the methods to provide for both types of input, or simply pass the request object to a central processing method
Syntax of Using doGet
public void doGet (HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException
{
...servlet code goes here...
}
Syntax of Using doPost
public void doPost (HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException
{
...servlet code goes here...
}
All of the actual request-by-request traffic in an HTTP Servlets is handled in the appropriate doOperation() method, including session management, user authentication, dispatching EJBs and JSPs, and accessing iAS features.
If you have a Servlets that you intend to also call using a RequestDispatcher method include() or forward() , be aware that the request information is no longer sent as HTTP POST, GET, etc. RequestDispatcher methods always call the service(). In other words, if a servlet overrides doPost(), it may not process anything if another servlet calls it, if the calling servlet happens to have received its data via HTTP GET. For this reason, be sure to implement routines for all possible types of the input, as explained above.
Note Arbitrary binary data, like uploaded files or images, can be problematic, since web connector translates incoming data into name-value pairs by default. You can program web connector to properly handle this kind of data and package it correctly in the request object. Accessing Parameters and Storing the Data
Incoming data is encapsulated in the request object. For HTTP servlet, the request object is of type HttpServletRequest. For generic servlet, the request object is of type ServletRequest. The request object contains all the parameters in a request, and you can also set your own values in the request. The latter is called attribute.
You can access all the parameters in an incoming request by using getParameter() method.
The following example describe the use of getParameter()
String username = request.getParameter("accountNumber");
You can also set and retrieve values in the request object using setAttribute() and getAttribute(), respectively.
The following example describe the use of setAttribute()
request.setAttribute("accountNumber", "3284766");
A complete example showing the use of doGet Method in Servlets
Step1:Make the HTML form
Step2:Make the corresponding Servlets Page
Step1:Make the HTML form
Here we are make a HTML form called form.html which is given below:
Step2:Make the corresponding Servlets Page
Here we are make a Servlets filr called name.java as we have given in the action attribute path in the form.html as name which is given below:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class name extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String name = req.getParameter("name");
out.println("");
}
public String getServletInfo()
{
return "A servlet that knows the name of the person to whom it's" +
"saying hello";
}
}
* The form can use the GET method or POST method.
* In GET method, if the user enter the name "Inigo Montoya," the request URL is http://server:8080/servlet/Hello?name=Inigo+Montoya in the form of querystring which is visible to the user.
* The space in the name is specially encoded as a plus sign by the browser because URLs cannot contain space.
* A servlet's HttpServletRequest object gives it access to form data in its query string.
Difference between GET and POST Method
When the user enters information in a form and clicks Submit , there are two ways the information can be sent from browser to server: in the URL, or within the body of the HTTP request.
The GET method, which was used in example earlier, appends name/value pairs to the URL. Unfortunately, the length of URL is limited, so this method only works if there are only a few parameters. The URL could be truncated if the form uses a large number of parameter or if the parameters contain large amounts of data. Also, parameters passed on URL are visible in the address field of the browsernot the best place for a password to be displayed.
The alternative to the GET method is POST method. This method packages the name/value pairs inside the body of HTTP request, which makes for a cleaner URL and imposes no size limitation on the forms output. It is more secure.
Overriding service, doGet, and doPost
When a request is made, Servlet Engine hands on the incoming data to the Servlet engine, which processes the request, including form data, cookies, session information, and URL name-value pairs, into an object of type HttpServletRequest called the request object. Client metadata is encapsulated as the object of type HttpServletResponse and is called the response object. The Servlet engine passes both objects as parameters to Servlets service() method.
The default service() method in an HTTP servlets routes the request to another method based on the HTTP transfer method (POST, GET, etc.) For example, HTTP POST requests are routed to doPost() method, HTTP GET requests are routed to the doGet() method, and so on. This enables the Servlet to perform different processing on request data depending on the transfer method. Since routing takes place in service(), you generally do not override service() in an HTTP Servlet. Instead, override doGet() and/or doPost(), etc., depending on type of request you expect.
The automatic routing in an HTTP Servlets is based simply on a call to request.getMethod(), which provides the HTTP transfer method. In Servlets Engine, request data is already preprocessed into a name-value list by the time the Servlet sees the data, so you could simply override the service() method in an HTTP Servlet without losing any functionality. However, this does make the Servlet less portable, since it is now dependent on preprocessed request data.
You must override service() method (for generic Servlets) or the doGet() and/or doPost() methods (for HTTP servlets) to perform the tasks needed to answer the request. Very often, this means accessing EJBs to perform the business transactions, collating the needed information (in the request object or in a JDBC ResultSet object), and then passing the newly generated content to the JSP for formatting and delivery back to the client.
Most operations that involve the forms use either a GET or a POST operation, so for most servlets you override either doGet() or doPost(). Note that you can implement both the methods to provide for both types of input, or simply pass the request object to a central processing method
Syntax of Using doGet
public void doGet (HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException
{
...servlet code goes here...
}
Syntax of Using doPost
public void doPost (HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException
{
...servlet code goes here...
}
All of the actual request-by-request traffic in an HTTP Servlets is handled in the appropriate doOperation() method, including session management, user authentication, dispatching EJBs and JSPs, and accessing iAS features.
If you have a Servlets that you intend to also call using a RequestDispatcher method include() or forward() , be aware that the request information is no longer sent as HTTP POST, GET, etc. RequestDispatcher methods always call the service(). In other words, if a servlet overrides doPost(), it may not process anything if another servlet calls it, if the calling servlet happens to have received its data via HTTP GET. For this reason, be sure to implement routines for all possible types of the input, as explained above.
Note Arbitrary binary data, like uploaded files or images, can be problematic, since web connector translates incoming data into name-value pairs by default. You can program web connector to properly handle this kind of data and package it correctly in the request object. Accessing Parameters and Storing the Data
Incoming data is encapsulated in the request object. For HTTP servlet, the request object is of type HttpServletRequest. For generic servlet, the request object is of type ServletRequest. The request object contains all the parameters in a request, and you can also set your own values in the request. The latter is called attribute.
You can access all the parameters in an incoming request by using getParameter() method.
The following example describe the use of getParameter()
String username = request.getParameter("accountNumber");
You can also set and retrieve values in the request object using setAttribute() and getAttribute(), respectively.
The following example describe the use of setAttribute()
request.setAttribute("accountNumber", "3284766");
A complete example showing the use of doGet Method in Servlets
Step1:Make the HTML form
Step2:Make the corresponding Servlets Page
Step1:Make the HTML form
Here we are make a HTML form called form.html which is given below:
Step2:Make the corresponding Servlets Page
Here we are make a Servlets filr called name.java as we have given in the action attribute path in the form.html as name which is given below:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class name extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String name = req.getParameter("name");
out.println("");
}
public String getServletInfo()
{
return "A servlet that knows the name of the person to whom it's" +
"saying hello";
}
}
Life Cycle of Servlets
Servlets Life Cycle
have the following Components:
* Handled by the servlets container.
* Create and initialize the servlets.
* Handle zero or more service call.
* Destroy and garbage collect the servlets.
* A single servlets instance to handle every request
The Basic Servlet Architecture or Life Cycle
Servlet container create only one instance of each servlet but the request of each user is handled with a separate thread. Each thread then calls the doGet or doPost methods. This idea is shown in the above Figure-5.
1.The init method of the servlets is called when the servlets is first created and each time the server receives a request for a servlets, the server spawns a new thread calls service method.
2.The service method check the HTTP request type (GET,SET, PUT, DELETE, etc.) and calls doGet, doPost, doPut,doDelete, etc. method as appropriate.
3.Finally, the server may decide to remove a previous loaded servlet. In this case, the server calls destroy method of the servlets.
HTTP
Before we can start writing the first Servlets, we need to know some basics of HTTP ("HyperText Transfer Protocol"), the protocol which is used by a WWW client (e.g. a browser) to send a request to a Web Server.
HTTP is the request-response oriented protocol. An HTTP request consist of a request method, a URI, header fields and a body (which can be empty). An HTTP response contain a result and again header fields and a body.
The service method of HttpServlet dispatch a request to different Java methods for different HTTP request methods. It recognize the standard HTTP/1.1 methods and should not be overridden in subclasses unless you need to implement additional methods. The recognized methods are GET, PUT,HEAD, POST, DELETE, OPTIONS and TRACE. Other methods are answered with a Bad Request HTTP error. An HTTP method XXX is dispatched to the Java method doXxx, e.g. GET -> doGet. All these method expect the parameters "(HttpServletRequest req, HttpServletResponse res)". The method doOptions and doTrace have suitable default implementations and are usually not overridden. The HEAD method (which is supposed to return the same header lines that a GET method would return, but doesn't include a body) is performed by calling the doGet and ignoring any output that is written by this method. That leaves us with the method doGet doPut doPost and doDelete whose default implementations in HttpServlet return a Bad Request HTTP error. A subclass of HttpServlet overrides one or more of these method to provide a meaningful implementation.
The request data is passed to all the methods through the first argument of type HttpServletRequest (which is a subclass of the more general ServletRequest class). The response can be created with the methods of the second argument of type HttpServletResponse (a subclass of ServletResponse).
When you request a URL in the Web Browser, the GET method is used for the request. A GET request does not have the body (i.e. the body is empty). The response should contain the body with the response data and header fields which describe the body (especially Content-Type and Content-Encoding). When you send an HTML form, either GET or POST action can be used. With the GET request the parameters are end in the URL, with a POST request they are transmited in the body. HTML editors and upload tools use PUT requests to the upload resources to a Web Server and DELETE requests to delete resources.
Servlet Types
# Classic Servlets-service() Method
# JSP's-Java Embeded in HTML Templates
# Http Servlets-doGet & doPost()
# Visual Servlets-Generated by Visual Age
Packages in Servlets
There are two types of package available in servlets which are as follows:
1.javax.servlet.*
2.javax.servlet.http.*
Interfaces in javax.servlet.*
# RequestDispatcher
# Servlet
# ServletRequest
# ServletResponse
# ServletConfig
# ServletContext
# SingleThreadModel
classes in javax.servlet.*
# GenericServlet
# ServletInputStream
# ServletOutputStream
# ServletException
# UnavailableException
Interfaces in javax.servlet.http.*
# HttpServletRequest
# HttpServletResponse
# HttpSessionBindingListener
# HttpSessionContext
# HttpSession
classes in javax.servlet.http.*
# Cookie
# HttpServlet
# HttpUtils
# HttpSessionBindingEvent
Servlet Scope Objects
The indicator specify the minimum number of time an element can occur:
There are four scope objects in servlets which enables the sharing information between web components. The scope objects and their corresponding Java classes are listed below:
# Web Context javax.servlet.ServletContext
# Request javax.servlet.HttpServletRequest
# Session javax.servlet.http.HttpSession
# Page javax.servlet.jsp.PageContext
You can get the attribute values from servlet scope objects using getAttribute method and set new values of attributes using setAttribute method. For example, you can get the client’s IP address by calling the getRemoteAddr method of HttpServletRequest class.
Following Examples prints the Hello World in the browser
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorld extends HttpServlet
{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
PrintWriter out = response.getWriter();
out.println("Hello World");
}
}
To be a servlet, a class should extend the HttpServlet and override doGet or doPost (or both), depending on whether the data is being sent by GET or by POST. These methods take two arguments: an HttpServletRequest and an HttpServletResponse. The HttpServletRequest has methods that let you find out about the incoming information such as FORM data, HTTP request headers, and the like.
The HttpServletResponse has method that lets you specify the HTTP response line (200, 404, etc.), response headers (Content-Type, Set-Cookie, etc.), and, most importantly, lets you obtain a PrintWriter used to send output back to the client. For simple servlet, most of the effort is spent in println statements that generate the desired page. Note that doGet and doPost throw two exception, so you are required to include them in the declaration. Also note that you have to import classes in the java.io (for PrintWriter, etc.), javax.servlet (for HttpServlet, etc.), and javax.servlet.http (for HttpServletRequest and HttpServletResponse). Finally, note that doGet and doPost are called by service method, and sometimes you may want to override service directly, e.g. for a servlet that handles both GET and POST request.
Compiling and Installing the Servlet
Note that the specific details for installing servlet vary from Web server to Web server. Please refer to your Web server documentation for the definitive directions. The on-line examples are running on Java Web Server (JWS) 2.0, where servlet are expected to be in a directory called servlets in the JWS installation hierarchy. However, I placed this servlets in a separate package (hall) to avoid conflicts with other servlets on this server; you'll want to do the same if you are using a Web server that is used by other people and doesn't have a good infrastructure for the "virtual servers" to prevent these conflicts automatically. Thus, HelloWorld.java actually goes in a subdirectory called hall in the servlets directory.
Note that setup on most other servers is similar, and the servlets and JSP examples in the tutorial have also been tested using BEA WebLogic and IBM WebSphere 3.0. WebSphere has an excellent mechanism for virtual servers, and it is not necessary to use packages solely to prevent name conflicts with other users.
If you've never used the packages before, there are two main ways to compile classes that are in packages.
One way is to set your CLASSPATH to point to directory above the one actually containing your servlets. You can them compile normally from within the directory. For example, if your base directory is C:\JavaWebServer\servlets and your package name (and thus subdirectory name) is the hall, and you were on Windows, you'd do:
DOS> set CLASSPATH=C:\JavaWebServer\servlets;%CLASSPATH%
DOS> cd C:\JavaWebServer\servlets\hall
DOS> javac YourServlet.java
The first part, setting CLASSPATH, you probably want to do permanently, rather than each time you start a new DOS window. On Windows 95/98 you'd typically put the "set CLASSPATH=..." statement in your autoexec.bat file somewhere after the line that set CLASSPATH to point to servlet.jar and jsp.jar. On Windows NT, you'd go to Start menu, select Settings, select Control Panel, select System, select Environment, then enter the variable and value. Note also that if your package were of the form name1.name2.name3 rather than simply name1 as here, you'd still have the CLASSPATH point to the top-level directory of your package hierarchy (the one containing name1).
A second way to compile classes that are in packages is to go to directory above the one containing your servlets, and then do "javac directory\YourServlet.java" (Windows; note the backslash) or "javac directory/YourServlet.java" (Unix; note the forward slash). For example, suppose again that your base directory is C:\JavaWebServer\servlets and your package name (and thus subdirectory name) is hall, and you were on Windows. In that case, you'd do following:
DOS> cd C:\JavaWebServer\servlets
DOS> javac hall\YourServlet.java
Note that, on Windows, most JDK 1.1 versions of javac require a backslash, not a forward slash, after directory name. This is fixed in JDK 1.2, but since many Web servers are configured to use the JDK 1.1, many servlet authors stick with JDK 1.1 for portability.
Finally, another advanced option is to keep source code in a location distinct from the .class files, and use javac's "-d" option to install them in the location the Web server expects.
Running the Servlet
With the Java Web Server, servlet are placed in the servlets directory within the main JWS installation directory, and are invoked via http://host/servlet/ServletName. Note that the directory is servlets plural, while URL refers to servlet, singular. Since this example was placed in the hall package, it would be invoked via http://host/servlet/hall.HelloWorld. Other Web servers may have slightly different conventions on where to install servlets and how to invoke them. Most server also let you define aliases for servlets, so that a servlet can be invoked via http://host/any-path/any-file.html. The process for doing this is completely server-specific; check your server's documentation for the details.
A Servlet that Generates HTML
Most servlet generate HTML, not plain text as in the previous example. To do that, you need two additional steps: tell the browser that you're sending back HTML, and modify the println statements to build a legal Web page. The first step is done by setting Content-Type response header. In general, headers can be set via the setHeader method of HttpServletResponse, but setting the content type is such a common task that there is also a special setContentType method just for this purpose. Note that you need to set the response headers before actually returning any of the content via the PrintWriter. Here's an example:
The following program called HelloWWW.java will print Hellow WWW in the browser in the HTML format.
package hall;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWWW extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println(""Transitional//EN\">\n" +
"\n" +
"\n" +
" \n" +
"
"");
}
}
have the following Components:
* Handled by the servlets container.
* Create and initialize the servlets.
* Handle zero or more service call.
* Destroy and garbage collect the servlets.
* A single servlets instance to handle every request
The Basic Servlet Architecture or Life Cycle
Servlet container create only one instance of each servlet but the request of each user is handled with a separate thread. Each thread then calls the doGet or doPost methods. This idea is shown in the above Figure-5.
1.The init method of the servlets is called when the servlets is first created and each time the server receives a request for a servlets, the server spawns a new thread calls service method.
2.The service method check the HTTP request type (GET,SET, PUT, DELETE, etc.) and calls doGet, doPost, doPut,doDelete, etc. method as appropriate.
3.Finally, the server may decide to remove a previous loaded servlet. In this case, the server calls destroy method of the servlets.
HTTP
Before we can start writing the first Servlets, we need to know some basics of HTTP ("HyperText Transfer Protocol"), the protocol which is used by a WWW client (e.g. a browser) to send a request to a Web Server.
HTTP is the request-response oriented protocol. An HTTP request consist of a request method, a URI, header fields and a body (which can be empty). An HTTP response contain a result and again header fields and a body.
The service method of HttpServlet dispatch a request to different Java methods for different HTTP request methods. It recognize the standard HTTP/1.1 methods and should not be overridden in subclasses unless you need to implement additional methods. The recognized methods are GET, PUT,HEAD, POST, DELETE, OPTIONS and TRACE. Other methods are answered with a Bad Request HTTP error. An HTTP method XXX is dispatched to the Java method doXxx, e.g. GET -> doGet. All these method expect the parameters "(HttpServletRequest req, HttpServletResponse res)". The method doOptions and doTrace have suitable default implementations and are usually not overridden. The HEAD method (which is supposed to return the same header lines that a GET method would return, but doesn't include a body) is performed by calling the doGet and ignoring any output that is written by this method. That leaves us with the method doGet doPut doPost and doDelete whose default implementations in HttpServlet return a Bad Request HTTP error. A subclass of HttpServlet overrides one or more of these method to provide a meaningful implementation.
The request data is passed to all the methods through the first argument of type HttpServletRequest (which is a subclass of the more general ServletRequest class). The response can be created with the methods of the second argument of type HttpServletResponse (a subclass of ServletResponse).
When you request a URL in the Web Browser, the GET method is used for the request. A GET request does not have the body (i.e. the body is empty). The response should contain the body with the response data and header fields which describe the body (especially Content-Type and Content-Encoding). When you send an HTML form, either GET or POST action can be used. With the GET request the parameters are end in the URL, with a POST request they are transmited in the body. HTML editors and upload tools use PUT requests to the upload resources to a Web Server and DELETE requests to delete resources.
Servlet Types
# Classic Servlets-service() Method
# JSP's-Java Embeded in HTML Templates
# Http Servlets-doGet & doPost()
# Visual Servlets-Generated by Visual Age
Packages in Servlets
There are two types of package available in servlets which are as follows:
1.javax.servlet.*
2.javax.servlet.http.*
Interfaces in javax.servlet.*
# RequestDispatcher
# Servlet
# ServletRequest
# ServletResponse
# ServletConfig
# ServletContext
# SingleThreadModel
classes in javax.servlet.*
# GenericServlet
# ServletInputStream
# ServletOutputStream
# ServletException
# UnavailableException
Interfaces in javax.servlet.http.*
# HttpServletRequest
# HttpServletResponse
# HttpSessionBindingListener
# HttpSessionContext
# HttpSession
classes in javax.servlet.http.*
# Cookie
# HttpServlet
# HttpUtils
# HttpSessionBindingEvent
Servlet Scope Objects
The
There are four scope objects in servlets which enables the sharing information between web components. The scope objects and their corresponding Java classes are listed below:
# Web Context javax.servlet.ServletContext
# Request javax.servlet.HttpServletRequest
# Session javax.servlet.http.HttpSession
# Page javax.servlet.jsp.PageContext
You can get the attribute values from servlet scope objects using getAttribute method and set new values of attributes using setAttribute method. For example, you can get the client’s IP address by calling the getRemoteAddr method of HttpServletRequest class.
Following Examples prints the Hello World in the browser
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorld extends HttpServlet
{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
PrintWriter out = response.getWriter();
out.println("Hello World");
}
}
To be a servlet, a class should extend the HttpServlet and override doGet or doPost (or both), depending on whether the data is being sent by GET or by POST. These methods take two arguments: an HttpServletRequest and an HttpServletResponse. The HttpServletRequest has methods that let you find out about the incoming information such as FORM data, HTTP request headers, and the like.
The HttpServletResponse has method that lets you specify the HTTP response line (200, 404, etc.), response headers (Content-Type, Set-Cookie, etc.), and, most importantly, lets you obtain a PrintWriter used to send output back to the client. For simple servlet, most of the effort is spent in println statements that generate the desired page. Note that doGet and doPost throw two exception, so you are required to include them in the declaration. Also note that you have to import classes in the java.io (for PrintWriter, etc.), javax.servlet (for HttpServlet, etc.), and javax.servlet.http (for HttpServletRequest and HttpServletResponse). Finally, note that doGet and doPost are called by service method, and sometimes you may want to override service directly, e.g. for a servlet that handles both GET and POST request.
Compiling and Installing the Servlet
Note that the specific details for installing servlet vary from Web server to Web server. Please refer to your Web server documentation for the definitive directions. The on-line examples are running on Java Web Server (JWS) 2.0, where servlet are expected to be in a directory called servlets in the JWS installation hierarchy. However, I placed this servlets in a separate package (hall) to avoid conflicts with other servlets on this server; you'll want to do the same if you are using a Web server that is used by other people and doesn't have a good infrastructure for the "virtual servers" to prevent these conflicts automatically. Thus, HelloWorld.java actually goes in a subdirectory called hall in the servlets directory.
Note that setup on most other servers is similar, and the servlets and JSP examples in the tutorial have also been tested using BEA WebLogic and IBM WebSphere 3.0. WebSphere has an excellent mechanism for virtual servers, and it is not necessary to use packages solely to prevent name conflicts with other users.
If you've never used the packages before, there are two main ways to compile classes that are in packages.
One way is to set your CLASSPATH to point to directory above the one actually containing your servlets. You can them compile normally from within the directory. For example, if your base directory is C:\JavaWebServer\servlets and your package name (and thus subdirectory name) is the hall, and you were on Windows, you'd do:
DOS> set CLASSPATH=C:\JavaWebServer\servlets;%CLASSPATH%
DOS> cd C:\JavaWebServer\servlets\hall
DOS> javac YourServlet.java
The first part, setting CLASSPATH, you probably want to do permanently, rather than each time you start a new DOS window. On Windows 95/98 you'd typically put the "set CLASSPATH=..." statement in your autoexec.bat file somewhere after the line that set CLASSPATH to point to servlet.jar and jsp.jar. On Windows NT, you'd go to Start menu, select Settings, select Control Panel, select System, select Environment, then enter the variable and value. Note also that if your package were of the form name1.name2.name3 rather than simply name1 as here, you'd still have the CLASSPATH point to the top-level directory of your package hierarchy (the one containing name1).
A second way to compile classes that are in packages is to go to directory above the one containing your servlets, and then do "javac directory\YourServlet.java" (Windows; note the backslash) or "javac directory/YourServlet.java" (Unix; note the forward slash). For example, suppose again that your base directory is C:\JavaWebServer\servlets and your package name (and thus subdirectory name) is hall, and you were on Windows. In that case, you'd do following:
DOS> cd C:\JavaWebServer\servlets
DOS> javac hall\YourServlet.java
Note that, on Windows, most JDK 1.1 versions of javac require a backslash, not a forward slash, after directory name. This is fixed in JDK 1.2, but since many Web servers are configured to use the JDK 1.1, many servlet authors stick with JDK 1.1 for portability.
Finally, another advanced option is to keep source code in a location distinct from the .class files, and use javac's "-d" option to install them in the location the Web server expects.
Running the Servlet
With the Java Web Server, servlet are placed in the servlets directory within the main JWS installation directory, and are invoked via http://host/servlet/ServletName. Note that the directory is servlets plural, while URL refers to servlet, singular. Since this example was placed in the hall package, it would be invoked via http://host/servlet/hall.HelloWorld. Other Web servers may have slightly different conventions on where to install servlets and how to invoke them. Most server also let you define aliases for servlets, so that a servlet can be invoked via http://host/any-path/any-file.html. The process for doing this is completely server-specific; check your server's documentation for the details.
A Servlet that Generates HTML
Most servlet generate HTML, not plain text as in the previous example. To do that, you need two additional steps: tell the browser that you're sending back HTML, and modify the println statements to build a legal Web page. The first step is done by setting Content-Type response header. In general, headers can be set via the setHeader method of HttpServletResponse, but setting the content type is such a common task that there is also a special setContentType method just for this purpose. Note that you need to set the response headers before actually returning any of the content via the PrintWriter. Here's an example:
The following program called HelloWWW.java will print Hellow WWW in the browser in the HTML format.
package hall;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWWW extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println(""Transitional//EN\">\n" +
"\n" +
"
"
"
Hello WWW
\n" +"");
}
}
Subscribe to:
Posts (Atom)