Java Server Pages | Advance Java - IndianTechnoEra
Latest update Android YouTube

Java Server Pages | Advance Java

Java Server Pages: Implicit Objects, JSP Directives, scripting elements, Extracting fields and values, attributes, Sessions in JSP, Cookies, JSP UseBe

Java Server Pages | JSP

Advance Java | IndianTechnoEra

Introduction:

JavaServer Pages (JSP) is a technology used to create dynamic web pages that are data-driven.

JSP allows developers to write server-side code using Java syntax, making it easier to create web applications.

JSP enables the separation of presentation logic from business logic, which makes it easier to maintain and update web pages.

JSP supports JavaBeans, which simplifies the management of complex data structures 

It also supports standard tag libraries, which makes it easier to create reusable code.


JSP Architecture 


JSP is a scripting language that enables developers to embed Java code within HTML pages.

JSP includes implicit objects that provide access to the runtime environment of the JSP page

It is including the request and response objects, session and application scopes, and other contextual information.

JSP can be integrated with Java servlets and other Java technologies, making it a popular choice for developing enterprise-level web applications.

JSP is platform-independent, which means it can be deployed on any server that supports Java. 

JSP can result in slower page load times due to the overhead of compiling and rendering pages dynamically.


JSP Life Cycle :

The lifecycle of a Java Server Page (JSP) can be divided into four stages:

JSP Life Cycle | IndianTechnoEra


Translation (JSP to Servlet): When a JSP is first requested, it is translated JSP into a Servlet by the JSP container. The container generates a Java file for the JSP and compiles it into a Servlet.

Compilation (Servlet to bytecode .class): The generated Servlet code compiles into bytecode by the Java compiler.

Instantiation (Create instance object of .class): It creates the instance of the generated .class 

Initialization (call jspInt() method): At the first time requested JSP the Servlet container loads it into memory and initializes it.

Execution (Call jspService() method): Finally, the JSP is executed by the container to generate the HTML output. During this stage, the container creates the necessary objects and calls the JSP methods as needed.

Destroy (Call jspDestroyer() method) : When the JSP container is shut down or the JSP page is removed from the container, the destroy() m


The lifecycle of a JSP can also include additional stages depending on how it is used. 

For example, if a JSP is included in another JSP or Servlet, its lifecycle will be affected by the container's handling of the parent JSP or Servlet. 

Additionally, if a JSP uses session or application scope attributes, its lifecycle will be tied to the lifecycle of those attributes.



Features:

Here are some features of Java server pages;

  • JSP allows for the separation of presentation and business logic.
  • It can be easily integrated with Java servlets and other Java technologies.
  • JSP is a scripting language that enables developers to write dynamic, data-driven web pages.
  • JSP is platform-independent, making it easy to deploy web applications across different platforms.
  • JSP supports standard tag libraries, which makes it easier to create reusable code.


Advantages:

There are some advantages of Java server pages;

  • JSP simplifies the development process of dynamic web pages by allowing developers to write server-side code using familiar Java syntax.
  • JSP is easy to maintain as it separates presentation logic from business logic.
  • JSP supports JavaBeans, which makes it easier to manage complex data structures.
  • JSP is platform-independent, which means it can be deployed on any server that supports Java.
  • JSP allows for the creation of reusable components that can be used across multiple web pages.


Disadvantages:

There are some disadvantages of Java server pages;

  • JSP can be difficult to learn for developers who are not familiar with Java.
  • The separation of presentation and business logic can make it harder to debug and maintain code.
  • JSP can result in slower page load times due to the overhead of compiling and rendering pages dynamically.
  • JSP pages can be prone to security vulnerabilities if not properly secured.
  • JSP can be limited in functionality compared to other web technologies, such as JavaScript or PHP.


JSP Implicit Objects: 

Implicit objects are predefined objects that are automatically available to the JSP page without any need for explicit declaration or initialization. 

JSP provides several built-in objects that can be accessed on any JSP page

These objects can be used to access information about the JSP environment, request, response, and other objects.

These objects include request, response, session, application, pageContext, and out. 

For example, to access the request object on a JSP page, you can use the following syntax: 

   ```

   <%

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

   %>

   ```

Types of Implicit Objects:

 Here is a list of types of JSP implicit objects along with an example:

  1. request
  2. response
  3. season
  4. application
  5. config
  6. pageContext
  7. out


1. request:

It represents the client's HTTP request and contains information such as parameters and headers.

Example: To access the "name" parameter sent by the client in the URL, we can use the following JSP code:

```

<p>The name parameter is: <%= request.getParameter("name") %></p>

```


2. response: 

It represents the HTTP response that the server sends to the client.

Example: To set the content type of the response to plain text, we can use the following JSP code:

```

<%

response.setContentType("text/plain");

%>

```


3. session: 

It represents the user's session, which stores information that can be accessed across multiple requests.

Example: To set a session attribute "username" with the value "John", we can use the following JSP code:

```

<%

session.setAttribute("username", "John");

%>

```


4. application: 

It represents the JSP application context and contains information that can be accessed by all JSP pages in the same context.

Example: To get the context path of the JSP application, we can use the following JSP code:

```

<p>The context path is: <%= application.getContextPath() %></p>

```


5. config: 

It represents the configuration information of the JSP page, such as initialization parameters.

Example: To get the value of an initialization parameter "dbUrl", we can use the following JSP code:

```

<p>The database URL is: <%= config.getInitParameter("dbUrl") %></p>

```


6. pageContext: 

It represents the context of the JSP page and contains information that can be accessed by all JSP elements on the page.

Example: To get the name of the JSP page, we can use the following JSP code:

```

<p>The JSP page name is: <%= pageContext.getServletConfig().getServletName() %></p>

```


7. out: 

It represents the output stream used to send content to the client.

Example: To write "Hello World!" to the response, we can use the following JSP code:

```

<%

out.print("Hello World!");

%>

```



JSP Directives: 

JSP directives provide instructions to the JSP container on how to process a JSP page

They are used to specify page settings, import classes, and define custom tags. 

There are three types of directives: page, include, and taglib. 

For example, to import a Java class in a JSP page, you can use the following syntax: 

   <%@ page import="com.example.MyClass" %>



Types of JSP Directives :

Here is a list of the type of JSP Directives along with an example:

  1. Page directive
  2. Include directive
  3. Taglib directive


1. Page directive:

It is used to provide instructions to the container about the page. 

It is defined using the "<%@ page %>" tag. 


Some of the commonly used attributes of the page directive are:

- import - It is used to import classes into the JSP page.

- contentType - It is used to specify the MIME type of the response.

- session - It is used to enable or disable session tracking.

- isErrorPage - It is used to indicate whether the page is an error page.


Example:

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

<%@ page contentType="text/html" %>

<%@ page session="false" %>

<%@ page isErrorPage="true" %>


2. Include directive:

It is used to include a file in the JSP page. 

It is defined using the "<%@ include %>" tag.

Example:

<%@ include file="header.jsp" %>


3. Taglib directive:

It is used to declare a custom tag library in the JSP page. 

It is defined using the "<%@ taglib %>" tag.

Example:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> 


In this example, the "uri" attribute specifies the URI of the tag library.

The "prefix" attribute specifies the prefix that will be used to refer to the tag library in the JSP page. 

The "c" prefix is commonly used for the JSTL core tag library.


Scripting Elements: 

JSP provides several scripting elements to embed Java code into a JSP page

These elements include scriptlets, expressions, and declarations

Scriptlets are used to execute arbitrary Java code, 

while expressions are used to evaluate and display values. 

Declarations are used to define variables and methods

For example, to define a variable in a JSP page, you can use the following syntax: 

Examples:

   <%! 

   int count = 0;

   %>


Types of JSP Scripting Elements:

JSP scripting elements are used to write Java code in a JSP file. The following are the types of JSP scripting elements:

  1. Declaration tags
  2. Expression tags
  3. Scriptlet tags
  4. Directive tags
  5. Expression Language (EL)


1. Declaration Tags: 

The declaration tag is used to declare variables and methods in JSP.

 The code written in the declaration tag is placed outside the service method but inside the JSP class.

Example: 

<%!

   int x = 5;

   public String getName() {

      return "John";

   }

%>


2. Expression Tags: 

The expression tag is used to insert the value of an expression directly into the output stream of the JSP. The value can be a variable or a method call.

Example: 

<%= x %>


3. Scriptlet Tags: 

The scriptlet tag is used to include Java code in a JSP file

The code written in the scriptlet tag is placed inside the service method.

Example: 

<%

   int x = 5;

   int y = 10;

   int sum = x + y;

%>


4. Directive Tags: 

The directive tag is used to provide instructions to the JSP container on how to process the JSP page.

Example: 

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

    pageEncoding="UTF-8" %>


5. Expression Language (EL): 

The EL is a simplified way to access JavaBean components or other data sources

The expression is evaluated at runtime and the value is inserted into the output stream.

Example: 

${person.name}


In the above example, the value of the name property of the person bean is inserted into the output stream.

An example JSP code that demonstrates the use of all five types of scripting elements in a single JSP page

This JSP code includes a declaration that defines variables and a method, a scriptlet that reads a parameter and writes a message, an expression that outputs a Java expression to HTML, a directive to set language and encoding, and a comment. 

It also uses a JSP standard action to create a JavaBean and access its properties with EL. 

When accessed, the declaration, scriptlet, and EL are evaluated and their results are included in HTML output, while the directive sets the language and encoding, and the comment is ignored.

Extracting fields and values: 

JSP pages can extract form fields and their values using the request object. 

This allows you to retrieve user input and use it in your application logic. 

For example, to retrieve a form field named "username" in a JSP page, you can use the following syntax: 

   ```

   <%

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

   %>

   ```

How to extract

There are different ways to extract fields and values in JSP:

  1. Request Parameters
  2. URL Parameters
  3. Session Parameters
  4. Application Parameters


1. Request Parameters: 

This is the most common way to extract data from an HTML form submission. 

The JSP implicit object `request` is used to retrieve the values from the form elements. 

Examples:

   ```

   <form action="process.jsp" method="post">

      First Name: <input type="text" name="firstName"><br>

      Last Name: <input type="text" name="lastName"><br>

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

   </form>

   ```


   In the `process.jsp` page, we can extract the values using the `request` object as follows:

   ```

   <%

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

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

   %>

   ```


2. URL Parameters: 

The JSP implicit object `request` can also be used to extract parameters passed through the URL.

Examples:

   ```

   <a href="process.jsp?name=John&age=25">Click Here</a>

   ```


   In the `process.jsp` page, we can extract the values using the `request` object as follows:

   ```

   <%

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

      int age = Integer.parseInt(request.getParameter("age"));

   %>

   ```


3. Session Attributes: 

Session attributes are used to store data across multiple requests. The JSP implicit object `session` is used to retrieve the values.

Examples:

   ```

   <%

      session.setAttribute("username", "JohnDoe");

   %>

   ```


   In another JSP page, we can extract the value using the `session` object as follows:

   ```

   <%

      String username = (String) session.getAttribute("username");

   %>

   ```


4. Application Attributes:

 Application attributes are used to store data that is shared across all users of an application. The JSP implicit object `application` is used to retrieve the values.

Examples:

   ```

   <%

      application.setAttribute("companyName", "XYZ Corporation");

   %>

   ```


   In another JSP page, we can extract the value using the `application` object as follows:

   ```

   <%

      String companyName = (String) application.getAttribute("companyName");

   %>

   ```




JSP Attributes: 

JSP pages can define and use attributes to store and share data between different components. 

There are four types of attributes: page, request, session, and application. 

For example, to set a session attribute in a JSP page, you can use the following syntax: 

   ```

   <%

   session.setAttribute("username", "John");

   %>

   ```

In JSP, attributes are used to store and retrieve data between different components of the JSP page. 


Types of JSP Attributes:

There are two types of attributes in JSP: page attributes and request attributes.

  1. Page Attributes
  2. Request Attributes
  3. Session Attributes
  4. Application Attributes


1. Page Attributes: 

Page attributes are used to set and retrieve values that are specific to a JSP page. 

These attributes are accessible to all the components on the same page

The syntax for setting a page attribute is:

    <%@ page attribute="value" %>


For example, the following code sets a page attribute named "title" to the value "Welcome to my website!":

    <%@ page title="Welcome to my website!" %>

This attribute can be retrieved in any component on the same page using the following syntax:

    <%= request.getAttribute("title") %>


2. Request Attributes: 

JSP request attributes are used to store data that is specific to a particular request and can be accessed from the same JSP page or from other pages that are forwarded from this page. 


Here's an example:

Suppose you have a JSP page that displays a form for users to enter their name and email address. When the user submits the form, the JSP page will receive the data as request parameters. 

To display a confirmation message to the user that their form has been submitted, you can use request attributes.

```

<%@ page language="java" %>

<%

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

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

   // process the data and store the result in a variable called message

   String message = "Thank you, " + name + ". Your email (" + email + ") has been added to our mailing list.";

   // set the message as a request attribute

   request.setAttribute("message", message);

%>

<html>

   <head>

      <title>Form Submitted</title>

   </head>

   <body>

      <h1>Form Submitted</h1>

      <%-- display the message using the request attribute --%>

      <p><%= request.getAttribute("message") %></p>

   </body>

</html>

```


In this example, we retrieve the name and email parameters from the request object and process them to create a message to be displayed to the user. 

We then set the message as a request attribute using the `request.setAttribute()` method. 

Finally, we display the message to the user in the HTML body using the `<%= request.getAttribute("message") %>` syntax.


3. Session attributes:

In JSP, session attributes are used to store and retrieve information about the user across multiple requests

When a user makes a request to a JSP page, a session is created to store information about the user. 

Session attributes can be set, retrieved, and removed using the `HttpSession` object.


To set a session attribute in JSP, the `setAttribute()` method of the `HttpSession` object is used. For example:


```

<%

   HttpSession session = request.getSession();

   session.setAttribute("username", "John");

%>

```


In this example, a session attribute named "username" is set to "John".


To retrieve a session attribute in JSP, the `getAttribute()` method of the `HttpSession` object is used. For example:


```

<%

   HttpSession session = request.getSession();

   String username = (String)session.getAttribute("username");

   out.println("Welcome, " + username);

%>

```


In this example, the value of the session attribute named "username" is retrieved and stored in a variable named `username`. The value is then displayed in a message using the `out` object.


Session attributes can also be removed using the `removeAttribute()` method of the `HttpSession` object. For example:


```

<%

   HttpSession session = request.getSession();

   session.removeAttribute("username");

%>

```

In this example, the session attribute named "username" is removed.


4. Application attributes:

JSP application attributes are used to store data that needs to be accessed across the entire application

These attributes can be set, retrieved, and removed within any JSP page or servlet of the application.


Here's an example of how to set an application attribute in a JSP page:

```

<%

    String message = "Welcome to my application!";

    application.setAttribute("welcomeMessage", message);

%>

```


In this example, we are setting an attribute called "welcomeMessage" with the value of "Welcome to my application!" using the `application.setAttribute()` method.


Here's an example of how to retrieve an application attribute in another JSP page:

```

<%

    String message = (String) application.getAttribute("welcomeMessage");

    out.println(message);

%>

```


In this example, we are retrieving the value of the "welcomeMessage" attribute using the `application.getAttribute()` method and then printing it out to the page using the `out.println()` method.


By using application attributes, we can share data across multiple JSP pages and servlets in our application. 

However, it's important to note that application attributes are accessible to all users of the application, so sensitive data should not be stored as an application attribute.





Sessions in JSP: 

JSP pages can use the session object to manage user sessions and store user-specific data

Sessions in JSP are used to maintain state and store user-specific data between requests.

For example, to retrieve a session attribute in a JSP page, you can use the following syntax: 


   ```

   <%

   String username = (String) session.getAttribute("username");

   %>

   ```


Types of JSP Sessions:

The following are the different types of sessions in JSP:

  1. HttpSession
  2. URL Rewriting
  3. Cookies
  4. Hidden Form Fields


1. HttpSession: 

It is a session management object that provides a way to identify a user across more than one page request or visit to a website and to store information about that user. 

The HttpSession object is created using the `getSession()` method of the HttpServletRequest object.


Example:

```

<%

    HttpSession session = request.getSession(true);

    session.setAttribute("username", "John");

%>

```


2. URL Rewriting: 

It is a technique in which session information is added to the URL as a parameter. 

This technique allows the user to continue using the same session across different pages of the website.


Example:

```

<a href="page2.jsp?sessionid=<%= session.getId() %>">Page 2</a>

```


3. Cookies: 

Cookies are small text files that are stored on the client side and sent back to the server with each subsequent request. 

They can be used to store session information on the client side.


Example:

```

<%

    Cookie userCookie = new Cookie("username", "John");

    userCookie.setMaxAge(60*60*24);

    response.addCookie(userCookie);

%>

```


4. Hidden Form Fields: 

Hidden form fields are used to store session information in an HTML form

This technique involves adding hidden input fields to the HTML form.


Example:

```

<form action="page2.jsp" method="post">

    <input type="hidden" name="sessionid" value="<%= session.getId() %>">

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

</form>

```


Overall, sessions in JSP provide a way to maintain state and store user-specific data between requests, making web applications more interactive and personalized.



JSP Cookies : 

JSP pages can use cookies to store and retrieve user preferences and data. 

Cookies are small pieces of data that are stored on the client-side and can be accessed by the server-side. 

JSP allows developers to create, modify, and delete cookies using built-in classes and methods.


For example, to set a cookie in a JSP page, you can use the following syntax: 

   ```

   <%

   Cookie cookie = new Cookie("username", "John");

   cookie.setMaxAge(3600);

   response.addCookie(cookie);

   %>

   ```


Types of JSP cookies:

There are two types of cookies in JSP:

  1. Session Cookies
  2. Persistent Cookies

1. Session Cookies: 

These cookies are stored on the client side for the duration of the user's session

They are commonly used to store user-specific information such as login credentials or preferences


Here is an example of setting a session cookie:

```

<%

    String name = "username";

    String value = "john.doe";

    Cookie cookie = new Cookie(name, value);

    response.addCookie(cookie);

%>

```


2. Persistent Cookies: 

These cookies are stored on the client-side for a specific duration of time

They are commonly used to store information that needs to persist across multiple sessions, such as user language preferences. 


Here is an example of setting a persistent cookie:

```

<%

    String name = "language";

    String value = "en";

    int maxAge = 3600; // cookie will expire after 1 hour

    Cookie cookie = new Cookie(name, value);

    cookie.setMaxAge(maxAge);

    response.addCookie(cookie);

%>

```


In both examples, the `Cookie` class is used to create a new cookie with a name and value. 

The `response.addCookie()` method is used to add the cookie to the HTTP response.


To retrieve a cookie in JSP, you can use the `request.getCookies()` method, which returns an array of `Cookie` objects. Here is an example:


```

<%

    Cookie[] cookies = request.getCookies();

    if (cookies != null) {

        for (Cookie cookie : cookies) {

            String name = cookie.getName();

            String value = cookie.getValue();

            out.println(name + ": " + value + "<br>");

        }

    }

%>

```

This code retrieves all cookies sent by the client and outputs their names and values. 

Note: that cookies are not secure by default and can be manipulated by the client, so it is important to validate and sanitize any data stored in cookies.


JSP UseBean:

JSP provides a tag called useBean to instantiate and use JavaBeans in a JSP page. 

JavaBeans are reusable software components that encapsulate data and behavior. 

JSP UseBean is a tag in JSP used to instantiate and manipulate Java objects in the page. 

It allows the creation of a new instance of a JavaBean and sets the instance's properties with the provided values.

For example, to use a JavaBean named "User" in a JSP page, you can use the following syntax: 

   ```

   <jsp:useBean id="user" class="com.example.User" />

   ```


Types of JSP UseBean:

There are two types of JSP UseBean:

  1. Simple JSP UseBean
  2. JSP UseBean with BeanInfo


1. Simple JSP UseBean: 

In this type, the JSP page creates an instance of a JavaBean and initializes it using the JSP setProperty tags. 

The following is an example:

```

<jsp:useBean id="person" class="com.example.Person" scope="session"/>

<jsp:setProperty name="person" property="name" value="John"/>

<jsp:setProperty name="person" property="age" value="30"/>

```


2. JSP UseBean with BeanInfo: 

In this type, a BeanInfo class is used to describe the properties of the JavaBean. 

The following is an example:

```

<jsp:useBean id="person" class="com.example.Person" scope="session">

    <jsp:attribute name="name" value="John"/>

    <jsp:attribute name="age" value="30"/>

</jsp:useBean>

```


In this example, the JSP page creates an instance of the Person class and sets its properties using the attributes in the UseBean tag.

The JSP UseBean tag can also be used with the JSP getProperty tag to retrieve the values of the properties of the JavaBean. The following is an example:

For example, to use a JavaBean named "User" in a JSP page, you can use the following syntax: 

<jsp:useBean id="person" class="com.example.Person" scope="session"/>

<jsp:getProperty name="person" property="name"/>

```


In this example, the JSP page retrieves the value of the "name" property of the Person instance created in the UseBean tag.


JSP UseBean tag helps to encapsulate the functionality of JavaBeans and make the code modular and reusable.


Java Standard Tag Library (JSTL): 

JSTL is a library of custom tags that provide a simplified way to perform common tasks in JSP pages, such as iteration, conditionals, and formatting. 

For example, to iterate over a collection in a JSP page using the forEach tag of JSTL,

Java Standard Tag Library (JSTL) is a collection of tags that simplify the development of JSP-based web applications. 

These tags can be used to perform common tasks such as iteration, conditional processing, and internationalization. 


Types of JSTL:

JSTL has several types of tags:

  1. Core Tags
  2. Formatting Tags
  3. SQL Tags
  4. XML Tags


1. Core Tags: 

These tags provide basic functionality for iteration, conditional processing, and manipulation of variables. 

Example: 

```

<c:forEach var="i" begin="1" end="5">

    <p>Iteration number: ${i}</p>

</c:forEach>

```

This code block will iterate from 1 to 5 and print the iteration number in a paragraph element for each iteration.


2. Formatting Tags: 

These tags provide support for internationalization and formatting of dates, numbers, and currencies.

Example: 

```

<fmt:setLocale value="en_US" />

<fmt:formatDate value="${now}" type="date" />

```

This code block sets the locale to US English and formats the current date using the "date" type.


3. SQL Tags: 

These tags provide support for executing SQL queries and manipulating result sets.

Example: 

```

<sql:setDataSource

    driver="org.apache.derby.jdbc.ClientDriver"

    url="jdbc:derby://localhost:1527/myDB"

    user="username"

    password="password" />

<sql:query dataSource="${dataSource}" var="result">

    SELECT * FROM myTable

</sql:query>

```

This code block sets up a data source for connecting to a Derby database and executes a SQL query to retrieve all rows from a table named "myTable".


4. XML Tags: 

These tags provide support for parsing and manipulating XML documents.

Example: 

```

<x:parse xml="${xmlString}" var="doc" />

<x:forEach select="$doc//book" var="book">

    <p>Book title: <x:out select="$book/title" /></p>

</x:forEach>

```

This code block parses an XML document from a string and iterates over all "book" elements to print the title of each book.

JSTL tags make JSP development easier by providing a simplified syntax for common tasks.




Topic Explained: Java Server Pages: Implicit Objects, JSP Directives, scripting elements, Extracting fields and values, attributes, Sessions in JSP, Cookies, JSP UseBean, Java Standard Tag Library, Expression Language, Custom Tag, Introduction to MVC Pattern. 

إرسال تعليق

Feel free to ask your query...
Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.