AJP U4-1
AJP U4-1
AJP U4-1
server pages – basics- beneath JSP -JSP session - JSP architecture – security.
Servlet basics
Servlet is a java program that runs inside JVM on the web server. Servlet technology is used to
create a web application (resides at server side and generates a dynamic web page).
NOTE
Limitations of CGI
Server has to create a new CGI process for every client request. For example, If 100 users are
accessing the web application, then the server has to create 100 CGI processes to handle the
request made by them. Since a server has limited resources, creating new process every time for
a new request is not a viable option, this imposed the limitation on server, due to that the server
cannot handle more than a specified number of users at the same time.
Applications of Servlet
• Read the explicit data sent by the clients (browsers). This includes an HTML form on a
Web page or it could also come from an applet or a custom HTTP client program.
• Read the implicit HTTP request data sent by the clients (browsers). This includes
cookies, media types and compression schemes the browser understands, and so forth.
• Process the data and generate the results. This process may require talking to a database,
executing an RMI or CORBA call, invoking a Web service, or computing the response
directly.
• Send the explicit data (i.e., the document) to the clients (browsers). This document can be
sent in a variety of formats, including text (HTML or XML), binary (GIF images), Excel,
etc.
• Send the implicit HTTP response to the clients (browsers). This includes telling the
browsers or other clients what type of document is being returned (e.g., HTML), setting
cookies and caching parameters, and other such tasks.
A servlet life cycle can be defined as the entire process from its creation till the destruction. The
following are the paths followed by a servlet.
The entire life cycle of a Servlet is managed by the Servlet container which uses the
javax.servlet.Servlet interface to understand the Servlet object and manage it.
Stages of the Servlet Life Cycle: The Servlet life cycle mainly goes through four stages,
• Loading a Servlet.
• Initializing the Servlet.
• Request handling.
• Destroying the Servlet.
Loading a Servlet: The first stage of the Servlet lifecycle involves loading and initializing the
Servlet by the Servlet container.
Instantiation : Creates an instance of the Servlet. To create a new instance of the Servlet, the
container uses the no-argument constructor.
NOTE
Initializing a Servlet: After the Servlet is instantiated successfully, the Servlet container
initializes the instantiated Servlet object. The container initializes the Servlet object by invoking
the Servlet.init(ServletConfig) method which accepts ServletConfig object reference as
parameter.
The Servlet container invokes the Servlet.init(ServletConfig) method only once, immediately
after the Servlet.init(ServletConfig) object is instantiated successfully.
Handling request: After initialization, the Servlet instance is ready to serve the client requests.
The Servlet container performs the following operations when the Servlet instance is located to
service a request :
It creates the ServletRequest and ServletResponse objects. In this case, if this is a HTTP
request, then the Web container creates HttpServletRequest and HttpServletResponse objects
which are subtypes of the ServletRequest and ServletResponse objects respectively.
After creating the request and response objects it invokes the Servlet.service(ServletRequest,
ServletResponse) method by passing the request and response objects.
NOTE
The service() method is the main method to perform the actual task.
The doGet() and doPost() are most frequently used methods with in each service request.
A GET request results from a normal request for a URL or from an HTML form that has no
METHOD specified and it should be handled by doGet() method.
// Servlet code
A POST request results from an HTML form that specifically lists POST as the METHOD and it
should be handled by doPost() method.
// Servlet code
}
Destroying a Servlet:The destroy() method is called only once at the end of the life cycle of a
servlet. This method gives your servlet a chance to close database connections, halt background
threads, write cookie lists or hit counts to disk, and perform other such cleanup activities.
After the destroy() method is called, the servlet object is marked for garbage collection. The
destroy method definition looks like this −
// Finalization code...
It is common in web applications to pass data or parameters from one to another page. To
retrieve the values of various elements in a HTML form or from another page, we can use the
following methods which are available in HttpServletRequest object:
login.html
<html>
<head>
<title>Login</title>
</head>
<body>
</form>
</body>
</html>
Authenticate.java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*/
* @see HttpServlet#HttpServlet()
*/
public Authenticate() {
super();
/**
*/
response.getWriter().print("Valid user!");
else
In the above example we are retrieving the data from login page using the getParameter()
method.
To read values of common input fields from HTML form on the server side with Java Servlet.
Handling form data represented in HTML page is a very common task in web development. A
typical scenario is the user fills in fields of a form and submits it. The server will process the
request based on the submitted data, and send response back to the client. The following picture
depicts that workflow with Java servlet on the server side:
<input>, <select>, <textarea>…: to create form fields like text boxes, dropdown list, text area,
check boxes, radio buttons,… and submit button.
To make the form works with Java servlet, we need to specify the following attributes for the
<form> tag:
method=”post”: to send the form data as an HTTP POST request to the server. Generally, form
submission should be done in HTTP POST method.
action=”URL of the servlet”: specifies relative URL of the servlet which is responsible for
handling data posted from this form.
</form>
On the server side, we need to create a Java servlet which is mapped to the URL: loginServlet, as
specified in the form’s action attribute.
Following is code of the servlet:
When the user submits the login form above, the servlet’s doPost() method will be invoked by
the servlet container. Typically we will do the following tasks inside doPost() method:
Read values of the fields posted from the form via the request object (implementation of
javax.servlet.http.HttpServletRequest interface).
Do some processing, e.g. connecting to database to validate the username and password.
Return response back to the user via the respone object (implementation of
javax.servlet.http.HttpServletResponse interface).
To read values of form’s fields, the HttpServletRequest interface provides the following
methods:
String getParameter(String name): gets value of a field which is specified by the given name, as
a String. The method returns null if there is no form field exists with the given name.
String[] getParameterValues(String name): gets values of a group of fields which have same
name, in an array of String objects. The method returns null if there is no field exists with the
given name.
For example, we can write the following code in the doPost() method to read values of form’s
fields:
String username = request.getParameter("username");
To send response back to the client, we need to obtain a writer from the response object by
calling the method getWriter() of the HttpServletResponse interface:
Then use the print() or println() method to deliver the response (in form of HTML code).
For example:
htmlRespone += "</html>";
writer.println(htmlRespone);
Here’s complete code of the servlet class to process the login form:
package net.codejava.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
htmlRespone += "</html>";
// return response
writer.println(htmlRespone);
Here’s an example output when submitting the above login form in browser:
The session tracking
Session Tracking is a way to maintain state (data) of an user. It is also known as session
management in servlet.
Http protocol is a stateless so we need to maintain state using session tracking techniques. Each
time user requests to the server, server treats the request as the new request. So we need to
maintain the state of an user to recognize to particular user.
HTTP is stateless that means each request is considered as the new request. It is shown in the
figure given below:
HttpSession Interface
The Java servlets provide the HttpSession Interface that gives a way to spot a particular user
among multiple page requests or to keep the information about that user. In fact, the Java servlets
use the HttpSession interface to establish a connection between the HTTP server and the HTTP
client.
The following diagram shows the working of the HttpSession interface in a session.
User A and User B both are requesting to connect to a server. The servlet container uses the
HttpSession interface to connect to the server by creating a unique id for each request. The
unique id is used to identify a user. The unique id can be stored in a request parameter or in a
cookie.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
if (session.isNew()) {
session.setAttribute(userIDKey, userID);
} else {
visitCount = (Integer)session.getAttribute(visitCountKey);
visitCount = visitCount + 1;
userID = (String)session.getAttribute(userIDKey);
session.setAttribute(visitCountKey, visitCount);
response.setContentType("text/html");
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(docType +
"<html>\n" +
</tr>\n" +
"<tr>\n" +
" <td>id</td>\n" +
</tr>\n" +
"<tr>\n" +
</tr>\n" +
"<tr>\n" +
</tr>\n" +
"<tr>\n" +
</tr>\n" +
"<tr>\n" +
</tr>\n" +
"</table>\n" +
"</body>
</html>"
);
}
Compile the above servlet SessionTrack would display the following result when you would
run for the first time
Now try to run the same servlet for second time, it would display following result.
Database connectivity
Servlets are mainly used in Dynamic web applications which provides dynamic responses to
client requests. In most cases, Dynamic web applications access a database to provide the client
requested data. We can use Java standard database connection – JDBC in Servlets to perform
database operations.
. A database connection is required in order to interact with a database, and there are several
methods for establishing a database connection, including:
1.JDBC (Java Database Connectivity): JDBC is a standard API for connecting to databases
from Java applications. JDBC provides a set of classes and interfaces that enable Java
applications to interact with databases.
2.JPA (Java Persistence API): JPA is a Java API for connecting to databases and performing
database operations. JPA is a standard API for Java applications, and it provides a simple and
efficient way to connect to databases and perform database operations.
4.JNDI (Java Naming and Directory Interface): JNDI is a Java API for connecting to
databases and performing database operations. JNDI provides a simple and efficient way to
connect to databases and perform database operations.
Note
There are 5 steps to connect any java application with the database using JDBC. These steps are
as follows:
The forName() method of Class class is used to register the driver class. This method is used to
dynamically load the driver class.
example
Class.forName ("oracle.jdbc.driver.OracleDriver");
Note:
The createStatement() method of Connection interface is used to create statement. The object of
statement is responsible to execute queries with the database.
Statement stmt=con.createStatement();
The executeQuery() method of Statement interface is used to execute queries to the database.
This method returns the object of ResultSet that can be used to get all the records of a table.
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
By closing connection object statement and ResultSet will be closed automatically. The close()
method of Connection interface is used to close the connection.
con.close();
Java Server Pages (JSP) is a server-side programming technology that enables the creation of
dynamic, platform-independent method for building Web-based applications. JSP have access to
the entire family of Java APIs, including the JDBC API to access enterprise databases.
JSP technology is used to create web application just like Servlet technology. It can be thought
of as an extension to Servlet because it provides more functionality than servlet such as
expression language, JSTL, etc.
A JSP page consists of HTML tags and JSP tags. The JSP pages are easier to maintain than
Servlet because we can separate designing and development. It provides some additional features
such as Expression Language, Custom Tags, etc.
Features of JSP
It Does Not Require Advanced Knowledge of Java: Suitable for users with basic Java skills.
Reduction in the Length of Code: JSP uses action tags, custom tags, etc., to minimize code
length.
Java Scriplets: Allows embedding Java code, variables, and expressions within JSP pages.
Declaration Tag: Used to declare variables and methods within JSP pages.
Implicit Objects: Provides built-in objects that reduce the length of code.
Make Interactive Websites: Facilitates the creation of dynamic web pages that interact with
users in real-time.
Connection to Database is Easier: Simplifies connecting to databases and allows for easy data
reading and writing.
Extension to Servlet: Inherits all features of servlets and includes implicit objects and custom
tags.
Portable, Powerful, Flexible, and Easy to Maintain: Browser and server independent, making
it versatile and easy to manage.
To create the first JSP page, write some HTML code as given below, and save it by .jsp
extension. We have saved this file as index.jsp. Put it in a folder and paste the folder in the web-
apps directory in apache tomcat to run the JSP page.
index.jsp
Let's see the simple example of JSP where we are using the scriptlet tag to put Java code in the
JSP page.
<html>
<body>
<% out.print(2*5); %>
</body>
</html>
JSP Session
In JSP, the session is the most regularly used implicit object of type HttpSession. It is mainly
used to approach all data of the user until the user session is active. Methods used in session
Implicit Object are as follows: Method 1: isNew(): This method is used to check either the
session is new or not.
Cookies: Cookies are text files that allow programmers to store some information on a client
computer, and they are kept for usage tracking purposes.
Passing Session ID in URL: Adding and passing session ID to URL is also a way to identify a
session. However, this method is obsolete and insecure because the URL can be tracked.
In JSP, session is an implicit object of type HttpSession.The Java developer can use this object to
set,get or remove attribute or to get session information.
• A session object is the most commonly used implicit object implemented to store user
data to make it available on other JSP pages until the user's session is active.
• The session implicit object is an instance of a javax.servlet.http.HttpSession interface.
• This session object has different session methods to manage data within the session
scope.
This example describes how to use the HttpSession object to find out the creation time and the
last-accessed time for a session. We would associate a new session with the request if one does
not already exist.
<%
if (session.isNew() ){
session.setAttribute(userIDKey, userID);
session.setAttribute(visitCountKey, visitCount);
}
visitCount = (Integer)session.getAttribute(visitCountKey);
visitCount = visitCount + 1;
userID = (String)session.getAttribute(userIDKey);
session.setAttribute(visitCountKey, visitCount);
%>
<html>
<head>
<title>Session Tracking</title>
</head>
<body>
<center>
<h1>Session Tracking</h1>
</center>
<th>Session info</th>
<th>Value</th>
</tr>
<tr>
<td>id</td>
<tr>
<td>Creation Time</td>
</tr>
<tr>
</tr>
<tr>
<td>User ID</td>
</tr>
<tr>
<td>Number of visits</td>
</tr>
</table>
</body>
</html>
Now put the above code in main.jsp and try to access http://localhost:8080/main.jsp. Once
you run the URL, you will receive the following result
JSP architecture
JSP architecture gives a high-level view of the working of JSP. JSP architecture is a 3 tier
architecture. It has a Client, Web Server, and Database. The client is the web browser or
application on the user side. Web Server uses a JSP Engine i.e; a container that processes JSP.
For example, Apache Tomcat has a built-in JSP Engine. JSP Engine intercepts the request for
JSP and provides the runtime environment for the understanding and processing of JSP files. It
reads, parses, build Java Servlet, Compiles and Executes Java code, and returns the HTML page
to the client. The webserver has access to the Database. The following diagram shows the
architecture of JSP.
JSP which stands for Java Server Pages. It is a server-side technology. It is used for creating
web applications. It is used to create dynamic web content. In this JSP tags are used to insert
JAVA code into HTML pages. It is an advanced version of Servlet Technology. It is a Web-
based technology that helps us to create dynamic and platform-independent web pages. In this,
Java code can be inserted in HTML/ XML pages or both. JSP is first converted into a servlet by
JSP container before processing the client’s request. JSP Processing is illustrated and discussed
in sequential steps prior to which a pictorial media is provided as a handful pick to understand
the JSP processing better which is as follows:
Step 1: The client navigates to a file ending with the .jsp extension and the browser initiates an
HTTP request to the webserver. For example, the user enters the login details and submits the
button. The browser requests a status.jsp page from the webserver.
Step 2: If the compiled version of JSP exists in the web server, it returns the file. Otherwise, the
request is forwarded to the JSP Engine. This is done by recognizing the URL ending with .jsp
extension.
Step 3: The JSP Engine loads the JSP file and translates the JSP to Servlet(Java code). This is
done by converting all the template text into println() statements and JSP elements to Java code.
This process is called translation.
Step 4: The JSP engine compiles the Servlet to an executable .class file. It is forwarded to the
Servlet engine. This process is called compilation or request processing phase.
Step 5: The .class file is executed by the Servlet engine which is a part of the Web Server. The
output is an HTML file. The Servlet engine passes the output as an HTTP response to the
webserver.
Step 6: The web server forwards the HTML file to the client’s browser.
Security
JavaServer Pages and servlets make several mechanisms available to Web developers to secure
applications. Resources are protected declaratively by identifying them in the application
deployment descriptor and assigning a role to them.
Several levels of authentication are available, ranging from basic authentication using identifiers
and passwords to sophisticated authentication using certificates.
The authentication mechanism in the servlet specification uses a technique called role-based
security. The idea is that rather than restricting resources at the user level, you create roles and
restrict the resources by role.
Different roles in file tomcat-users.xml, which is located off Tomcat's home directory in
conf. An example of this file is shown below −
<tomcat-users>
</tomcat-users>
When you use the FORM authentication method, you must supply a login form to prompt the
user for a username and password. Following is a simple code of login.jsp. This helps create a
form for the same purpose
Example
<html>
<tr>
<td>Login</td>
</tr>
<tr>
<td>Password</td>
</tr>
</table>
</form>
</body>
</html>
The HttpServletRequest object provides the following methods, which can be used to mine
security information at runtime.