0% found this document useful (0 votes)
51 views59 pages

Lecture1.1 - Java Server Pages

Uploaded by

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

Lecture1.1 - Java Server Pages

Uploaded by

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

JAVASERVER PAGES

Instructor:

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 1


Learning Goals

Know about
Java Server
Pages (JSP)
Can use JSP
to build Web
application

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 2


Table of contents
◊ JSP Introduction
◊ JSP Scripting Element
◊ JSP Implicit Objects
◊ Expression language
◊ Q&A

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 3


Section 1

JSP INTRODUCTION

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 4


JSP Introduction (1/2)
 What is JSP?
 JavaServer Pages (JSP) is a technology for developing web pages that
support dynamic content which helps developers insert java code in
HTML.
 As an extension of Servlet technology
 JSPs are essential an HTML page with special JSP tags embedded.
 All JSP programs are stored as a .jsp files

HTML page JSP page

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 5


JSP Introduction (2/2)
 Servlet:
 Java Servlets are programs that run on a Web server and act as a
middle layer between a request coming from a Web browser and
databases on the HTTP server.

 JSP vs Servlet:

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 6


Architecture of a JSP Application
 JSP plays a key role and it is responsible for of processing
the request made by client.
 Client (Web browser) makes a request
 JSP then creates a bean object which then fulfills the request and
pass the response to JSP
 JSP then sends the response back to client

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 7


JSP Process
Steps required for a JSP request:
1. The user goes to web side made using JSP. The web browser makes the request via the
Internet.
2. The JSP request gets sent to the Web server.
3. The Web server recognizes that the file required is special (.jsp), therefore passes the JSP file to the
JSP servlet engine.
4. If the JSP file has been called the first time, the JSP file is parsed, otherwise goto step 7.
5. The next step is to generate a special Servlet from the JSP file. All the HTML required is converted
to println statements.
6. The Servlet source code is compiled into a class.
7. The servlet is instantiated, calling the init and service methods.
8. HTML from the Servlet output is sent via the Internet.
9. HTML results are displayed on the user's web browser.

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 8


Example
First Example

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 9


Practical time
1. Create Dynamic Web Project:

2. Create jsp page in


WebContent folder

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 10


Practical time
Create a simple jsp
page:

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 11


Practical time
3. Setup tomcat server:
 Download and unzip Apache Tomcat .
 Open Window | Preferences | Server | Installed Runtimes to create a
Tomcat installed runtime.
 Click on Add... to open the New Server Runtime dialog, then select your
runtime under Apache
4. Run your code

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 12


Section 2

JSP SCRIPTING ELEMENT

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 13


Scriptlet
 Scriptlet (<% ... %>) - also called “Scripting Elements”
 Enable programmers to insert Java code in JSPs
 Performs request processing
 For example, to print a variable:

Code snippet
<%
String username = "alliant";
out.println(username);
%>

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 14


JSP Tags
 Declaration tag (<%! %>)
 Allow the developer to declare variables or methods.

Code snippet
<%!
private int counter = 0;
private String getAccount(int accountNo);
%>
 Expression tag (<%= %>)
 Allow the developer to embed any Java expression and is short for
out.println()

Code snippet
<%!
<%=new java.util.Date()%>
%>

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 15


Directive tags (1/3)
 Directive[chỉ thị] (<%@ directive... %>
 Give special information about the page to the JSP
container.
 Enable programmers to specify:
 Page settings (page directive):
Ex:<%@page import="java.sql.Statement"%>
 Content to include from other resources (Include directive).
Ex:<%@include file="Connection.jsp"%>

 Tag libraries to be used in the page (Tag library).


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

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 16


Directive tags (2/3)
 Content to include from other resources (Include
directive).

Code snippet
<%@page import="java.util.Date"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Directive tag</title>
</head>
<body>
<%@include file="Header.jsp"%>

<hr />
<h2>This is main content</h2>
<h4 style="color: red"><%=new Date()%></h4>
<hr />

<%@include file="Footer.jsp"%>
</body>
</html>
43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 17
Directive tags (3/3)
 Tag libraries to be used in the page (Tag library).
 Add jstl lib

 Defining core tags:

<%@ taglib prefix="c"


uri="http://java.sun.com/jsp/jstl/core"%>
Code snippet
<h3 align="left">TRAINEE FULL INFORMATION</h3>
<table>
<tr>
<th>Id</th>
<th>Trainee Name</th>
<th>Salary</th>
</tr>
<!-- traineeData: a list of trainee -->
<c:forEach items="${traineeData}"
var="trainee">
<tr>
<td>${trainee.getId()}</td>
<td>${trainee.getName()}</td>
<td>${trainee.getSalary()}</td>
</tr>
</c:forEach>
</table>
43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 18
Action tags (1/2)
 Action (<%action... %>
 JSP Actions lets you perform some action.
 Provide access to common tasks performed in a JSP:
• Including content from other resources.
• Forwarding the user to another page.
• Interacting with JavaBeans.
 Delimited by <jsp:action> and </jsp:action>.

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 19


Action tags (2/2)

Action Desc ription


<jsp:include> Dynamically includes another resource in a JSP. As the JSP executes,
the referenced resource is included and processed.
<jsp:forward> Forwards request processing to another JSP, servlet or static page. This
action terminates the current JSP’s execution.
<jsp:plugin> Allows a plug-in component to be added to a page in the form of a
browser-specific object or embed HTML element. In the case of a
Java applet, this action enables the downloading and installation of the
Java Plug-in, if it is not already installed on the client computer.
<jsp:param> Used with the include, forward and plugin actions to specify
additional name/value pairs of information for use by these actions.
JavaBean Manipulation
<jsp:useBean> Specifies that the JSP uses a JavaBean instance. This action specifies
the scope of the bean and assigns it an ID that scripting components can
use to manipulate the bean.
<jsp:setProperty> Sets a property in the specified JavaBean instance. A special feature of
this action is automatic matching of request parameters to bean
properties of the same name.
<jsp:getProperty> Gets a property in the specified JavaBean instance and converts the
result to a string for output in the response.

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 20


Include tag (1/3)
 Include action tag is used for including another resource
to the current JSP page.
 The included resource can be a static page in HTML, JSP page,
 We can also pass parameters and their values to the resource
which we are including.
 Syntax:
1) Include along with parameters.
<jsp:include page="Relative_URL_Of_Page">
<jsp:param ... />
<jsp:param ... />

</jsp:include>
2) Include of another resource without sharing parameters.
<jsp:include page="Relative_URL_of_Page" />

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 21


Include tag (2/3)
Code snippet
<html>
<body>
<div class="main_wrap">
<div class="header">
<jsp:include page="Header.jsp"></jsp:include>
</div>
<div class="container">
<div class="side-bar">
<jsp:include page=“SideBar.jsp"></jsp:include>
</div>
<div class="content">
<jsp:include page=“Order.jsp"></jsp:include>
</div>
</div>
</div>
</body> header
</html>

side-
bar

content

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 22


Include tag (3/3)
 Directives vs Actions:
1. Directives are used during translation phase (at translate time) while actions are used
during request processing phase (at request time).

JSP Include Directive JSP Include Action

2. If the included file is changed but not the JSP which is including it then the changes will
reflect only when we use include action tag. The changes will not reflect if you are using
include.
3. Syntax difference.
4. When using include action tag we can also pass the parameters to the included page by
using param action tag but in case of include directive it’s not possible.

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 23


Back to menu
Forward tag (1/2)
 Forwards request processing to another JSP, servlet or
static page. This action terminates the current JSP’s
execution.
 Request can be forwarded with or without parameter
 Syntax:
1) Forwarding along with parameters.
<jsp:forward page="display.jsp">
<jsp:param ... />
<jsp:param ... />

</jsp:forward>
2) Forwarding without parameters.
<jsp:forward page="Relative_URL_of_Page" />

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 24


Forward tag (2/2)
 Without passing parameters
<html>
<head>
<title>Forward tag</title>
</head>
<body>
<p align="center">My main JSP page</p>
<jsp:forward page="OtherPage.jsp"></jsp:forward>
</body>
</html>

 With passing parameters


<html>
<head>
<title>Forward tag</title>
</head>
<body>
<p align="center">My main JSP page</p>
<jsp:forward page="OtherPage.jsp">
<jsp:param name="name" value="Chaitanya" />
<jsp:param name="tutorialname" value="Jsp forward action" />
</jsp:forward>
</body>
</html>

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 25


Usebean tag (1/3)
 A JavaBean is a specially constructed Java class written in the Java.
JavaBeans component design conventions govern the properties of the class
and govern the public methods that give access to the properties.
Code snippet
package ctc.fr.atjb.bean;

public class Account implements Serializable {

private String emailAddress;


private String password;

public String getEmailAddress() {


return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public String getPassword() {
return password;
}

public void setPassword(String password) {


this.password = password;
}
}

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 26


Usebean tag (2/3)
Accessing JavaBeans:
 The useBean action declares a JavaBean for use in a JSP.
 The full syntax:
<jsp: useBean id="unique_name_to_identify_bean" class="package_name.class_name" />
<jsp:setProperty name="unique_name_to_identify_bean" property="property_name" />
<jsp:getProperty name="unique_name_to_identify_bean" property="property_name" />
 Example:
<html>
<head>
<title>useBean Example</title>
</head>
<body>
<jsp:useBean id="date" class="java.util.Date" />
<p>The date/time is <%= date %>
</body>
</html>

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 27


Usebean tag (3/3)

Code snippet
<jsp:useBean id="account" class="ctc.fr.atjb.bean.Account">
<jsp:setProperty property="emailAddress" name="account" />
<jsp:setProperty property="password" name="account" />
<h3>
Welcome,
<jsp:getProperty property="emailAddress" name="account" /><br>
</h3>
You have been successfully Logged in...
</jsp:useBean>

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 28


Practical time
 Sử dụng JSP Scripting Element, JavaBean xử lý màn hình
Login và Màn hình đăng ký như sau:

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 29


Section 3

JSP IMPLICIT OBJECTS

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 30


Implicit Objects
 There are some jsp implicit objects. These objects are created by the
web container that are available to all the jsp pages:
 All the implicit objects are divided by four variable scopes:
 Application:
• Objects owned by the container application
• Any servlet or JSP can manipulate these objects
 Page:
• Objects that exist only in page in which they are defined
• Each page has its own instance of these objects
 Request:
• Objects exist for duration of client request
• Objects go out of scope when response sent to client
 Session:
• Objects exist for duration of client’s browsing session
• Objects go out of scope when client terminates session or when session timeout
occurs

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 31


Implicit Objects
Implicit Object Description
Application Scope
application This javax.servlet.ServletContext object represents the container in which the JSP executes.
Page Scope
config This javax.servlet.ServletConfig object represents the JSP configuration options. As with servlets,
configuration options can be specified in a Web application descriptor.
exception This java.lang.Throwable object represents the exception that is passed to the JSP error page. This
object is available only in a JSP error page.
out This javax.servlet.jsp.JspWriter object writes text as part of the response to a request. This object is
used implicitly with JSP expressions and actions that insert string content in a response.
page This java.lang.Object object represents the this reference for the current JSP instance.
pageContext This javax.servlet.jsp.PageContext object hides the implementation details of the underlying servlet
and JSP container and provides JSP programmers with access to the implicit objects discussed in this
table.
response This object represents the response to the client. The object normally is an instance of a class that
implements HttpServlet­Response (package javax.servlet.http). If a protocol other than HTTP is used,
this object is an instance of a class that implements javax.servlet.ServletResponse.
Request Scope
request This object represents the client request. The object normally is an instance of a class that
implements HttpServlet­Request (package javax.servlet.http). If a protocol other than HTTP is used,
this object is an instance of a subclass of javax.servlet.Servlet­Request.
Session Scope
session This javax.servlet.http.HttpSession object represents the client session information if such a session
has been created. This object is available only in pages that participate in a session.

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 32


Implicit Objects
Application
 Application implicit object is an instance of javax.servlet.ServletContext.
 This object can be used to get initialization parameter from configuaration
file (web.xml).
 which means any attribute set by application implicit object would be available to
all the JSP pages.
 Methods:
 Object getAttribute(String attributeName)
 void setAttribute(String attributeName, Object object)
 void removeAttribute(String objectName)
 String getInitParameter(String paramname): It returns the value of Initialization
parameter for a given parameter name (in web.xml).
 String getServerInfo()
 URL getResource(String value)

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 33


Implicit Objects
Application
 Example:
 Cầu hình web.xml file:

 Get initialization parameter:


String driver = application.getInitParameter("driver");
String userName = application.getInitParameter("userName");
String password = application.getInitParameter("password");
String url = application.getInitParameter("url");

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 34


Implicit Objects
Application
 Example:

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


<html>
<head>
<title>Applcation object in JSP</title>
</head>
<body>
<%
Integer hitsCount = (Integer)
application.getAttribute("hitCounter");
if (hitsCount == null || hitsCount == 0) {
/* First visit */
hitsCount = 1;
} else {
/* return visit */
hitsCount += 1;
}
application.setAttribute("hitCounter", hitsCount);
%>
<center>
<p>
Total number of visits: <%=hitsCount%></p>
</center>
</body>
</html>

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 35


Back to menu
Implicit Objects
config
 Config Implicit object is used for getting configuration information for a
particular JSP page.
 application vs config implicit object:
 Using application implicit object we can get application-wide initialization
parameters.
 Using config we can get initialization parameters of an individual servlet
mapping.
 Methods:
 String getServletName() – It returns the name of the servlet which we
define in the web.xml file inside <servlet-name> tag.
 String getInitParameter(String paramname) – Same what we discussed in
application implicit object tutorial.

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 36


Implicit Objects
config
 Example:
<body>
<h3>CONFIG INFORMATION</h3>
<%
String sname = config.getServletName();
out.println("Servlet Name is: " + sname);
%>
</body>

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 37


Implicit Objects
out
 It’s an instance of javax.servlet.jsp.JspWriter.
 is used to write content to the client.
 Methods of OUT Implicit Object
 void print(): writes the value to the output screen (client browser).
 void println()
 void newLine()
 void clear()
 …
 Example:
<%
out.print("Out Implicit Object in JSP");
out.newLine();
out.println("This is will write content with a new line");
out.println("I'm just an another print statement");
%>

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 38


Implicit Objects
Page
 The page object represents the generated servlet instance itself, it is
same as the “this” keyword used in a java class.
 Example:
<html>
<head>
<title>Page Object</title>
</head>
<body>
<table>
<tr>
<td>Class name:</td>
<td><%=page.getClass().getName()%></td>
</tr>
<tr>
<td>Package name:</td>
<td><%=page.getClass().getPackage()%></td>
</tr>
</table>
</body>
</html>

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 39


Implicit Objects
PageContext
 It is an instance of javax.servlet.jsp.PageContext.
 Using this object you can find attribute, get attribute, set attribute and
remove attribute at any of the below levels:
 JSP Page – scope: PAGE_CONTEXT
 HTTP Requests - scope: REQUEST_CONTEXT
 HTTP Session – scope: SESSION_CONTEXT
 Application Level – scope: APPLICATION_CONTEXT
 Methods:
 Object findAttribute (String AttributeName).
 Object getAttribute (String AttributeName, int Scope).
 void removeAttribute(String AttributeName, int Scope).
 void setAttribute(String AttributeName,Object AttributeValue, int Scope)

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 40


Implicit Objects
PageContext
 Login page: asking user to enter login details.
 Code Snippets:

<html>
<head>
<title>User Login Page - Enter Details</title>
</head>
<body>
<form action="Validation.jsp" method="post">
<table>
<tr>
<td>Enter User - Id:</td>
<td><input type="text" size="30px" name="uid">
</td>
</tr>
<tr>
<td>Enter Passord:</td>
<td><input type="password" size="30px"
name="upass"> </td>
</tr>
<tr>
<td colspan="2" align="right">
<input type="submit" value="Submit">
</td>
</tr>
</table>
</form>
</body>
</html>
43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 41
Implicit Objects
PageContext
 Validation page: set attribute

<html>
<head>
<title>Validation JSP Page</title>
</head>
<body>
<%
String id = request.getParameter("uid");
String pass = request.getParameter("upass");
pageContext.setAttribute("UName", id,
PageContext.SESSION_SCOPE);
pageContext.setAttribute("UPassword", pass,

PageContext.SESSION_SCOPE);
%>
</body>
</html>

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 42


Implicit Objects
PageContext
 DisplayPageContext page:
<html>
<head>
<title>Displaying User Details</title>
</head>
<body>
<%
String username = (String) pageContext.getAttribute("UName", PageContext.SESSION_SCOPE);
String userpassword = (String) pageContext.getAttribute("UPassword",
PageContext.SESSION_SCOPE);
%>
<h3> Hello, <%=username%></h3>
</body>
</html>
 PageContext Forward:
<%
pageContext.removeAttribute("UName");
pageContext.forward("DisplayPageContext.jsp");
%>

After
Before removeAttribute
removeAttribute

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 43


Implicit Objects
request

 The JSP request is an implicit object of type HttpServletRequest i.e.


created for each jsp request by the web container.
 It can be used to get request information such as:
• parameter, header information, remote address, server name, server port, content type,
character encoding etc.

 It can also be used to set, get and remove attributes from the jsp request
scope.
 Example: create a form to get information

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 44


Implicit Objects
request
 Code Snippets:

<form action="view-stock.jsp" method="post">


<table cellspacing="5px">
<tr>
<td>Stock Code:</td>
<td><input type="text" size="20px" name="stockCode"></td>
</tr>
<tr>
<td>Stock Name:</td>
<td><input type="text" size="20px" name="stockName"></td>
</tr>
<tr>
<td>Description:</td>
<td><textarea rows="3px" cols="30" name="des"></textarea></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="Submit" style="border-radius: 10px; width:
80px">
<input type="reset" value="Clean" style="border-radius: 10px; width:
80px">
</td>
</tr>
</table>
</form>

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 45


Implicit Objects
request
 Code Snippets:
<html>
<head>
<title>View Stock</title>
</head>
<body>
<h3>STOCK INFORMATION</h3>
<table>
<tr>
<td>Stock code:</td>
<td><%=request.getParameter("stockCode")%></td>
</tr>
<tr>
<td>Stock name:</td>
<td><%=request.getParameter("stockName")%></td>
</tr>
<tr>
<td>Description:</td>
<td><%=request.getParameter("des")%></td>
</tr>
</table>
</body>
</html>

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 46


Implicit Objects
response
 In JSP, response is an implicit object of type HttpServletResponse.
 The instance of HttpServletResponse is created by the web container for each jsp
request.

 It can be used to add or manipulate response such as redirect response to


another resource, send error etc.
 Methods:
 void sendRedirect(String address) – It redirects the control to a new JSP page. For
e.g.
• Example: response.sendRedirect("http://beginnersbook.com");

 void addCookie(Cookie cookie) – This method adds a cookie to the response. The
below statements would add 2 Cookies Author and Siteinfo to the response.
• Example: response.addCookie(Cookie Author); response.addCookie(Cookie Siteinfo);

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 47


Implicit Objects
response
 Methods:
 void sendError(int status_code, String message) – It is used to send error
response with a code and an error message.
• For example: response.sendError(404, "Page not found error");
 Example: verify stock information
<html>
<head>
<title>View Stock</title>
</head>
<body>
<h3>STOCK INFORMATION</h3>
<%
String stockCode = request.getParameter("stockCode");
String stockName = request.getParameter("stockName");
if (stockCode == "") { response.sendRedirect("StockInfo.jsp");
} else if ((stockCode.equals("5656") && (stockName
.equals("Colum-Co")))) {
response.sendRedirect(“Success.jsp");
} else
response.sendRedirect("StockError.jsp");
%>
</body>
</html>

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 48


Implicit Objects
response
 In JSP, response is an implicit object of type HttpServletResponse.
 The instance of HttpServletResponse is created by the web container for
each jsp request.
 It can be used to add or manipulate response such as redirect
response to another resource, send error etc.
 Example:

<%
String stockCode = request.getParameter("stockCode");
if (stockCode == "")
response.sendRedirect("StockInfo.jsp");
else {

%>

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 49


Back to menu
Implicit Objects
session
 This javax.servlet.http.HttpSession object represents the client session
information if such a session has been created.
 Methods:
 setAttribute(String, object): This method is used to save an object in
session by assigning a unique string to the object.
 getAttribute(String name): The object stored by setAttribute method is
fetched from session using getAttribute method.
 removeAttribute(String name): The objects which are stored in session can
be removed from session using this method. Pass the unique string identifier
as removeAttribute’s method.
 getAttributeNames: It returns all the objects stored in session. Basically, it
results in an enumeration of objects.

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 50


Implicit Objects
session
 Code Snippets:
<html>
<body bgcolor="#ffffff">
<%
// Open connection
String user_name = request.getParameter("userName");
String password = request.getParameter("passWord");
try {
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM dbo.[User] WHERE [user_account] = '“ +
user_name
+ "' AND [user_password] = '“ + password + "'");
if (rs.next())
{
session.setAttribute("login_fail", "success");
session.setAttribute("user_name", user_name);
response.sendRedirect("Index2.jsp");
}
else
{
session.setAttribute("login_fail", "fail");
response.sendRedirect("Login.jsp");
}
} catch (Exception ex) {
ex.printStackTrace();
}
%>
</body>
</html>

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 51


Section 4

EXPRESSION LANGUAGE

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 52


Expression Language (EL) in JSP
 The Expression Language (EL) simplifies the accessibility
of data stored in the Java Bean component, and other
objects like request, session, application etc.
 There are many implicit objects, operators and reserve
words in EL.
 Syntax:
 ${ expression }

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 53


Implicit Objects in Expression Language (EL)
Implicit Objects Usage
pageScope it maps the given attribute name with the value set in the page scope

requestScope it maps the given attribute name with the value set in the request scope

sessionScope it maps the given attribute name with the value set in the session scope

applicationScope it maps the given attribute name with the value set in the application scope

param it maps the request parameter to the single value

paramValues it maps the request parameter to an array of values

header it maps the request header name to the single value

headerValues it maps the request header name to an array of values

cookie it maps the given cookie name to the cookie value

initParam it maps the initialization parameter

pageContext it provides access to many objects request, session etc.

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 54


Expression Language (EL) in JSP
 EL Param Example:
index.jsp

1.<form action="process.jsp">
2. Enter Name:<input type="text" name="name" />
3. <input type="submit" value="go"/>
4.</form>

process.jsp

1.Welcome, ${ param.name }

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 55


Expression Language (EL) in JSP
 EL sessionScope example:

index.jsp

1.<h3>welcome to index page</h3>


2.<%
3. session.setAttribute("user","sonoo");
4.%>
5.
6.<a href="process.jsp">visit</a>

process.jsp

1.Value is $
{ sessionScope.user }

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 56


Reserve words in EL
 There are many reserve words in the Expression Language.
They are as follows:

lt le gt ge
eq ne true false
and or not instanceof
div mod empty null

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 57


Summary
◊ JSP Introduction
◊ JSP Scripting Element
◊ JSP Implicit Objects
◊ Expression language

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 58


Thank you

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher


59
59
Academy - Internal Use

You might also like