0% found this document useful (0 votes)
3 views44 pages

Server Side Development

The document provides an overview of Java Server Pages (JSP), detailing its fundamentals, architecture, scripting elements, implicit objects, directives, actions, and integration with JavaBeans. It explains the different components of JSP, including how to use scripting elements like declarations, scriptlets, and expressions, as well as the use of implicit objects for accessing server-side data. Additionally, it covers JSP actions for including and forwarding resources, managing JavaBeans, and session management in web applications.

Uploaded by

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

Server Side Development

The document provides an overview of Java Server Pages (JSP), detailing its fundamentals, architecture, scripting elements, implicit objects, directives, actions, and integration with JavaBeans. It explains the different components of JSP, including how to use scripting elements like declarations, scriptlets, and expressions, as well as the use of implicit objects for accessing server-side data. Additionally, it covers JSP actions for including and forwarding resources, managing JavaBeans, and session management in web applications.

Uploaded by

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

Server Side Development

Java Server Pages


Topics
• JSP Fundamentals
• JSP Scripting Elements
• JSP Implicit Objects
• JSP Directives
• JSP Actions
• JSP Example (Loan Calculator)
• Servlets & JSPs together
• Tag Libraries
• Deploying and Running a JSP Application
Java Server Pages (JSP)
Fundamentals
• Java Server Pages are HTML pages embedded with
snippets of Java code.
– It is an inverse of a Java Servlet
• Four different elements are used in constructing JSPs
– Scripting Elements
– Implicit Objects
– Directives
– Actions
Java Server Pages (JSP)
Architecture
• JSPs run in two phases Receive
Request
HTTP
Server

– Translation Phase JSP

– Execution Phase JSP


Serv
Container
Page Compiler Servlet

No
• In translation phase JSP
let Parse JSP
Curr
ent?
JSP Yes
page is compiled into a Serv
let Generate JSP

servlet Load Servlet Source


ed?
Yes No

– called JSP Page Load Servlet


Compile JSP
Servlet
Implementation class
• In execution phase the Generate
JSP Page Servlet

compliled JSP is processed Response

Send
Respon
se
Scripting Elements
Types
• There are three kinds of scripting elements
– Declarations
– Scriptlets
– Expressions
Declarations
Basics
• Declarations are used to define methods & instance
variables
– Do not produce any output that is sent to client
– Embedded in <%! and %> delimiters
Example:
<%!
Public void jspDestroy() {
System.out.println(“JSP Destroyed”);
}
Public void jspInit() {
System.out.println(“JSP Loaded”);
}
int myVar = 123;
%>
– The functions and variables defined are available to the JSP
Page as well as to the servlet in which it is compiled
Scriptlets
Basics
• Used to embed java code in JSP pages.
– Contents of JSP go into _JSPpageservice() method
– Code should comply with syntactical and semantic constuct
of java
– Embedded in <% and %> delimiters
Example:
<%
int x = 5;
int y = 7;
int z = x + y;
%>
Expressions
Basics
• Used to write dynamic content back to the browser.
– If the output of expression is Java primitive the value is
printed back to the browser
– If the output is an object then the result of calling toString on
the object is output to the browser
– Embedded in <%= and %> delimiters
Example:
– <%=“Fred”+ “ “ + “Flintstone %>
prints “Fred Flintstone” to the browser
– <%=Math.sqrt(100)%>
prints 10 to the browser
Java Implicit Objects
Scope
• Implicit objects provide access to server side objects
– e.g. request, response, session etc.
• There are four scopes of the objects
– Page: Objects can only be accessed in the page where they are
referenced
– Request: Objects can be accessed within all pages that serve
the current request.
(Including the pages that are forwarded to and included in the
original jsp page)
– Session: Objects can be accessed within the JSP pages for
which the objects are defined
– Application: Objects can be accessed by all JSP pages in a
given context
Java Implicit Objects
List
• request: Reference to the current request
• response: Response to the request
• session: session associated woth current request
• application: Servlet context to which a page belongs
• pageContext: Object to access request, response,
session and application associated with a page
• config: Servlet configuration for the page
• out: Object that writes to the response output stream
• page: instance of the page implementation class (this)
• exception: Available with JSP pages which are error
pages
Java Implicit Objects
Example
<html> <p>
<head> Storing a string to the application...<br>
<title>Implicit Objects</title> <% application.setAttribute("name", "Meeraj"); %>
</head> Retrieving the string from application...<br>
<body style="font-family:verdana;font-size:10pt"> <b>Name:</b>
<p> <%= application.getAttribute("name") %>
Using Request parameters...<br> </p>
<b>Name:</b> <%= request.getParameter("name") %> <p>
</p> Storing a string to the page context...<br>
<p> <% pageContext.setAttribute("name", "Meeraj"); %>
<% out.println("This is printed using the out implicit Retrieving the string from page context...</br>
variable"); %> <b>Name:</b>
</p> <%= pageContext.getAttribute("name") %>
<p> </p>
Storing a string to the session...<br> </body>
<% session.setAttribute("name", "Meeraj"); %> </html>
Retrieving the string from session...<br>
<b>Name:</b> <%= session.getAttribute("name") %>
</p>
Example Implicit Objects
Deploy & Run
• Save file:
– $TOMCAT_HOME/webapps/jsp/Implicit.jsp
• Access file
– http://localhost:8080/jsp/Implicit.jsp?name=Sanjay
• Results of the execution

Using Request parameters...


Name: sanjay
This is printed using the out implicit variable
Storing a string to the session...
Retrieving the string from session...
Name: Meeraj
Storing a string to the application...
Retrieving the string from application...
Name: Meeraj
Storing a string to the page context...
Retrieving the string from page context...
Name: Meeraj
Directives
Basics & Types
• Messages sent to the JSP container
– Aids the container in page translation
• Used for
– Importing tag libraries
– Import required classes
– Set output buffering options
– Include content from external files
• The jsp specification defines three directives
– Page: provder information about page, such as scripting language that is
used, content type, or buffer size
– Include – used to include the content of external files
– Taglib – used to import custom actions defined in tag libraries
Page Directives
Basics & Types
• Page directive sets page properties used during translation
– JSP Page can have any number of directives
– Import directive can only occur once
– Embedded in <%@ and %> delimiters
• Different directives are
– Language: (Default Java) Defines server side scripting language (e.g. java)
– Extends: Declares the class which the servlet compiled from JSP needs to extend
– Import: Declares the packages and classes that need to be imported for using in
the java code (comma separated list)
– Session: (Default true) Boolean which says if the session implicit variable is
allowed or not
– Buffer: defines buffer size of the jsp in kilobytes (if set to none no buffering is
done)
Page Directives
Types con’t.
• Different directives are (cont’d.)
– autoFlush:When true the buffer is flushed when max buffer size is
reached (if set to false an exception is thrown when buffer exceeds the
limit)
– isThreadSafe: (default true) If false the compiled servlet implements
SingleThreadModel interface
– Info: String returned by the getServletInfo() of the compiled servlet
– errorPage: Defines the relative URI of web resource to which the
response should be forwarded in case of an exception
– contentType: (Default text/html) Defines MIME type for the output
response
– isErrorPage: True for JSP pages that are defined as error pages
– pageEncoding: Defines the character encoding for the jsp page
Page Directives
Example
<%@
page language=“java”
buffer=“10kb”
autoflush=“true”
errorPage=“/error.jsp”
import=“java.util.*, javax.sql.RowSet”
%>
Include Directive
Basics
• Used to insert template text and JSP code during the translation
phase.
– The content of the included file specified by the directive is included in
the including JSP page
• Example
– <%@ include file=“included.jsp” %>
Taglib Directive
• In JavaServer Pages (JSP), the <%@ taglib
%> directive is used to declare and define
custom tag libraries in a JSP page. Tag
libraries provide a way to extend the
functionality of JSP by encapsulating
reusable code into custom tags. These tags
can be used in JSP pages to perform
specific tasks.
Syntax
• The syntax for the <%@ taglib %>
directive is as follows:
• <%@ taglib uri="URI" prefix="PREFIX"
%>
• uri: Uniform Resource Identifier that
uniquely identifies the tag library. The URI
is used to locate the tag library descriptor
(TLD) file, which provides information
about the tags in the library.
• prefix: A short name or prefix that is used
to reference the tags from the specified tag
library in the JSP page.
Example
• <%@ taglib uri="http://java.sun.com/jsp/jstl/core"
prefix="c" %>
• In this example, the JSTL (Java Server Pages
Standard Tag Library) core tag library is declared
with the URI "http://java.sun.com/jsp/jstl/core"
and the prefix "c". This allows you to use JSTL
core tags in your JSP page using the "c" prefix.
• After declaring a tag library, you can use
the custom tags defined in that library
throughout the JSP page using the specified
prefix. Custom tags typically encapsulate
logic or functionality that can be reused
across multiple JSP pages, promoting
modularity a
• nd maintainability in web applications.
JSP Actions
Basics & Types
• Processed during the request processing phase.
– As opposed to JSP directives which are processed during translation
• Standard actions should be supported by J2EE compliant web servers
• Custom actions can be created using tag libraries
• The different actions are
– Include action
– Forward action
– Param action
– useBean action
– getProperty action
– setProperty action
– plugIn action
JSP Actions
Include
• Include action used for including resources in a JSP page
– Include directive includes resources in a JSP page at translation time
– Include action includes response of a resource into the response of the
JSP page
– Same as including resources using RequestDispatcher interface
– Changes in the included resource reflected while accessing the page.
– Normally used for including dynamic resources
• Example
– <jsp:include page=“inlcudedPage.jsp”>
– Includes the the output of includedPage.jsp into the page where this is
included.
JSP Actions
Forward
• Forwards the response to other web specification resources
– Same as forwarding to resources using RequestDispatcher interface
• Forwarded only when content is not committed to other web
application resources
– Otherwise an IllegalStateException is thrown
– Can be avoided by setting a high buffer size for the forwarding jsp page
• Example
– <jsp:forward page=“Forwarded.html”>
– Forwards the request to Forwarded.html
JSP Actions
Param
• Used in conjunction with Include & Forward actions to include
additional request parameters to the included or forwarded
resource
• Example
<jsp:forward page=“Param2.jsp”>
<jsp:param name=“FirstName” value=“Sanjay”>
</jsp:forward>
– This will result in the forwarded resource having an additional parameter
FirstName with a value of Sanjay
Java Beans
• JavaBeans are commonly used in conjunction with
JavaServer Pages (JSP) to separate the presentation logic
from the business logic in web applications. This helps
maintain a clean and modular architecture. Here's how you
can use JavaBeans with JSP
Creating a JavaBean
• Define a JavaBean class with private fields, getter and setter
methods, and a default constructor.
public class PersonBean {
private String name;
private int age;
public PersonBean() {
// Default constructor
}
// Getter and setter methods for name
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
// Getter and setter methods for age
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
JSP Actions
useBean
• Creates or finds a Java object with the defined scope.
– Object is also available in the current JSP as a scripting variable

• Syntax:
<jsp:useBean id=“name”
scope=“page | request | session | application”
class=“className” type=“typeName” |
bean=“beanName” type=“typeName” |
type=“typeName” />
– At least one of the type and class attributes must be present
– We can’t specify values for bith the class and bean name.

• Example
<jsp:useBean id=“myName” scope=“request” class=“java.lang.String”>
<% firstName=“Sanjay”; %>
</jsp:useBean>
JSP Actions
get/setProperty
• getProperty is used in conjunction with useBean to get property values of the
bean defined by the useBean action
• Example (getProperty)
– <jsp:getProperty name=“myBean” property=“firstName” />
– Name corresponds to the id value in the useBean
– Property refers to the name of the bean property

• setProperty is used to set bean properties


• Example (setProperty)
– <jsp:setProperty name=“myBean” property=“firstName” value=“Sanjay”/>
– Sets the name property of myBean to SanjayExample (setProperty)
– <jsp:setProperty name=“myBean” property=“firstName” param=“fname”/>
– Sets the name property of myBean to the request parameter fname
– <jsp:setProperty name=“myBean” property=“*”>
– Sets property to the corresponding value in request
JSP Actions
plugIn
• Enables the JSP container to render appropriate HTML (based on the
browser type) to:
– Initiate the download of the Java plugin
– Execution of the specified applet or bean
• plugIn standard action allows the applet to be embedded in a browser neutral
fashion
• Example
<jsp: plugin type=“applet” code=“MyApplet.class” codebase=“/”>
<jsp:params>
<jsp:param name=“myParam” value=“122”/>
</jsp:params>
<jsp:fallback><b>Unable to load applet</b></jsp:fallback>
</jsp:plugin>
useBean in JSP
• <jsp:useBean id="person" class="com.example.PersonBean" scope="request"
/>
• <html>
• <head>
• <title>JavaBeans with JSP</title>
• </head>
• <body>
• <h1>Person Details</h1>
• <c:out value="${person.name}" /> is <c:out value="${person.age}" /> years
old.
• </body>
• </html>
• In this example, <jsp:useBean> is used to
create or locate a bean with the id "person" of
the type "com.example.PersonBean" in the
request scope.
• The JavaBean is automatically instantiated if it
does not exist, and its properties can be
accessed using the expression language (EL) in
the JSP page.
Session Management
• In Java web applications, session tracking is a mechanism
that allows the server to maintain stateful information
about a user across multiple requests. This is crucial for
scenarios where you need to keep track of user-specific
data during their interaction with your web application.
Ways to implement session
tracking
• Cookies
• URL Rewriting
• HTTP Session Object
• Session Configuration in web.xml
Cookies
• Java servlets can use cookies to store session
information on the client side.
• You can use the HttpServletResponse object
to set a cookie with the necessary session
information, and then retrieve that
information using the HttpServletRequest
object in subsequent requests.
Example
• // Setting a cookie
• Cookie myCookie = new Cookie("username",
"john_doe");
• response.addCookie(myCookie);
• // Retrieving a cookie
• Cookie[] cookies = request.getCookies();
• for (Cookie cookie : cookies) {
• if (cookie.getName().equals("username")) {
• String username = cookie.getValue();
• break;
• }
• }
URL Rewriting
• In URL rewriting, you append the session information to
URLs.
• You can use the HttpServletResponse object to encode
the URLs with session information and then extract it in
subsequent requests using the HttpServletRequest object.
• // Encoding URL with session information
• String urlWithSession =
response.encodeURL("/myapp/mypage");

• // Using the encoded URL in a response


• response.sendRedirect(urlWithSession);

• // Retrieving session information from a request


• String sessionId = request.getRequestedSessionId();
HTTP Session Object
• The HttpSession object is part of the servlet API and
provides a server-side mechanism for session tracking.
• You can use the getSession() method of
HttpServletRequest to get the HttpSession object.
Example
• // Storing data in the session
• HttpSession session = request.getSession();
• session.setAttribute("username", "john_doe");

• // Retrieving data from the session


• HttpSession session = request.getSession();
• String username = (String)
session.getAttribute("username");
Session Configuration in
web.xml
• You can configure session behavior in the web.xml file of
your web application.
• You can set session timeout, cookie properties, and other
session-related configurations.
Example
• <web-app>
• <session-config>
• <session-timeout>30</session-
timeout>
• </session-config>
• </web-app>

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy