Java Unit7 Ashok Kumar K
Java Unit7 Ashok Kumar K
JAVA/ J2EE
Notes prepared by
Mr. Ashok Kumar K
9742024066 | [email protected]
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
Unit 7:
7.1 Basics
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 (presentation logic). 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.
Below is the snap shot of the servlet program that we have seen in previous chapter. Notice the application logic and presentation logic
are coupled together which is not recommended. In later sections we see how JSP helps in separating the application logic from the
presentation logic.
Defining a JSP
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 a plain HTML but it also will be interspersed with special JSP tags.
Java Server Pages (JSP) is a server side program that is similar in design and functionality to a java Servlet. A JSP is called by client to
provide a web service, the nature of which depends on the J2EE Application.
Servlet is written using Java programming language and JSP is written in HTML, XML, or in the client’s
responses are encoded as an output string object that is format that is interspersed with the scripting
passed to the println() method. The output string object is elements, directives, and actions comprised of
formatted in HTML, XML, or whatever format are required by Java programming language and JSP syntax
the client
Servlets use println statements for printing an HTML document which is usually very difficult to use. JSP has no such
tedious task to maintain.
JSP needs no compilation, CLASSPATH setting and packaging.
In a JSP page visual content and logic are separated, which is not possible in a servlet.
There is automatic deployment of a JSP; recompilation is done automatically when changes are made to JSP pages.
Usually with JSP, Java Beans and custom tags web application is simplified
Reduces Development time
A JSP page is executed in a JSP container (or JSP engine), which is installed in a web server (or an application server). When a client
requests 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 abstraction 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 when 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.
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.
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.
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.
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 tags define java code that is to be executed before the output of a JSP program is sent to the browser.
There are five types of JSP tags:
1. Comment Tag
2. Declaration statement Tag
3. Directive Tag
4. Expression Tag
5. Scriptlet Tag
Comment Tag
A comment tag opens with <%-- and closes with --%>, and is followed by a comment that usually describes the functionality of
statements that follow the comment tag.
Ex:
<%--
This is a JSP Comment
--%>
A Declaration statement tag opens with <%! and is followed by a Java declaration statements that define variables, objects, and
methods.
Ex:
<%!
int a; String s;
Employee e = new Employee();
%>
Directive Tag
A Directive tag opens with <%@ and closes with %>. There are three commonly used directives.
Import
Used to import java packages into JSP program
Ex: <%@ page import = “java.sql.*” %>
Include
It inserts a specified file into the JSP program replacing the include tag
Ex: <%@ include file = ”Keogh\book.html” %>
Taglib
It specifies a file that contains a tag library
Ex: <%@ taglib uri = “myTags.tld” %>
Expression Tag
An expression tag opens with <%= and is used for an expression statement whose result replaces the expression tag. It closes with %>
Ex:
<%! int a = 5, b = 10; %>
<%= a+b %>
Scriptlet Tag
A scriptlet tag opens with <% and contains commonly used java control statements and loops. It closes with %>
JSP Implicit Objects are the Java objects that the JSP Container makes available to developers in each page and developer can call
them directly without being explicitly declared. JSP Implicit Objects are also called pre-defined variables.
JSP supports nine Implicit Objects which are listed below:
Object Description
request This is the HttpServletRequest object associated with the
request.
response This is the HttpServletResponse object associated with the
response to the client.
out This is the PrintWriter object used to send output to the
client.
session This is the HttpSession object associated with the request.
application This is the ServletContext object associated with application
context.
config This is the ServletConfig object associated with the page.
pageContext This encapsulates use of server-specific features like higher
performance JspWriters.
page This is simply a synonym for this, and is used to call the
methods defined by the translated servlet class.
Exception The Exception object allows the exception data to be
accessed by designated JSP.
<html>
<body>
<%!
Mr. Ashok Kumar K | 9742024066 | [email protected]
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
int a = 10;
String s = "TEST";
%>
<p>
int value is <%= a %>
String value is <%= s %>
</p>
</body>
</html>
<html>
<body>
<%!
int findSum(int a, int b) {
return a+b;
}
%>
<p>
sum of 2 and 5 is <%=findSum(2,5) %>
</p>
</body>
</html>
<html>
<body>
<%!
int grade = 70;
%>
<html>
<body>
The browser generates a user request string whenever the submit button is selected.
The user request string consists of:
1. URL
2. Query String
Example
Query String
JSP program should parse the query string to extract the values of fields that are to be processed by a JSP. A JSP can parse the query
string in two ways:
a) Using request.getParameter()
getParameter() method requires an argument, which is the name of the field whose value you want to retrieve.
Ex:
<%!
String uname = request.getParameter(“username”);
String pword = request.getParameter(“password”);
%>
b) Using request.getParameterValues()
Multi valued fields (such as checkboxes and select menus) can be read using getParameterValues() method.
It returns multiple values from the field specified as an argument to this method.
Ex:
<%!
String[] games = request.getParameterValues(“favgames”);
%>
Example Program
Here we will develop a sample JSP to read the parameters from the client request.
<html>
<body>
<form action='readParam.jsp'>
Enter your name: <input type='text' name='username' /> <br />
<br /> Select your favourite games : <br/>
<select name='games' multiple=multiple>
<option value='Cricket'>Cricket</option>
<option value='Football'>Football</option>
<option value='Hockey'>Hockey</option>
<option value='Tennis'>Tennis</option>
</select> <br />
<br /> <input type='submit' value='Click me' />
</form>
</body>
</html>
<html>
<body>
<%
String name = request.getParameter("username");
String games[] = request.getParameterValues("games");
%>
Step 3:
Run param.html by entering the direct URL in the browser.
URL
Protocol
It defines the rules that are used to transfer the request string from the browser to JSP program. Three commonly used
protocols are HTTP, HTTPS, and FTP
Host
It is the internet protocol address (IP) or name of the server that contains the JSP program.
Port
It is the port that the host monitors. If the port is not specified, it is defaulted to 80.
Whenever HTTP is used, the host will be monitoring the port 80
Virtual path to JSP program
The server maps this virtual path to the physical path
As mentioned earlier, HTTP is a "stateless" protocol which means each time when a client retrieves a web page, the client opens a
separate connection to the web server and the server does not keep any record of previous client request. The question here is how
can we maintain the session between the client and a server?
As explained in the previous chapter, there are four possible ways to maintain the session between client and a server
Cookies
Hidden fields
URL Rewriting
HttpSession interface (session object)
A hidden field is a field in HTML form whose value isn’t displayed on the HTML page. You can assign a value to the hidden field in a
JSP program before the program sends the HTML page to the browser.
Consider a login screen which asks for username and password.
Here is how the session is tracked using hidden field:
Upon submitting the form, the browser sends the username and password to the JSP program.
The JSP program then validates the username and password and generates another dynamic HTML page. This newly
generated HTML page has a form that contains hidden field which is assigned a userID along with other fields as well.
When the user submits the form in the new HTML page, the userID stored in the hidden field and other information on the form
are sent to the JSP program.
This cycle continues where the JSP program processing the request string receives the userID as a parameter and then
passes the userID to the next dynamically built HTML page as a hidden field.
In this way, each HTML page and subsequent JSP program has access to userID and therefore can track the session.
7.7.2 Cookies
A cookie is a small piece of information created by a JSP program that is stored in the client’s hard disk by the browser. Cookies are
used to store various kind of information such as username, password, and user preferences, etc.
<html>
<body>
<%!
String cName = "userID";
String cValue = "1VK06IS009";
Cookie myCookie = new Cookie (cName, cValue);
<html>
<body>
<%!
String cName = "userID";
String name;
String value;
int found = 0;
%>
<%
Cookie[] myCookies = request.getCookies();
for (int i=0;i<myCookies.length;i++) {
name = myCookies[i].getName();
if (name.equals(cName)) {
value = myCookies[i].getValue();
found = 1;
}
}
if (found==1) { %>
<p> Cookie Name: <%= cName %> </p>
<p> Cookie Value: <%= value %> </p>
<% } else { %>
<p> Cookie NOT FOUND </p>
<%>} %>
</body>
</html>
A JSP database system is able to share information among JSP programs within a session by using a session object. Each time a
session is created, a unique ID is assigned to the session and stored as a cookie. The unique ID enables JSP programs to track
multiple sessions simultaneously while maintaining data integrity of each session. In addition to session ID, a session object is also
used to store other types of information called attributes.
<html>
<body>
<%!
String attName = "userID";
String attValue = "1VK06IS009";
%>
<%
session.setAttribute(attName, attValue);
%>
</body>
</html>
<html>
<body>
<%!
Enumeration<String> e;
%>
<%
e = session.getAttributeNames();
while (e.hasMoreElements()) {
String name = (String) e.nextElement();
String value = (String) session.getAttribute(name);
%>
<p> Attribute name : <%= name %></p>
<p> Attribute value : <%= value %></p>
<%
}
%>
</body>
</html>
A Java object runs within a JVM. Likewise, a J2EE application runs within JVM; however, objects used by a J2EE application do not
need to run on the same JVM as the J2EE application. This is because a J2EE application and its components can invoke objects
located on different JVM by using Java RMI system.
RMI is used for remote communication between Java applications and components, both of which must be written in Java
Programming language.
RMI handles transmission of requests and provides the facility to load the object’s bytecode, which is referred to as dynamic code
loading
When client references a remote object, the RMI passes a remote stub for the remote object. The remote stub is the local proxy for the
remote object. The client calls the method on the local stub whenever the client wants to invoke one of the remote object’s methods.
There are three steps necessary to make an object available to remote clients
1. Design an object
2. Compile the object
Designing an object
Besides defining the business logic of an object, the developer must define a remote interface for the object, which identifies methods
that are available to remote clients.
In addition to methods that can be invoked by remote clients, the developer must also define other methods that support the processing
of client invoked methods. There are referred as server methods, while methods invoked by a client are called client methods.
It is done by loading the object into a server. Make sure the RMI remote object registry is running. If not, type the following at the
command line:
C:\> start rmiregistry
Server side of RMI consists of a remote interfaces and methods. Remote interfaces provide the API for clients to access the methods.
Methods provide the business logic that fulfills a client’s request whenever the client remotely invokes them.
HelloInterface.java
import java.rmi.*;
public interface HelloInterface extends Remote {
public String say() throws RemoteException;
}
Hello.java
import java.rmi.*;
import java.rmi.server.*;
Below program in the server side makes the Remote object available to the clients by binding it to the naming registry.
HelloServer.java
import java.rmi.Naming;
Clients can access the remote object by looking up the naming registry for the appropriate entry.
Below example shows how a client can lookup the naming registry to get an instance of the remote object. It also illustrates how a client
can use the remote object to call its methods.
HelloClient.java
import java.rmi.Naming;