JSP (Part II)
JSP (Part II)
It is necessary to control the servlet engine's behavior, which can be controlled dynamically by
inserting the file by reusing the JavaBeans components or redirecting or forwarding the user to
another page., i.e., by forwarding the request to another resource, which will possibly be a JSP,
HTML, or other resources.
The JSP specification provides a standard tag called Action tag used within JSP code and is used to
remove or eliminate Scriptlet code from your JSP code as JSP Scriptlets are obsolete and are not
considered nowadays. There are many JSP action tags or elements, and each of them has its own
uses and characteristics. Each JSP action tag is implemented to perform some precise tasks.
The action tag is also implemented to streamline flow between pages and to employ a Java Bean. As
it coincides with the XML standard, the syntax for the action element is:
jsp:forward: is used for forwarding the request and response to other resources.
jsp:include: is used for including another resource.
jsp:body: is used for defining dynamically-defined body of XML element.
jsp:useBean: is used for creating or locating bean objects.
jsp:setProperty: is used for setting the value of property in the bean object.
jsp:getProperty: is used for printing the value of the property of the bean.
jsp:element: is used for defining XML elements dynamically.
jsp:plugin: is used for embedding other components (applets).
jsp:param: is used for setting the parameter for (forward or include) value.
jsp:text: is used for writing template text in JSP pages and documents.
jsp:fallback: is used for printing the message if plugins are working.
jsp:attribute: is used for defining attributes of dynamically-defined XML element.
Advanced Java
Two basic attributes are commonly used for all action tags. These are:
id: The id attribute defines unique action elements and allows actions to be referenced within the
JSP page. When the action creates an object's instance, the id attribute is used to refer to it.
Scope: The scope attribute is used for identifying an action's life cycle. It correlates with the id
attribute because the scope attribute is used to establish that particular object's lifespan associated
with the ID.
Here the syntax and implementation of some actions are described below:
This "include action" allows you to include another resource in the page being generated.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
</body>
</html>
This "forward action" terminates the current page and allows you to forward the request to other
resources.
<!DOCTYPE html>
Advanced Java
<html>
<head>
</head>
<body>
</body>
</html>
It is to be noted that this JSP file and forward_eg.jsp file should have to reside in the same directory
to make it work.
This "param action" is used for setting the parameter for (forward or include) value.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<jsp:forward page="forward_eg.jsp">
</jsp:forward>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h2>UseBean Action</h2>
<h2>
</h2>
</body>
</html>
Advanced Java
package samplePackageName;
public Teacher() {}
this.t_name = t_name;
return t_name;
this.deptno = deptno;
return deptno;
}
Advanced Java
}
Expression tags
Expression tags are one of the most useful scripting elements of JSP. Expression tags use special
tags to print the different java expressions and output directly on the client-side. You can also use
this for displaying information on your client browser.
The expression tag is used to evaluate Java's expression within the JSP, which then converts the
result into a string and forwards the result back to the client browser via the response object.
Essentially, it is implemented for printing the result to the client (browser). An expression tag can
hold any java language expression that can be employed as an argument to the out.print()
method.
The syntax of the expression tag in JSP looks something like:
Syntax:
<%= expression %>
This is how the JSP container sees this when it encounters the above expression:
<%= (6*4) %>
It is to be noted that you will never terminate an expression using semicolon within Expression Tag.
Like this:
<%= (6*4); %>
<html>
<head>
<body>
</body>
</html>
Expression of Values
In this chase, you have to pass the expression of values within the expression tag.
Example:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
</body>
</html>
Advanced Java
Expression of Variables
In this case, you have to initialize a few variables, which can then be passed as the expression of
variables within the expression tag in order to evaluate the result.
Example:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
</body>
</html>
Here, you have to set an attribute using an application implicit object and then display it with a
simple string on another JSP page via an expression tag.
Example(start.jsp):
<!DOCTYPE html>
<html>
<head>
<body>
</body>
</html>
Example(show.jsp):
<!DOCTYPE html>
<html>
<head>
</head>
<body>
</body>
</html>
2. You don't have to write the out.println in the expression tag to print the expression based output
because these are changed into out.print() statement (as shown above the process of
transformation of expression), which gets inserted by the container in the _jspService(-, -) of the
servlet class.
There is another concept of JSP, which are Java objects made available by the developers for each
page, allowing developers to call them directly without any explicit declaration. JSP implicit objects
are essential components used in this regard.
The JSP engine produces these objects during the translation phase (i.e., at the time of translation
from JSP to Servlet). They are being formed within the service method so that JSP developers can
use them directly in Scriptlet without declaration and initialization.
There are a total of nine implicit objects supported by the JSP. These are:
1. out: javax.servlet.jsp.JspWriter
2. request: javax.servlet.http.HttpServletRequest
3. response: javax.servlet.http.HttpServletResponse
4. session: javax.servlet.http.HttpSession
5. application: javax.servlet.ServletContext
6. exception: javax.servlet.jsp.JspException
7. page: java.lang.Object
8. pageContext: javax.servlet.jsp.PageContext
9. config: javax.servlet.ServletConfig
Advanced Java
The brief information about the implicit objects are given below:
An out object is an implicit object for writing data to the buffer and sending output as a response
to the client's browser.
<html>
<head>
</head>
<body>
</body>
</html>
Output:
Today's date-time: Nov 01 12:10:05 IST 2020
A request object is an implicit object that is used to request an implicit object, which is to receive
data on a JSP page, which has been submitted by the user on the previous JSP/HTML page.
Advanced Java
The request implicit object used in Java is an instance of
a javax.servlet.http.HttpServletRequest interface where a client requests a page every time
the JSP engine has to create a new object for characterizing that request.
It is used to request information such as parameters, header information, server names, cookies,
and HTTP methods.
Here is an example of a JSP request implicit object where a user submits login information, and
another JSP page receives it for processing:
Example (HTML file):
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form action="login.jsp">
</form>
</body>
</html>
Advanced Java
Example (login.jsp):
<%@ page import = " java.util.* " %>
<%
%>.
A response object is an implicit object implemented to modify or deal with the reply sent to the
client (i.e., browser) after processing the request, such as redirect responding to another resource
or an error sent to a client.
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.
This session object has different session methods to manage data within the session scope.
You will learn more about the use of the session in subsequent chapters.
It is only available for JSP pages, with the isErrorPage value set as "True". This means Exception
objects can only be used in error pages.
<html>
<head>
</head>
<body>
<form action="submit.jsp">
</form>
</body>
</html>
Example (submit.jsp):
<%@ page errorPage="exception.jsp" %>
Advanced Java
<%
%>
Example (exception.jsp):
<%@ page isErrorPage='true' %>
<%
out.print(exception.getMessage());
%>
A page object is an implicit object that is referenced to the current instance of the servlet. You can
use it instead. Covering it specifically is hardly ever used and not a valuable implicit object while
building a JSP application.
<% String pageName = page.toString();
Advanced Java
out.println("The current page is: " +pageName);%>
A config object is a configuration object of a servlet that is mainly used to access and receive
configuration information such as servlet context, servlet name, configuration parameters, etc. It
uses various methods used to fetch configuration information.
JSP request:
In dynamic web application development, client and server interactions are essential for sending
and receiving information over the Internet. When the browser requests a webpage, a lot of
information is sent to the webserver. Such information cannot be read directly because such
information is part of an HTTP header request.
The JSP request can be defined as an implicit object is an instance of "HttpServletRequest" and is
formed for all JSP requests through the web container. This JSP request gets request information
like a parameter, remote address, header information, server port, server name, character
encoding, content type, etc.
A request object is an implicit object that is used to request an implicit object, which is to receive
data on a JSP page, which has been submitted by the user on the previous JSP/HTML page.
It is used to request information such as parameters, header information, server names, cookies,
and HTTP methods.
<html>
<head>
</head>
<body>
<form action="login.jsp">
</form>
</body>
</html>
Example (login.jsp):
<%@ page import = " java.util.* " %>
<%
%>
Cookie[] getCookies(): is used for returning an array that contains all of the cookie-objects of the
client sent associated with a particular request.
Enumeration getHeaderNames(): is used for returning an enumeration of all the header names
associated with the request.
HttpSession getSession(): It is used to return the current session connected with your request or
create a session if it does not have any session.
HttpSession getSession(boolean create): is used to return the current HttpSession linked with
the request or create a new session if there is no current session.
Locale getLocale(): is used for returning the chosen Locale that will be accepted by the client,
based upon the Accept-Language header.
Object getAttribute(String name): is used for returning the value of the named attribute as an
Object or set as null.
ServletInputStream getInputStream(): is used to retrieve the body of the request in the form of
binary data through a ServletInputStream.
String getAuthType(): is used for returning the name of the authentication scheme (BASIC, SSL,
or null) implemented for protecting the servlet.
String getCharacterEncoding(): is used for returning the name of the character encoding
implemented in the body of a request.
String getContentType(): is used for returning the MIME type of the requested content body.
Advanced Java
String getContextPath(): is used for returning the portion of the request URI, which is used for
indicating the context of the request.
String getHeader(String name): is used for returning the value of the specified request header in
the form of a String.
String getMethod(): is used for returning the name of the HTTP method (GET, PUT, and POST)
through which this request was made.
String getPathInfo(): is used for returning any extra path information connected to the URL sent
by the client when the request is made.
String getProtocol(): is used for returning the name and the version of the protocol.
String getQueryString(): is used for returning the query string contained in the request URL
following the path.
String getRemoteAddr(): is used for returning the Internet Protocol (IP) address of the client,
which is used by all websites.
String getRemoteHost(): is used for returning the fully qualified name of the client who sent the
request.
String getRemoteUser(): is used to return the user's login, making an authenticated request or
null if the user has not yet authenticated.
String getRequestURI(): is used for returning the part of a request's URL from the protocol name
till the starting line of the HTTP request.
String getRequestedSessionId():is used for returning the particular session ID of the client.
String getServletPath(): is used for returning the part of this request's URL, which calls the JSP.
String[] getParameterValues(String name): is used for returning an array of String objects that
will contain all of the values of a requested parameter or otherwise returns null.
boolean isSecure(): is used for returning a Boolean value indicating if a request was made
through a secure channel (HTTPS, FTPS) or not.
int getIntHeader(String name): is used for returning the value of a particular request header as
an int.
Advanced Java
int getServerPort(): is used for returning the port number on which a request was received.
JSP response:-
As you know, in dynamic web application development, client and server interactions are necessary
to send and receive information over the Internet. When the browser requests a webpage, a lot of
information is sent to the webserver, and the webserver responds after processing the HTTP
request. Such a response is part of an HTTP header response and cannot be read directly.
A response object is an implicit object implemented to modify or deal with the reply sent to the
client (i.e., browser) after processing the request, such as redirect responding to another resource
or an error sent to a client.
Here is an example of a JSP request and response implicit objects where a user submits login
information, and another JSP page receives it for processing:
Example (HTML file):
<!DOCTYPE html>
<html>
<head>
</head>
Advanced Java
<body>
<form action="login.jsp">
</form>
</body>
</html>
Example (login.jsp):
<%@ page import = " java.util.* " %>
<%
if(username.equals("admin")){
response.sendRedirect("home.jsp");
}else{
out.print("Invalid Username");
%>
JSP has different methods for dealing with implicit response objects, which is of type
HttpServeltResponse. Each of these methods has its own functionality.
Advanced Java
String encodeURL(String url): is used for encoding a particular URL by comprising the session ID
along with it. Otherwise, when the encoding is not required, it will return the URL unchanged.
String encodeRedirectURL(String url): is used for encoding a particular URL for using it in the
sendRedirect method. Otherwise, when the encoding is not required, it will return the URL
unchanged.
boolean containsHeader(String name): is used for returning a Boolean signifying whether the
name response header is already set or not.
void addDateHeader(String name, long date): is used for adding a response header with the
given name along with a date-value.
void addHeader(String name, String value): is used to add a response header with the given
name and a value.
boolean isCommitted(): is used for returning a Boolean value signifying whether the response
has been committed or not.
void addIntHeader(String name, int value): is used for adding a response header with the
specified name along with an integer value.
void flushBuffer(): is used for forcing any content in the buffer for writing it to the client.
void addCookie(Cookie cookie): is used for adding a particular cookie with the response.
void reset(): is used for clearing any data which is present in the buffer, header or status code.
void sendError(int sc): is used for sending an error response (through particular status code) to
its client.
void sendError(int sc, String msg): is used for sending an error response (through some
particular status string) to its client.
void resetBuffer(): is used for clearing the content of the underlying buffer without clearing the
status code or header.
void sendRedirect(String location): is used for sending a short-term redirect response to the
client.
void setBufferSize(int size): is used for setting an ideal buffer size for the response body.
Advanced Java
void setCharacterEncoding(String charset): is used for setting the character encoding (usually
MIME charset - UTF 8) being sent to the client.
void setContentType(String type): is used for setting the content type being sent to the client
when the response has not yet been committed.
void setDateHeader(String name, long date): is used to set a response header with the given
name and date-value.
void setContentLength(int len): is used for setting the length of the body of content in the
response.
void setHeader(String name, String value): is used for setting a response header with the given
name as well as value.
void setIntHeader(String name, int value): is used to set a response header with the given
name and an integer value.
void setLocale(Locale loc): is used for setting the locale of the response in case the response is
not yet committed.
void setStatus(int sc): is used for setting the status code for your response.
Session:
A session can be defined as an object associated with each user with a unique session ID, and the
user's data is based on the account they have registered. Different forms of data can be set in a
session; These data related to each user of the site help the user and the website owner in different
ways. As you know, HTTP is a "stateless" protocol; Whenever a user visits a web page, the user
opens a separate connection with the webserver, and the server does not keep a record of
preceding client requests.
Different approaches to maintain a session between client and server are:
1. Cookies: Cookies are text files that allow programmers to store some information on a client
computer, and they are kept for usage tracking purposes.
2. 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.
This session object has different session methods to manage data within the session scope.
Here is an example of a JSP request and session implicit objects where a user submits login
information, and another JSP page receives it for processing:
Example (HTML file):
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form action="login.jsp">
</form>
</body>
</html>
Example (login.jsp):
<%@ page import = " java.util.* " %>
<%
Advanced Java
String username = request.getParameter("u_name");
if(username.equals("admin")){
session.setAttribute("u_name",username);
response.sendRedirect("home.jsp");
}else{
out.print("Invalid Username");
%>
Example (home.jsp):
<%
out.print("Hi "+session_u_name);
%>
1. public Object getAttribute(String name): is used for returning the object bound with the
that will hold the names of all the objects to this session.
3. public long getCreationTime(): is used for returning the time when the session was created right
your session.
5. public long getLastAccessedTime(): is used for returning the latest time your client sent a
6. public int getMaxInactiveInterval(): is used for returning the highest time interval (in seconds),
which has to be maintained by the servlet container as a session gets opened between client
accesses.
7. public void invalidate(): is used for invalidating a session and unbinds its objects bound to it.
8. public boolean isNew(): is used for returning a true when the client does not know anything
about the session or when the client chooses not to join the session.
9. public void removeAttribute(String name): is used for removing the object bound specifically to
a session.
10. public void setAttribute(String name, Object value): is used for binding an object to your
11. public void setMaxInactiveInterval(int interval): is used for specifying the time (in seconds)
between client requests where the servlet container will nullify this session.
create-table.jsp
pageEncoding="ISO-8859-1"%>
<html>
<head>
</head>
<body>
<%
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
statement.executeUpdate(query);
catch (Exception e)
Advanced Java
{
%>
</body>
</html>
For insert data in MySQL using JSP first we have to create a table in data base.
The INSERT INTO statement is used to insert new data to a MySQL table:
SQL Query
first_name varchar(50),
last_name varchar(50),
city_name varchar(50),
email varchar(50),
index.html
<!DOCTYPE html>
<html>
<body>
First name:<br>
<br>
Last name:<br>
<br>
City name:<br>
<br>
Email Id:<br>
<br><br>
</form>
Advanced Java
</body>
</html>
process.jsp
pageEncoding="ISO-8859-1"%>
<%@page import="java.sql.*,java.util.*"%>
<%
String first_name=request.getParameter("first_name");
String last_name=request.getParameter("last_name");
String city_name=request.getParameter("city_name");
String email=request.getParameter("email");
try
Class.forName("com.mysql.jdbc.Driver");
Statement st=conn.createStatement();
catch(Exception e)
Advanced Java
{
System.out.print(e);
e.printStackTrace();
%>
Output
First name:
Last name:
City name:
Email Id:
For retrieve data from MySQL database using JSP first we have to create a table in data base.
After create a table in the MySQL database you need to insert record or data on it.If you want to
know how to insert data in jsp please visit the link : Insert data in JSP.
Advanced Java
The SELECT statement is used to retrieve data from one or more tables:
retrieve.jsp
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.Connection"%>
<%
String id = request.getParameter("userid");
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
%>
<!DOCTYPE html>
<html>
<body>
<table border="1">
<tr>
<td>first name</td>
<td>last name</td>
<td>City name</td>
<td>Email</td>
Advanced Java
</tr>
<%
try{
statement=connection.createStatement();
resultSet = statement.executeQuery(sql);
while(resultSet.next()){
%>
<tr>
<td><%=resultSet.getString("first_name") %></td>
<td><%=resultSet.getString("last_name") %></td>
<td><%=resultSet.getString("city_name") %></td>
<td><%=resultSet.getString("email") %></td>
</tr>
<%
connection.close();
} catch (Exception e) {
e.printStackTrace();
%>
</table>
</body>
Advanced Java
</html>
After retrieve the data from the data base the table look like this.
In this example we will discuss about how to delete a record or data from MySQL database using
JSP.
Notice : The WHERE clause specifies which record or records that should be deleted. If you omit the
WHERE clause, all records will be deleted!
The following examples delete the record with id=3 in the "users" table:
To delete a record from table you must have insert data.If you want to know how to insert data in
jsp please visit : Insert data in JSP.
index.jsp
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.Connection"%>
<%
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
%>
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<body>
<table border="1">
<tr>
<td>first name</td>
<td>last name</td>
<td>City name</td>
<td>Email</td>
<td>Action</td>
</tr>
<%
try{
statement=connection.createStatement();
resultSet = statement.executeQuery(sql);
int i=0;
while(resultSet.next()){
Advanced Java
%>
<tr>
<td><%=resultSet.getString("fname") %></td>
<td><%=resultSet.getString("lname") %></td>
<td><%=resultSet.getString("city_name") %></td>
<td><%=resultSet.getString("email") %></td>
</tr>
<%
i++;
connection.close();
} catch (Exception e) {
e.printStackTrace();
%>
</table>
</body>
</html>
delete.jsp
<%@page import="java.sql.*,java.util.*"%>
<%
Advanced Java
String id=request.getParameter("id");
try
Class.forName("com.mysql.jdbc.Driver");
Statement st=conn.createStatement();
catch(Exception e)
System.out.print(e);
e.printStackTrace();
%>
After delete the id=3 record from the table the table is now