0% found this document useful (0 votes)
13 views11 pages

Unit 3 - Chp2

JavaServer Pages (JSP) is a technology for creating interactive web pages by embedding Java code within HTML. It offers advantages over servlets, such as easier maintenance, faster development, and reduced code complexity. JSP pages undergo a life cycle involving translation into servlets, compilation, and execution, allowing for dynamic content generation and interaction with databases.
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)
13 views11 pages

Unit 3 - Chp2

JavaServer Pages (JSP) is a technology for creating interactive web pages by embedding Java code within HTML. It offers advantages over servlets, such as easier maintenance, faster development, and reduced code complexity. JSP pages undergo a life cycle involving translation into servlets, compilation, and execution, allowing for dynamic content generation and interaction with databases.
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/ 11

Q.

1
Introduction to JavaServer Pages (JSP)

JavaServer Pages (JSP) is a technology for building interactive web pages. It was created by Sun Microsystems and is
an advanced version of Java servlets. JSP makes it easier to develop web pages and is useful for many applications.
Like most server-side technologies, JSP separates the business logic (how the website works) from the presentation
layer (how the website looks).

JSP pages are just like normal HTML pages but with Java code inside them. To use JSP, developers need a special
engine (JSP engine) connected to a web server. The JSP engine turns the JSP page into a servlet, which the servlet
engine processes. This process is called "translation." The servlet then runs, creating dynamic HTML content that
gets sent to the browser. The JSP page is converted to a servlet the first time it is requested, and it stays that way
unless changes are made to the JSP file. JSP can also work with Java DataBase Connectivity (JDBC) to create dynamic,
database-driven websites.

Why Use JavaServer Pages (JSP)?

Advantages of JSP Over Servlets:

 Extension of Servlet Technology: JSP builds on servlet technology. It can use all the features of servlets and
adds more, like implicit objects, predefined tags, expression language (EL), and custom tags, making JSP
easier to develop.

 Easy to Maintain: In JSP, the business logic and presentation (how the website looks) are separate. This
makes it easier to manage compared to servlets, where both are mixed together.

 Fast Development: If you modify a JSP page, there's no need to recompile and redeploy the project. In
contrast, with servlets, you need to update and recompile the code whenever you want to change the look
of the application.

 Less Code: JSP allows you to use tags like action tags, JavaServer Pages Standard Tag Library (JSTL), custom
tags, and implicit objects, which reduces the amount of code you need to write. It also uses Java's "write
once, run anywhere" advantage.

 Simplified Syntax: JSP uses a simpler scripting language to embed HTML, making it easier to work with.

Q.2

Advantages of JSP Over Other Technologies (Not Servlets)

 Compared to Active Server Pages (ASP): ASP, created by Microsoft, is also a tag-based programming
language, but ASP code isn't portable. This means you can't easily move it to different platforms. On the
other hand, JSP is portable because it's written in Java, which works across different platforms. With JSP,
you're not tied to any specific server or IIS (Internet Information Services).

 Compared to PHP: PHP is an open-source scripting language, just like Java. It is similar to JSP and ASP but
isn't ideal for large-scale applications or banking apps that involve financial transactions due to security
concerns. Also, PHP requires learning a new language, while JSP lets you work with Java, which you may
already know.
 Compared to JavaScript: JavaScript has no connection to Java programming. It's mostly used to create
dynamic HTML on the client side (in the browser). However, JavaScript is not suitable for tasks like network
programming or accessing server resources. Java (used in JSP) is much more powerful, flexible, reliable, and
portable than JavaScript.

 Compared to HTML: Regular HTML is static, meaning it can't react to user input or handle dynamic content.
It also doesn't interact with server-side resources. JSP can handle both static (HTML) and dynamic content,
making it more versatile than plain HTML.

Q.3

Q.4

Life Cycle of a JSP Page

A JSP page doesn't directly send content to the browser. Instead, it goes through several steps on the server. The JSP
page is first translated into a Java class (called a servlet) which then handles all requests made to the JSP.

Here are the steps in the JSP life cycle:


1. JSP Page Translation: The JSP file is converted into a Java servlet file. This is the first step in the life cycle.
During this translation, the server checks the JSP code for errors. It processes the standard directives,
actions, and any custom tag libraries used in the page.

2. JSP Page Compilation: After translation, the Java servlet file is compiled into a servlet class (Java bytecode).
This step can happen either when the JSP page is first deployed or when a client requests the page for the
first time.

3. Class Loading: The servlet class created from the JSP file is loaded into the server's memory.

4. Execution Phase: The server creates one or more instances of the servlet class when a request is made to
the JSP page. Two important methods (jspInit() and jspDestroy()) are defined in the interface called JspPage,
which helps manage the JSP life cycle. For pages handling HTTP requests, the jspService() method handles
the requests.

5. Initialization: The jspInit() method is called right after the servlet instance is created. This happens only once
in the JSP life cycle.

6. jspService() Execution: This method is called every time a request is made to the JSP page during its life
cycle. It passes the request and response objects to handle the request. You cannot override the jspService()
method.

7. jspDestroy() Execution: This method is called when the JSP page is about to be destroyed. After this, the
servlet completes its job and gets cleaned up by the garbage collector, marking the end of the JSP life cycle.

Q.5

How Does a JSP Page Function?

To run JSP pages, the web server requires a JSP engine (also called a container). This container is responsible for
handling all requests made for JSP pages.

The JSP container works with the web server to provide the necessary environment and services for JSP to run. It
understands and processes the special JSP elements (like tags and Java code) embedded in the page.

Here’s a simplified view of how it works:

 The web server handles requests for regular HTML pages.

 When it encounters a JSP page, the web server passes the request to the JSP handler.

 The JSP handler processes the JSP tags and Java code in the page.

 The Java compiler converts this code into a Java class (a servlet).

 The Java runtime then runs this servlet, which generates the final HTML content to be sent back to the
user’s browser.

In short, the JSP container ensures that JSP pages are properly processed and converted into dynamic web content
that can be displayed in the browser.

How Does JSP Execute?

Here’s a simple explanation of how a JSP page works step by step:

1. Browser Request: Your browser sends an HTTP request to the web server, just like it does for a regular
webpage.
2. Web Server Detection: The web server sees that the request is for a JSP page (because the file ends with .jsp
instead of .html) and sends the request to the JSP engine.

3. JSP to Servlet Conversion: The JSP engine loads the JSP page from the server’s disk and converts it into a
servlet. This process is simple: any regular text (like HTML) is turned into println() statements, and JSP
elements (Java code) are transformed into Java code that handles the dynamic content of the page.

4. Servlet Compilation: The JSP engine compiles this Java code into an executable servlet class and sends the
request to the servlet engine.

5. Servlet Execution: The servlet engine, a part of the web server, loads the compiled servlet class and runs it.
During this process, the servlet generates HTML output.

6. Sending HTML to Browser: The servlet engine sends the generated HTML back to the web server, which
forwards it to your browser as an HTTP response.

7. Browser Display: The browser receives this dynamically generated HTML and displays it, just like a normal
webpage.

Additionally, the JSP engine checks whether a servlet for the JSP page has already been created. If the JSP file hasn’t
changed, the engine reuses the existing servlet, making the process more efficient and faster than some other
scripting languages like PHP

1. Explain the coding styles of JSP page


From Tb
2. What are directives in JSP? Explain its types
JSP Directives
JSP directives provide instructions to the JSP container, controlling how the JSP page is processed. They are used
to set global properties and behavior for the JSP page.
Types of JSP Directives:
1. Page Directive:
o Defines attributes that apply to the entire JSP page.
o Syntax: <%@ page attribute="value" %>
o Common attributes:
 language: Specifies the programming language used (default is java).
 extends: Specifies a superclass for the generated servlet.
 import: Imports Java classes/packages for use in the JSP.
 session: Indicates if the page uses HTTP sessions (true or false).
 buffer: Sets the buffer size for output (e.g., none, 8kb).
 autoFlush: Controls if the buffer is flushed automatically (true or false).
 contentType: Defines the MIME type and character set (e.g., text/html, UTF-8).
 errorPage: Specifies a page to handle exceptions.
 isErrorPage: Indicates if this page is an error page.
 isThreadSafe: Defines whether the JSP page is thread-safe (true or false).
 pageEncoding: Specifies the character encoding for the JSP.
 isELIgnored: Specifies whether Expression Language (EL) is ignored (true or false).
2. Include Directive:
o Used to include static resources (such as headers, footers, or common HTML content) during the
translation phase.
o Syntax: <%@ include file="filename.jsp" %>
o Key points:
 Includes the content of another file at the time of page translation.
 Commonly used for reusable components like navigation bars, footers, etc.
 If the included file changes, the main JSP page needs to be recompiled to reflect changes.
3. Taglib Directive:
o Declares a tag library for use within the JSP.
o Syntax: <%@ taglib uri="URI" prefix="prefix" %>
o Key points:
 Allows the use of custom tags defined in the tag library.
 The uri attribute identifies the location of the tag library.
 The prefix attribute provides a short name for referencing the custom tags in the JSP.
 Used extensively with JavaServer Pages Standard Tag Library (JSTL) and custom tag libraries
to simplify JSP code and reduce Java scripting.
Additional Points:
 Multiple directives: You can have more than one directive on a single page, but directives should be placed
at the top for readability.
 Performance impact: Directives affect how the JSP page is compiled into a servlet and its overall
performance.
 JSP vs. Servlets: Directives help make JSP more flexible and maintainable compared to servlets, as they
separate presentation from business logic.
3. Write short note on JSP page directive
JSP Page Directive
1. Purpose:
o The JSP page directive provides instructions to the servlet container about how to handle and
configure the JSP page, such as importing classes, setting the content type, or managing error
handling.
2. Syntax:
o <%@ page attribute="value" %>
3. Attributes and Their Functions:
o language: Specifies the programming language used in the JSP (default is java).
o extends: Defines a superclass for the generated servlet.
o import: Imports Java packages or classes for use in the JSP (e.g., java.util.*).
o session: Specifies if the page should participate in an HTTP session (true or false).
o buffer: Sets the buffer size for the output stream (e.g., none, default, sizekb - default is at least 8 KB).
o autoFlush: Controls whether the buffer is flushed automatically (true or false).
o contentType: Defines the MIME type and character encoding for the response (default is text/html).
o errorPage: Specifies the URL of another JSP page to handle errors if an exception occurs.
o isErrorPage: Indicates if this page is an error page that can access exception objects (true or false).
o isThreadSafe: Defines the threading model for the generated servlet (true for thread-safe, false for
single-threaded).
o info: Provides a string accessed via the getServletInfo() method to describe the JSP.
o pageEncoding: Defines the character encoding for the JSP page (default is based on the contentType
or ISO-8859-1).
o isELIgnored: Specifies whether to ignore Expression Language (EL) expressions within the JSP page
(true or false).
o isScriptingEnabled: Determines whether JSP scripting elements (like <% %>) are allowed in the page.
4. Key Notes:
o You can use multiple import attributes, but other attributes can only be used once.
o Page directives can be placed anywhere in the JSP file but are typically placed at the top.
o The errorPage attribute must point to a JSP page that has isErrorPage="true" to handle exceptions.
o The default buffer size is at least 8 KB, and autoFlush ensures that the buffer is cleared when full.
CODE = TB
4. List and explain scripting elements used in JSP page
In JSP, scripting elements are used to embed Java code directly into HTML pages, enabling dynamic content
generation.
JSP Scripting Elements
1. Expressions:
o Used to insert Java values directly into the output of a JSP page.
o Syntax: <%= expression %>
o The expression is evaluated and the result is inserted into the HTML output as a string.
o Example: <%= new java.util.Date() %> (displays the current date and time).
o Can access predefined variables like request, response, session, and out.
o Example: <%= request.getRemoteHost() %> (displays the client's hostname).
2. Scriptlets:
o Used to include Java code within the service() method of the generated Servlet.
o Syntax: <% Java Code %>
o Allows for complex processing, such as retrieving request parameters and displaying results.
o Example:
jsp
Copy code
<%
String fname = request.getParameter("fname");
out.println("name: " + fname);
%>
3. Declarations:
o Used to define methods or fields that will be part of the Servlet class.
o Syntax: <%! Java Code %>
o These are placed outside of the service() method, in the body of the generated Servlet class.
o Example:
jsp
Copy code
<%!
public int getValue() {
return 25;
}
%>
o The method can be called within the JSP as <%= getValue() %>.

5. What is XML based JSP document? Explain with example


From Tb
Example Code :
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.0">
<jsp:directive.page contentType="text/html" />
<jsp:declaration>
int count = 0;
</jsp:declaration>
<jsp:scriptlet>
count++;
</jsp:scriptlet>
<jsp:expression>
count
</jsp:expression>
</jsp:root>

Chapter 14

Q 1. What are the different action element in JSP Page?


Action elements in JSP are like built-in functions that perform specific tasks. They use XML-style code to control how
the web server (Servlet engine) behaves. With JSP actions, we can do things like add another file to the page, use
JavaBeans, send the user to a different page, or create HTML content for Java plug-ins.

Syntax:
<JSP:action_name attribute="value" />

JSP action elements often use two main attributes:


1. **Id attribute**: This gives a unique name to the action, making it easy to refer to it later in the page. If the action
creates an object, this name can be used to access it through the `PageContext`.

2. **Scope attribute**: This controls how long the action's data is available. It works with the id attribute to decide
the lifespan of the object. The scope can be:
- **Page**: Data is available only on the current page.
- **Request**: Data lasts for the entire request, even if it moves to another page.
- **Session**: Data is kept for the user's whole visit.
- **Application**: Data is available for all users across the entire application.

Q 2. How to forward and pass parameter to other action in JSP?


 Purpose: The <jsp:forward> action tag is used to send the user's request to another resource, such as a
JSP file, HTML page, or Java servlet.

 How It Works: When this tag is used, it stops processing the current page and transfers the request to the
specified resource.

Syntax: <jsp:forward page="Relative URL" />

The page attribute specifies the relative URL of the another resource (another JSP, static page, or servlet).
EXAMPLE:
Let's say we have two files:

 myDate.jsp: Displays the current date.


 home.jsp: Uses <jsp:forward> to forward the request to myDate.jsp

myDate.jsp file example:


<p> Today's date: <%= (new java.util.Date()).toLocaleString() %></p>

home.jsp file example:


html
Copy code
<html>
<head><title>The JSP:forward Action Example</title></head>
<body>
<center>
<h2>The JSP:forward action Example</h2>
<jsp:forward page="myDate.jsp" />
</center>
</body>
</html>

 Result: When home.jsp is loaded, the browser displays:

The JSP:forward action Example


Today's date: [current date and time]

Passing Parameters: The <jsp:param> tag allows sending extra information, such as parameters, to another
file using an action tag like <jsp:forward>.

 Attributes:

 The <jsp:param> tag has two main attributes:


o name: Specifies the parameter's name.
o value: Specifies the parameter's value.

 Use in Forwarding: This tag is often placed inside <jsp:forward> to send parameters along with the
forwarded request.

 Multiple Parameters: You can include multiple <jsp:param> tags inside <jsp:forward> if you need to
send more than one parameter.

 Retrieving Parameters: The target file can access these parameters using
request.getParameter("parameterName").

 Example:

 Forward parameters to another file:


<html>
<head><title>Parameters</title></head>
<body>
<jsp:forward page="ssParameters.jsp">
<jsp:param name="myParam" value="Amar Patel" />
<jsp:param name="Age" value="15" />
</jsp:forward>
</body>
</html>

 In the target file (ssParameters.jsp):


This page had a parameter forwarded to it: <br>
<b>Name:</b> <%= request.getParameter("myParam") %> <br>
<b>Age:</b> <%= request.getParameter("Age") %>

Q 3 Write a short note on loading Java bean in JSP.

Adding a JavaBean to a JSP Page

1. Use <jsp:useBean> Tag: The <jsp:useBean> action is used to add or create an instance of a
JavaBean in a JSP page.
2. Attributes: Common attributes are id (to reference the bean), scope (lifecycle of the bean: page,
request, session, or application), and class (Java class used to create the bean).
3. Bean Creation: If the bean instance doesn’t exist in the specified scope, the JSP container will
create a new one.
4. Example:

<jsp:useBean id="userBean" class="com.example.User" scope="session" />


o This adds a JavaBean named "userBean" with a session scope.

Setting the Properties of a JavaBean

1. Use <jsp:setProperty> Tag: The <jsp:setProperty> action is used to set the value of a bean
property.
2. Attributes: name (identifies the bean), property (the property to set), and value (the value to
assign).
3. Usage Outside and Inside <jsp:useBean>: It can be used outside <jsp:useBean> for existing
beans, or inside to set properties when a new bean is instantiated.
4. Example:

<jsp:setProperty name="userBean" property="username" value="JohnDoe" />

o This sets the "username" property of "userBean" to "JohnDoe".

Accessing the Properties of a JavaBean

1. Use <jsp:getProperty> Tag: The <jsp:getProperty> action retrieves the value of a specified
bean property.
2. Attributes: name (identifies the bean) and property (the property to access).
3. Output the Property Value: The value is converted to a string and inserted into the JSP page's
output.
4. Example:

<jsp:getProperty name="userBean" property="username" />

o This retrieves and displays the "username" property of "userBean".

Q 4. How to set and access the properties of java bean in JSP?

Setting the Properties of a Bean

1. The <jsp:setProperty> action is used to set the properties of a previously defined Bean.
2. It can be used outside of <jsp:useBean>, meaning it will run whether a new Bean was created or an
existing one was found:

jsp
Copy code
<jsp:useBean id="myBean" ... />
<jsp:setProperty name="myBean" property="someProperty" ... />

3. If <jsp:setProperty> is inside the <jsp:useBean> element, it will only run if a new Bean is
instantiated:

jsp
Copy code
<jsp:useBean id="myBean" ...>
<jsp:setProperty name="myBean" property="someProperty" ... />
</jsp:useBean>

4. The name attribute specifies the Bean to update, and the property attribute identifies which property
to set. Using "*" for property sets all matching request parameters.
5. The value attribute assigns a specific value to the property, while the param attribute assigns a
request parameter's value.
6. If the specified parameter does not exist or is null, <jsp:setProperty> does nothing.

Accessing the Properties of a Bean

1. The <jsp:getProperty> action retrieves the value of a Bean's property and outputs it as a string.
2. The name attribute specifies which Bean to retrieve the property from, and the property attribute
specifies which property to access.
3. Here’s an example setup:

<jsp:useBean id="myBean" ... />


<jsp:getProperty name="myBean" property="someProperty" />

4. For demonstration, create a simple TestClass Bean:

public class TestClass {


private String msg = "Hello JSP...";
public String getMsg() { return msg; }
public void setMsg(String msg) { this.msg = msg; }
}

5. Make sure the compiled TestClass.class file is accessible in the web application's classpath.
6. In a JSP file:

<html>
<head><title>Using JavaBeans in JSP</title></head>
<body>
<center>
<h2>Using JavaBeans in JSP</h2>
<jsp:useBean id="test" class="testAction.TestClass" />
<jsp:setProperty name="test" property="msg" />
<p>Here we got the message</p>
<jsp:getProperty name="test" property="msg" />
</center>
</body>
</html>

Output: "Hello JSP..."

Q 5. Explain any three JSP actions.

These actions are used to create XML elements dynamically. The term "dynamically" is important because it means
the XML elements can be generated during the request, rather than being fixed at the time compiling.

You might also like