Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

AJP U4-1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 35

UNIT – IV

Servlet basics-the servlet life cycle- retrieving information- sending HTML

information- the session tracking- database connectivity. JSP: Introducing Java

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).

Properties of Java Servlet

The properties of Servlets are as follows:

• Servlets work on the server side.


• Servlets are capable of handling complex requests obtained from the web server.

NOTE

Servlets provide a component-based, platform-independent method for building Webbased


applications, without the performance limitations of CGI programs. Servlets have access to the
entire family of Java APIs, including the JDBC API to access enterprise databases.

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.

How Servlet Works


The servlet life cycle

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 servlet is initialized by calling the init() method.


• The servlet calls service() method to process a client's request.
• The servlet is terminated by calling the destroy() method.
• Finally, servlet is garbage collected by the garbage collector of the JVM.

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.

The Servlet container performs two operations in this stage :

Loading : Loads the Servlet class.

Instantiation : Creates an instance of the Servlet. To create a new instance of the Servlet, the
container uses the no-argument constructor.

NOTE

The init() Method

The init() method is called only once.

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.

Here is the signature of this method −


public void service(ServletRequest request, ServletResponse response)

throws ServletException, IOException

The doGet() and doPost() are most frequently used methods with in each service request.

The doGet() Method

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.

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException

// Servlet code

The doPost() Method

A POST request results from an HTML form that specifically lists POST as the METHOD and it
should be handled by doPost() method.

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException

// 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 −

public void destroy()

// Finalization code...

Retrieving information in java servlet

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:

• String getParameter(String name)


• Enumeration getParameterNames()
• String[] getParamterValues(String name)

Following example demonstrates retrieving data from a login page to a servlet:

login.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"


"http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<title>Login</title>
</head>

<body>

<form action="authenticate.java" method="get">

Username: <input type="text" name="txtuser" /><br />

Password: <input type="password" name="txtpass" /><br />

<input type="submit" value="Submit" />

<input type="reset" value="Clear" />

</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;

/**

* Servlet implementation class Authenticate

*/

public class Authenticate extends HttpServlet {

private static final long serialVersionUID = 1L;


/**

* @see HttpServlet#HttpServlet()

*/

public Authenticate() {

super();

// TODO Auto-generated constructor stub

/**

* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse


response)

*/

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

String username = request.getParameter("txtuser");

String password = request.getParameter("txtpass");

if(username.equals("vishnu") && password.equals("college"))

response.getWriter().print("Valid user!");

else

response.getWriter().print("Bad username or password");


}

In the above example we are retrieving the data from login page using the getParameter()
method.

Sending html information in Java Servlet

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:

To create a form in HTML we need to use the following tags:


<form>: to create a form to add fields in its body.

<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.

Example: following is HTML code of a login form:

<form name="loginForm" method="post" action="loginServlet">

Username: <input type="text" name="username"/> <br/>

Password: <input type="password" name="password"/> <br/>

<input type="submit" value="Login" />

</form>

This form would look like this in browser:

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:

public class LoginServlet extends HttpServlet

protected void doPost(HttpServletRequest request,

HttpServletResponse response) throws ServletException, IOException

// code to process the form...

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");

String password = request.getParameter("password");

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:

PrintWriter writer = response.getWriter();

Then use the print() or println() method to deliver the response (in form of HTML code).

For example:

String htmlRespone = "<html>";

htmlRespone += "<h2>Your username is: " + username + "</h2>";

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 {

protected void doPost(HttpServletRequest request,

HttpServletResponse response) throws ServletException, IOException {

// read form fields

String username = request.getParameter("username");

String password = request.getParameter("password");

System.out.println("username: " + username);

System.out.println("password: " + password);

// do some processing here...

// get response writer

PrintWriter writer = response.getWriter();

// build HTML code

String htmlRespone = "<html>";

htmlRespone += "<h2>Your username is: " + username + "<br/>";

htmlRespone += "Your password is: " + password + "</h2>";

htmlRespone += "</html>";

// return response

writer.println(htmlRespone);

Here’s an example output when submitting the above login form in browser:
The session tracking

Session simply means a particular interval of time.

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:

Why use Session Tracking?

To recognize the user It is used to recognize the particular user.

Session Tracking Techniques

There are four techniques used in Session tracking:


• Cookies
• Hidden Form Field
• URL Rewriting
• HttpSession

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.

Session Tracking Example


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.

// Import required java libraries

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

import java.util.*;

// Extend HttpServlet class

public class SessionTrack extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

// Create a session object if it is already not created.

HttpSession session = request.getSession(true);

// Get session creation time.

Date createTime = new Date(session.getCreationTime());

// Get last access time of this web page.

Date lastAccessTime = new Date(session.getLastAccessedTime());


String title = "Welcome Back to my website";

Integer visitCount = new Integer(0);

String visitCountKey = new String("visitCount");

String userIDKey = new String("userID");

String userID = new String("ABCD");

// Check if this is new comer on your web page.

if (session.isNew()) {

title = "Welcome to my website";

session.setAttribute(userIDKey, userID);

} else {

visitCount = (Integer)session.getAttribute(visitCountKey);

visitCount = visitCount + 1;

userID = (String)session.getAttribute(userIDKey);

session.setAttribute(visitCountKey, visitCount);

// Set response content type

response.setContentType("text/html");

PrintWriter out = response.getWriter();

String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +

"transitional//en\">\n";

out.println(docType +

"<html>\n" +

"<head><title>" + title + "</title></head>\n" +

"<body bgcolor = \"#f0f0f0\">\n" +

"<h1 align = \"center\">" + title + "</h1>\n" +

"<h2 align = \"center\">Session Infomation</h2>\n" +

"<table border = \"1\" align = \"center\">\n" +

"<tr bgcolor = \"#949494\">\n" +

" <th>Session info</th><th>value</th>

</tr>\n" +

"<tr>\n" +

" <td>id</td>\n" +

" <td>" + session.getId() + "</td>

</tr>\n" +

"<tr>\n" +

" <td>Creation Time</td>\n" +


" <td>" + createTime + " </td>

</tr>\n" +

"<tr>\n" +

" <td>Time of Last Access</td>\n" +

" <td>" + lastAccessTime + " </td>

</tr>\n" +

"<tr>\n" +

" <td>User ID</td>\n" +

" <td>" + userID + " </td>

</tr>\n" +

"<tr>\n" +

" <td>Number of visits</td>\n" +

" <td>" + visitCount + "</td>

</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.

3.Hibernate: Hibernate is a Java framework for connecting to databases and performing


database operations. Hibernate is a popular framework 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

Database connectivity is an important concept in web development, and it is used to connect to


databases from web applications in order to retrieve and store data. Understanding the different
methods for establishing a database connection is essential for building robust and scalable web
applications.

There are 5 steps to connect any java application with the database using JDBC. These steps are
as follows:

• Register the Driver class


• Create connection
• Create statement
• Execute queries
• Close connection

1) Register the driver class

The forName() method of Class class is used to register the driver class. This method is used to
dynamically load the driver class.

Syntax of forName() method

public static void forName(String className)throws ClassNotFoundException

example

Class.forName("com.mysql.jdbc.Driver"); // for mysql database software

Class.forName ("oracle.jdbc.driver.OracleDriver");

Note:

Since JDBC 4.0, explicitly registering the driver is optional.

2) Create the connection object


The getConnection() method of DriverManager class is used to establish connection with the
database.

Syntax of getConnection() method

1) public static Connection getConnection(String url)throws SQLException.


2) public static Connection getConnection(String url,String name,String password)
throws SQLException.
Example to establish connection with the Oracle database
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","password");

3) Create the Statement object

The createStatement() method of Connection interface is used to create statement. The object of
statement is responsible to execute queries with the database.

Syntax of createStatement() method

public Statement createStatement()throws SQLException

Example to create the statement object

Statement stmt=con.createStatement();

4) Execute the query

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.

Syntax of executeQuery() method

public ResultSet executeQuery(String sql)throws SQLException

Example to execute query

ResultSet rs=stmt.executeQuery("select * from emp");

while(rs.next()){

System.out.println(rs.getInt(1)+" "+rs.getString(2));
}

5) Close the connection object

By closing connection object statement and ResultSet will be closed automatically. The close()
method of Connection interface is used to close the connection.

Syntax of close() method

public void close()throws SQLException

Example to close connection

con.close();

JSP: Introducing Java server pages

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.

JSP more Advantageous than Servlet

• They are easy to maintain.


• No recompilation or redeployment is required.
• Less coding is required in JSP.
• JSP has access to the entire API of JAVA.
• JSP are extended version of Servlet.

Features of JSP

Coding in JSP is Easy: As it involves adding Java code to HTML/XML.


Easy to Use and Learn: It is straightforward and accessible for both Java and non-Java
programmers.

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.

JSP Expression: Evaluates expressions and converts them to strings.

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.

The Lifecycle of a JSP Page

The JSP pages follow these phases:

• Translation of JSP Page


• Compilation of JSP Page
• Classloading (the classloader loads class file)
• Instantiation (Object of the Generated Servlet is created).
• Initialization ( the container invokes jspInit() method).
• Request processing ( the container invokes _jspService() method).
• Destroy ( the container invokes jspDestroy() method).
Note: jspInit(), _jspService() and jspDestroy() are the life cycle methods of JSP.

Creating a simple JSP Page

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>

It will print 10 on the browser.

How to run a simple JSP Page?

Follow the following steps to execute this JSP page:

Start the server

Put the JSP file in a folder and deploy on the server

Visit the browser by the URL http://localhost:portno/contextRoot/jspfile, for example,


http://localhost:8888/myapplication/index.jsp

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.

Different approaches to maintain a session between client and server are:

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.

The session implicit object

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.

Session Tracking Example

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.

<%@ page import = "java.io.*,java.util.*" %>

<%

// Get session creation time.

Date createTime = new Date(session.getCreationTime());

// Get last access time of this Webpage.

Date lastAccessTime = new Date(session.getLastAccessedTime());

String title = "Welcome Back to my website";

Integer visitCount = new Integer(0);

String visitCountKey = new String("visitCount");

String userIDKey = new String("userID");

String userID = new String("ABCD");

// Check if this is new comer on your Webpage.

if (session.isNew() ){

title = "Welcome to my website";

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>

<table border = "1" align = "center">

<tr bgcolor = "#949494">

<th>Session info</th>

<th>Value</th>

</tr>

<tr>

<td>id</td>

<td><% out.print( session.getId()); %></td>


</tr>

<tr>

<td>Creation Time</td>

<td><% out.print(createTime); %></td>

</tr>

<tr>

<td>Time of Last Access</td>

<td><% out.print(lastAccessTime); %></td>

</tr>

<tr>

<td>User ID</td>

<td><% out.print(userID); %></td>

</tr>

<tr>

<td>Number of visits</td>

<td><% out.print(visitCount); %></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.

Role Based Authentication

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 −

<?xml version = '1.0' encoding = 'utf-8'?>

<tomcat-users>

<role rolename = "tomcat"/>

<role rolename = "role1"/>

<role rolename = "manager"/>

<role rolename = "admin"/>

<user username = "tomcat" password = "tomcat" roles = "tomcat"/>

<user username = "role1" password = "tomcat" roles = "role1"/>

<user username = "both" password = "tomcat" roles = "tomcat,role1"/>

<user username = "admin" password = "secret" roles = "admin,manager"/>

</tomcat-users>

Form Based Authentication

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>

<body bgcolor = "#ffffff">

<form method = "POST" action ="j_security_check">

<table border = "0">

<tr>
<td>Login</td>

<td><input type = "text" name="j_username"></td>

</tr>

<tr>

<td>Password</td>

<td><input type = "password" name="j_password"></td>

</tr>

</table>

<input type = "submit" value = "Login!">

</form>

</body>

</html>

Programmatic Security in a Servlet/JSP

The HttpServletRequest object provides the following methods, which can be used to mine
security information at runtime.

You might also like