[go: up one dir, main page]

0% found this document useful (0 votes)
15 views29 pages

Module 5

JavaServer Pages (JSP) is a server-side technology that enables the creation of dynamic web pages by embedding Java code within HTML. The document outlines the JSP architecture, request processing steps, and details about JSP implicit objects such as request, response, out, session, and config. It also includes examples of how to use these implicit objects in JSP code to manage user sessions and handle requests and responses.

Uploaded by

SyedaFatima
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views29 pages

Module 5

JavaServer Pages (JSP) is a server-side technology that enables the creation of dynamic web pages by embedding Java code within HTML. The document outlines the JSP architecture, request processing steps, and details about JSP implicit objects such as request, response, out, session, and config. It also includes examples of how to use these implicit objects in JSP code to manage user sessions and handle requests and responses.

Uploaded by

SyedaFatima
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 29

MODULE-5:

JavaServer Pages (JSP)


JSP Architecture:
JSP (JavaServer Pages) is a technology used for creating dynamic web pages using Java. It
allows embedding Java code inside HTML to generate dynamic content. JSP is an extension
of Servlets, making it easier to develop web applications by separating business logic from
presentation.

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.

JSP Request Processing Diagram


Client (Browser)
|
V
Web Server
|
V
JSP Container
|
V
JSP → Compiled into Servlet
|
V
Servlet executes & generates response
|
V
Sends response to Client

2. JSP Standard / Implicit Objects

<%@ page language = "java" contentType = "text/html; charset = UTF-8"


pageEncoding = "UTF-8"%>
<!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 = UTF-8">
<title>Insert title here</title>
</head>
<body>

<!-- Here we are going to insert our Java code-->

<% Geeks saying hello to JSP %>


</body>
</html>

Implicit objects are a set of Java objects that the JSP Container makes available to
developers on each page. These objects may be accessed as built-in variables via scripting
elements and can also be accessed programmatically by JavaBeans and Servlets. JSP
provides implicit objects, which are automatically available in JSP pages without needing to
be declared.

JSP provide you Total 9 implicit objects which are as follows


1. request: This is the object of HttpServletRequest class associated with the request.
2. response: This is the object of HttpServletResponse class associated with the response
to the client.
3. config: This is the object of ServletConfig class associated with the page.
4. application: This is the object of ServletContext class associated with the application
context.
5. session: This is the object of HttpSession class associated with the request.
6. page context: This is the object of PageContext class that encapsulates the use of
server-specific features. This object can be used to find, get or remove an attribute.
7. page object: The manner we use the keyword this for current object, page object is used
to refer to the current translated servlet class.
8. exception: The exception object represents all errors and exceptions which is accessed
by the respective jsp. The exception implicit object is of type java.lang.Throwable.
9. out: This is the PrintWriter object where methods like print and println help for
displaying the content to the client.

3. Explanation of JSP Implicit Objects

1. request Object
 Retrieves client request data such as form parameters, headers, and cookies.
 Example: Getting form input from a text field.
 The JSP request is an implicit object which is provided by HttpServletRequest. In
the servlet, we have to first import javax.servlet.http.HttpServletRequest then we
have to create its object for taking input from any HTML form as.
Syntax :
import javax.servlet.http.HttpServletRequest;

public class LoginServlet extends HttpServlet


{
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
HttpSession session = request.getSession()
}
}

In JSP, the request object is implicitly defined so that you don’t have to create an
object. JSP request object is created by the web container for each request of the
client. It’s used for getting the parameter value, server name, server port, etc.

<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action = "Geeks.jsp">
<input type = "text" name = "username">
<input type = "submit" value = "submit"><br/>
</form>
</body>
</html>

OUTPUT:

2.response Object
 This is the HttpServletResponse object associated with the response to the client.
The response object also defines the interfaces that deal with creating new HTTP
headers. Through this object the JSP programmer can add new cookies or date
stamps, HTTP status codes, etc.
 Sends response back to the client (redirects, setting headers, etc.).
 Example: Redirecting to another page.

<%@ page language="java" contentType="text/html; charset=UTF-8"


pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
String name=request.getParameter("username");
out.print("Welcome "+ name);
%>
</body>
</html>

In JSP the response object is implicitly defined, so you don’t have to create an object. JSP
response object is created by the web container for each request of the client. It basically is
used for redirecting to any other resource.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>GeeksforGeeks</title>
</head>
<body>
<%
//below line in JSP redirect you to geeksforgeeks page
response.sendRedirect("geeksforgeeks.org");
%>
</body>
</html>

OUTPUT:

3.out Object
 The Out implicit object in the JSP can provide a way to send the content to the
response stream which is then rendered on the web page. It is mainly used to display the
dynamic content generated by the JPS codes. Sends output to the client. Example:
Displaying dynamic content

Steps to Use Out Implicit Object:


 We can access the Out implicit object within the JSP Code.
 Use methods like print( ) or println() to send the content to the response stream.
 Then the content can be sent using Out and is directly rendered on the web page when
the response is sent to the client.

Using Out.print() method:


The print() method can be used to the Out implicit objects sends content to the response
stream without appending the new line character.
Example:
<%
// Using Out.print() to send content
out.print("This is printed using Out.print(). ");
out.print("No new line character is appended.");
%>

Using Out.println() method:


The println() method can be used to the Out implicit object sends content to the response
stream and it can append the new line character after the content.

Example:
<body>
<%
// Using Out.println() to send content
out.println("This is printed using Out.println().");
out.println("A new line character is appended after each println() call.");
%>

Flushing the Output:


Flushing can be used to the output ensures that the content can sent using Out is
immediately sent to client's browser instead of waiting for the buffer to be filled.

Example:

<%
//Using Out.println() to send content
out.println("This content is flushed immediately.");

//Flush the output to ensure it's sent immediately


out.flush();
%>
Directives to Control Output:
JSP directives like <% page buffer = "none" %> can be used to the control of buffering
behavior and it can affecting how the content sent using the Out is handled.
Example:

<%
// Send content using Out implicit object
out.println("This content is not buffered because buffer=\"none\" directive is used.");
%>

Example to demonstrate the implementation of Out Implicit Object of JSP:


<%@ page language="java" contentType="text/html; charset=UTF-
8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Out Implicit Object Example</title>
</head>
<body>
<%
// Using Out.print() method
out.print("Hello, this is printed using
Out.print()<br>");

// Using Out.println() method


out.println("This is printed using Out.println()");
%>
</body>
</html>
Output:
Hello, this is printed using Out.print()
This is printed using Out.println()

4.session Object
 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.
 Manages user session across multiple pages.
 Example: Storing and retrieving session data.

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.
Boolean value (true or false) is returned by it. Primarily it used to trace either the
cookies are enabled on client side or not. If cookies are not enabled then
the session.isNew() method should return true all the time.
 Method 2: getId(): While creating a session, the servlet container allots a distinctive
string identifier to the session. This distinctive string identifier is returned
by getId method.
 Method 3: getAttributeNames(): All the objects stored in the session are returned
by getAttributeNames method. Fundamentally, this method results in an
enumeration of objects.
 Method 4: getCreationTime(): The session creation time (the time when the session
became active or the session began) is returned by getCreationTime method.
 Method 5: getAttribute(String name): Using getAttribute method, the object which
is stored by the setAttribute() method is retrieved from the session. For example, We
need to store the “userid” in session using the setAttribute() method if there is the
requirement of accessing userid on every jsp page until the session is active and
when needed it can be accessed using the getAttribute() method.
 Method 6: setAttribute(String, object): The setAttribute method is used to store an
object in session by allotting a unique string to the object. Later, By using the same
string this object can be accessed from the session until the session is active. In JSP,
while dealing with session setAttribute() and getAttribute() are the two most
regularly used methods.
 Method 7: getMaxInactiveInterval(): The getMaxInactiveInterval return session’s
maximum inactivates time interval in seconds.
 Method 8: getLastAccessedTime: The getLastAccessedTime method is mostly used
to notice the last accessed time of a session.
 Method 9: removeAttribute(String name): Using removeAttribute(String
name) method, the objects that are stored in the session can be removed from the
session.
 Method 10: invalidate(): The invalidate() method ends a session and breaks the
connection of the session with all the stored objects.
Example: index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>

The name which is entered by user in the index page is displayed on the welcome.jsp page
and it saves the same variable in the session object so that it can be retrieved on any page
till the session becomes inactive.

Welcome.jsp:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<%
String name=request.getParameter("uname");
out.print("Welcome "+name);
session.setAttribute("user",name);
%>

<a href="second.jsp">Display the value</a>

</body>
</html>

In second.jsp page, the value of variable is retrieved from the session and displayed.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>Display the session value on this page</h1>
<%
String name=(String)session.getAttribute("user");
out.print("Hello "+name);
%>
</body>
</html>
OUTPUT:
5. config Object:
 JSP Config is an implicit object which is used to transmit the configuration details
to the JSP page. In JSP, Config is an instance of type ServletConfig.
 This implicit object is used to acquire an initialization parameter for a certain JSP
page. For each JSP page, the config object is generated through the web container.
 JSP’s config object carries the configuration pieces of information like the
username, password, driver name, servlet name, servlet context, specification
names, and their values settle in the web.xml (configuration file).
 It is an object of type javax. servlet.ServletConfig interface.Through web.xml file
the detail is send to JSP file. To fetch this detail the Config object is used. Normally,
it is used extensively for the initialization parameters like as the paths or file
locations from the web.xml file.
 JSP Config object has scope only up to a single JSP page.
 Methods of ServletConfig interface are listed alongside the action performed from
the below table as follows:

Index.Html:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="welcome">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>

Web.xml:

<?xml version="1.0" encoding="UTF-8"?>


<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
id="WebApp_ID" version="4.0">
<display-name>HelloWorld</display-name>
<servlet>
<servlet-name>welcome</servlet-name>
<jsp-file>/welcome.jsp</jsp-file>

<init-param>
<param-name>dname</param-name>
<param-value>com.mysql.jdbc.Driver</param-value>
</init-param>

</servlet>

<servlet-mapping>
<servlet-name>welcome</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>

<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>

Welcome.JSP:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>GeeksforGeeks</title>
</head>
<body>

<%
out.print("Welcome "+request.getParameter("uname"));
String driver=config.getInitParameter("dname");
out.print("<br/>driver name is="+driver);
%>

</body>
</html>

OUTPUT:
6. application Object

 In JSP, application is an implicit object of type ServletContext. This is an instance


of javax.servlet.ServletContext. It is generated onetime by the web container when
web application or web project is deployed on server.
 This object is used to acquire the initialization parameter from the configuration file
(web.xml). It is used for allotting the attributes and the values of the attributes over
all JSP page. This indicates that any attribute which is set by application object will
be accessible to all the JSP pages. In the application scope, it is also used to get, set,
and remove attribute.
 JSP application implicit object has scope in all jsp pages.

 Methods of Application implicit object


 void setAttribute(String attributeName, Object object) : It saves an attribute
and its value in application context that is available to use over JSP application. For
instance :
 application.setAttribute(“Attribute”, “value of Attribute”);
 The statement which is given above should have saved the attribute and its value.
 Object getAttribute(String attributeName) : It gives back the object which is
saved in a given attribute name. For instance, Lets have a look to the statement
given in the above example. Now, what will be the value of ‘s’ if the below
statement is used in any of the JSP page?
 String s= (String) application.getAttribute(“Attribute”);
 The value of ‘s’ will be “value of Attribute” after all we have put it with the help of
setAttribute method and this value here is obtained using the getAttribute method.
 void removeAttribute(String objectName) : For eliminating the given attribute
from the application, This method is used. For instance : It will withdraw the
Attribute “Attribute” from the application. If we attempt to retrieve the value of a
withdrawn attribute with the help of getAttribute method then it will give back Null.
 application.removeAttribute(“Attribute”);
 Enumeration getAttributeNames() : This method gives back the enumeration of
all attribute names which are saved in the application object.
 Enumeration e = application.getAttributeNames();
 String getInitParameter(String paramname) : For a given parameter name, it
gives back the value of Initialization parameter. Example : web.xml
 Stores data globally across all JSP pages.
 Example: Setting and retrieving global data.

<web-app>

<context-param>
<param-name>parameter</param-name>
<param-value>ValueOfParameter</param-value>
</context-param>
</web-app>

String s=application.getInitParameter("parameter");
The value of ‘s’ will be “ValueOfParameter” which is given in the param-value tag in the
configuration file (web.xml).
Enumeration getInitParameterNames() : The enumeration of all Initialization parameters
is given by this method.
Enumeration e= application.getinitParameterNames();
String getRealPath(String value) : In the file system, it transforms a path given to a
complete path.

String abspath = application.getRealPath(“/index.html”);


Based on the actual file system, the value of abspath will be an absolute http URL.
void log(String message) : This method sets down the given content to the JSP container’s
default log file which is related to the application.
application.log(“Error 404, Page not found”);
To the default log file, the call above will writes the message “Error 404, Page not found”.
String getServerInfo() : This method gives back the name and version of JSP container.
application.getServerInfo();

Example:

Index.HTML

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<form action="welcome">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>

</body>
</html>
Web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<display-name>HelloWorld</display-name>

<servlet>
<servlet-name>welcome</servlet-name>
<jsp-file>/welcome.jsp</jsp-file>

</servlet>

<servlet-mapping>
<servlet-name>welcome</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
<context-param>
<param-name>dname</param-name>
<param-value>com.mysql.jdbc.Driver</param-value>
</context-param>

</web-app>

Welcome.jsp:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>GeeksforGeeks</title>
</head>
<body>

<%
out.print("Welcome "+request.getParameter("uname"));
String driver=application.getInitParameter("dname");
out.print("<br/>driver name is="+driver);
%>

</body>
</html>
OUTPUT:
7. pageContext Object

PageContext extends JspContext to contribute helpful context details while JSP


technology is applied in a Servlet environment. A PageContext is an instance that gives
access to all the namespaces related to a JSP page, gives access to some page attributes and
a layer over the application details. Implicit objects are connected to the pageContext
consequently.

 The PageContext class is an abstract class that is formed to be extended to give


application-dependent applications whereof by compatible JSP engine runtime
environments. In JSP, pageContext is an instance of javax.servlet.jsp.PageContext.
 The entire JSP page is represented by the PageContext object. This object is considered
as a method to obtain detail about the page while keeping away from most of the
execution information.
 For each request, the credentials to the response and request objects are saved by this
pageContext object. By accessing attributes of the pageContext object, the out, session,
config, and application objects are obtained.
 This pageContext object further holds information regarding the directives provided to
the JSP page, together with the page scope, buffering information, and the
errorPageURL.
 By using the pageContext object you can set attributes, get attributes and remove
attributes that are present in the different scopes like as page, request, session,
and application scopes which are given below as follows:
 page – Scope: PAGE_CONTEXT
 request – Scope: REQUEST_CONTEXT
 session – Scope: SESSION_CONTEXT
 application – Scope: APPLICATION_CONTEXT

Syntax:
public abstract class PageContext
extends JspContext

Syntax: To use pageContext


pageContext.methodName(“name of attribute”, “scope”);

Method 1: getAttribute (String AttributeName, int Scope)


The getAttribute method finds an attribute in the described scope. For example, the
statement given below the getAttribute method finds the attribute “GeeksforGeeks” in the
scope of Session (Session layer). If it finds the attribute then it will assign the attribute to
Object obj otherwise it will return Null.
Syntax:
Object obj = pageContext.getAttribute("GeeksforGeeks",
PageContext.SESSION_CONTEXT);
Correspondingly, this method can be used for more other scopes also, like as follows:
 Object obj = pageContext.getAttribute(“GeeksforGeeks”, PageContext.
REQUEST_CONTEXT);
 Object obj = pageContext.getAttribute(“GeeksforGeeks”, PageContext.
PAGE_CONTEXT);
 Object obj = pageContext.getAttribute(“GeeksforGeeks”, PageContext.
APPLICATION_CONTEXT);
Method 2: findAttribute (String AttributeName)
The findAttribute() method finds the described attribute in all four levels in the following
order listed below. At any level, if no attribute is found then it will return NULL.
Page --> Request --> Session and Application
Method 3: void setAttribute(String AttributeName, Object AttributeValue, int Scope)
This method sets down an attribute in a given scope. For example, consider the statement
given below will save an Attribute “data” in the scope of application with the value “This is
data”.
Syntax:
pageContext.setAttribute(“data”, “This is data”, PageContext.
APPLICATION_CONTEXT);
Correspondingly, this method will design an attribute named attr1 in the scope of Request
with the value “Attr1 value” is as follows:
pageContext.setAttribute(“attr1”, “Attr1 value”, PageContext. REQUEST_CONTEXT);
Method 4: void removeAttribute(String AttributeName, int Scope)
In order to remove an attribute from a given scope, this method is used. For example,
consider the JSP statement given below will remove an Attribute “Attr” from page scope.
Syntax:
pageContext.removeAttribute(“Attr”, PageContext. PAGE_CONTEXT);

 Provides access to JSP implicit objects.


 Example: Setting an attribute at page level.

Index.html:

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>GeeksforGeeks</title>
</head>
<body>

<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>

</body>
</html>

Welcome.jsp:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<%

String name=request.getParameter("uname");
out.print("Welcome "+name);

pageContext.setAttribute("user",name,PageContext.SESSION_SCOPE);

%>
<a href="second.jsp">second jsp page</a>

</body>
</html>

Second.jsp:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<%

String name=(String)pageContext.getAttribute("user",PageContext.SESSION_SCOPE);
out.print("Hello "+name);

%>

</body>
</html>
8. page Object:
 This object is an actual reference to the instance of the page. It can be thought of as an
object that represents the entire JSP page.
 The page object is really a direct synonym for the this object.

9. exception Object
The Exception implicit object in the JSP provides information about any exception that
occurs during the execution of the JSP pages.
The Exception implicit object in the JSP provides information about any exception that can
occur during the execution of the JSP page. It enables the developers to handle the
exceptions gracefully and provide meaningful error messages to the users.
Developers can effectively handle the exceptions and ensure a smoother user experience in
the JSP applications.
Steps to Use Exception Implicit Object
 It can enclose the JSP code that might throw an exception within the try-catch block.
 Catch the exception and obtain the exception implicit object.
 Extract the relevant information such as exception type, message, and stack trace.
 Display the appropriate error message or handle the exception as required.
Subtopics:
 Accessing the Exception information: Developer can access the information such as
the exception type, message and the stack trace from the Exception implicit object.
 Displaying the Custom Error Messages: Exception handling in the JSP allows the
developers to display the custom error messages or the redirect users to error pages
based on the type of exception.
 Nested Exception Handing: It can be nested try-catch blocks and can be used to
handles the exceptions at the different levels of the JSP page and it can provide the
granular control over the error handling.
Program to Implement Exception Implicit Object of JSP:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-


8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Exception Implicit Object Example</title>
</head>
<body>
<%
try {
// Attempting division by zero to trigger an exception
int result = 10 / 0;
out.println("Result: " + result);
} catch (Exception e) {
// Handling the exception and accessing exception information
out.println("<h2>Error Details:</h2>");
out.println("<p><b>Exception Type:</b> " + e.getClass().getName() + "</p>");
out.println("<p><b>Message:</b> " + e.getMessage() + "</p>");
out.println("<p><b>Stack Trace:</b></p>");
out.println("<pre>");
e.printStackTrace(new java.io.PrintWriter(out));
out.println("</pre>");
}
%>
</body>
</html>
 The above code demonstrates the usage of the exception implicit object to handle
runtime exceptions.
 Inside the try-catch block, it attempts a division by zero to trigger an exception.
 Upon catching the exception, it prints detailed error information including the exception
type, message, and stack trace to the web page

OUTPUT:

4. JavaBeans:
INTRODUCTION TO JAVA BEANS :
Software components are self-contained software units developed according to the motto
“Developed them once, run and reused them everywhere”. Or in other words, reusability is
the main concern behind the component model. A software component is a reusable object
that can be plugged into any target software application. You can develop software
components using various programming languages, such as C, C++, Java, and Visual Basic.
A “Bean” is a reusable software component model based on sun’s java bean specification that
can be manipulated visually in a builder tool. The term software component model describe
how to create and use reusable software components to build an application Builder tool is
nothing but an application development tool which lets you both to create new beans or use
existing beans to create an application. To enrich the software systems by adopting
component technology JAVA came up with the concept called Java Beans. Java provides the
facility of creating some user defined components by means of Bean programming. We
create simple components using java beans. We can directly embed these beans into the
software.
Advantages of Java Beans: The java beans posses the property of “Write once and run
anywhere”. Beans can work in different local platforms. Beans have the capability of
capturing the events sent by other objects and vice versa enabling object communication.
The properties, events and methods of the bean can be controlled by the application
developer.(ex. Add new properties) Beans can be configured with the help of auxiliary
software during design time.(no hassle at runtime) The configuration setting can be made
persistent.(reused) Configuration setting of a bean can be saved in persistent storage and
restored later. What can we do/create by using JavaBean: There is no restriction on the
capability of a Bean. It may perform a simple function, such as checking the spelling of a
document, or a complex function, such as forecasting the performance of a stock portfolio. A
Bean may be visible to an end user. One example of this is a button on a graphical user
interface. Software to generate a pie chart from a set of data points is an example of a Bean
that can execute locally. Bean that provides real-time price information from a stock or
commodities exchange. Definition of a builder tool: Builder tools allow a developer to
work with JavaBeans in a convenient way. By examining a JavaBean by a process known as
Introspection, a builder tool exposes the discovered features of the JavaBean for visual
manipulation. A builder tool maintains a list of all JavaBeans available. It allows you to
compose the Bean into applets, application, servlets and composite components (e.g. a
JFrame), customize its behavior and appearance by modifying its properties and connect
other components to the event of the Bean or vice versa.

JavaBeans basic rules A JavaBean should: be public implement the Serializable interface
have a no-arg constructor be derived from javax.swing.JComponent or java.awt.Component
if it is visual The classes and interfaces defined in the java.beans package enable you to
create JavaBeans. The Java Bean components can exist in one of the following three phases
of development: • Construction phase • Build phase • Execution phase It supports the
standard component architecture features of Properties Events Methods Persistence. In
addition Java Beans provides support for Introspection (Allows Automatic Analysis of a java
beans) Customization(To make it easy to configure a java beans component) Elements of a
JavaBean: Properties Similar to instance variables. A bean property is a named attribute of a
bean that can affect its behavior or appearance. Examples of bean properties include color,
label, font, font size, and display size. Methods Same as normal Java methods. Every
property should have accessor (get) and mutator (set) method. All Public methods can be
identified by the introspection mechanism. There is no specific naming standard for these
methods.

The JavaBean Component Specification: Customization: Is the ability of JavaBean to allow


its properties to be changed in build and execution phase. Persistence:- Is the ability of
JavaBean to save its state to disk or storage device and restore the saved state when the
JavaBean is reloaded. Communication:-Is the ability of JavaBean to notify change in its
properties to other JavaBeans or the container. Introspection:- Is the ability of a JavaBean to
allow an external application to query the properties, methods, and events supported by it.
Services of JavaBean Components Builder support:- Enables you to create and group
multiple JavaBeans in an application. Layout:- Allows multiple JavaBeans to be arranged in a
development environment. Interface publishing: Enables multiple JavaBeans in an
application to communicate with each other. Event handling:- Refers to firing and handling of
events associated with a JavaBean. Persistence:- Enables you to save the last state of
JavaBean. Features of a JavaBean Support for “introspection” so that a builder tool can
analyze how a bean works. Support for “customization” to allow the customisation of the
appearance and behaviour of a bean. Support for “events” as a simple communication
metaphor than can be used to connect up beans. Support for “properties”, both for
customization and for programmatic use. Support for “persistence”, so that a bean can save
and restore its customized state.

JavaBeans are reusable software components in Java that follow a standard architecture for
encapsulating data.

4.1 JavaBean Architecture

JavaBeans follow a three-tier architecture:

1. Presentation Layer – JSP/Servlets interact with users.


2. Business Logic Layer – JavaBeans process business rules.
3. Data Layer – Databases store and retrieve data.

JavaBeans Architecture Diagram

Client (Browser)
|
V
JSP/Servlet (View Layer)
|
V
JavaBean (Business Logic Layer)
|
V
Database (Data Layer)

4.2 JavaBean Characteristics

A JavaBean must follow these rules:

1. Encapsulation: Use private fields with public getter/setter methods.


2. Default Constructor: Must have a public no-argument constructor.
3. Serializable: Implements java.io.Serializable to allow object persistence.
4. No Public Fields: Fields must be accessed using getter and setter methods.
4.3 Providing Properties and Methods in JavaBeans

4.3.1 Properties in JavaBeans

 Properties represent data fields that can be accessed via getters and setters.

Example: JavaBean Class with Properties

java
CopyEdit
import java.io.Serializable;

public class UserBean implements Serializable {


private String name;
private int age;

// Default Constructor
public UserBean() {}

// Getter and Setter for name


public String getName() { return name; }
public void setName(String name) { this.name = name; }

// Getter and Setter for age


public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
}

4.3.2 Methods in JavaBeans

 JavaBeans may include methods to process data.

Example: Adding a method

public String getUserDetails() {


return "Name: " + name + ", Age: " + age;
}

4.4 Using JavaBeans in JSP

JSP provides the <jsp:useBean> tag to create and access JavaBeans.

Example: Using JavaBean in JSP


jsp
CopyEdit
<jsp:useBean id="user" class="UserBean" scope="session"/>
<jsp:setProperty name="user" property="name" value="John"/>
<jsp:setProperty name="user" property="age" value="25"/>

User Details: <jsp:getProperty name="user" property="name"/> (Age:


<jsp:getProperty name="user" property="age"/>)

You might also like