1 Java Server Pages (JSP) - Sharad Ballepu. 2 Servlets & JSPs Agenda Introduction JSP Elements...

41
1 ava Server Pages (JSP - Shar

Transcript of 1 Java Server Pages (JSP) - Sharad Ballepu. 2 Servlets & JSPs Agenda Introduction JSP Elements...

Page 1: 1 Java Server Pages (JSP) - Sharad Ballepu. 2 Servlets & JSPs Agenda Introduction JSP Elements Implicit Objects Tag Libraries JSP Actions Error Handling.

1

Java Server Pages (JSP) - Sharad Ballepu

Page 2: 1 Java Server Pages (JSP) - Sharad Ballepu. 2 Servlets & JSPs Agenda Introduction JSP Elements Implicit Objects Tag Libraries JSP Actions Error Handling.

2

Servlets & JSPsAgenda

• Introduction • JSP Elements• Implicit Objects• Tag Libraries• JSP Actions• Error Handling• Demo

Java Server Pages (JSP)

Page 3: 1 Java Server Pages (JSP) - Sharad Ballepu. 2 Servlets & JSPs Agenda Introduction JSP Elements Implicit Objects Tag Libraries JSP Actions Error Handling.

3

Introduction – What is JSP

• JSP Stands for Java Server Pages

• Presents dynamic content to users

• Handles the presentation logic in an MVC architecture

Co

ntain

er

servlet

JSP

request

response

HelperObjects

(business logic)

(presentation logic)

Bu

siness

Tier

Page 4: 1 Java Server Pages (JSP) - Sharad Ballepu. 2 Servlets & JSPs Agenda Introduction JSP Elements Implicit Objects Tag Libraries JSP Actions Error Handling.

4

Introduction – JSP v/s Servlet

Servlets JSP

Handles dynamic data

Handles business logic Handles presentation logic

Lifecylce methods init() : can be overridden service() : can be overridden destroy() : can be overridden

Lifecylce methods jspInit() : can be overridden _jspService() : cannot be overridden jspDestroy() : can be overridden

Html within javaout.println(“<htrml><body>”);out.println(“Time is” + new Date());out.println(“</body></html>”);

Java within html<html><body>Time is <%=new Date()%></body></html>

Runs within a Web Container

How is JSP different / similar to Servlet?

Page 5: 1 Java Server Pages (JSP) - Sharad Ballepu. 2 Servlets & JSPs Agenda Introduction JSP Elements Implicit Objects Tag Libraries JSP Actions Error Handling.

5

Introduction – JSP is a Servlet

• In the end, a JSP is just a Servlet

0010 00011100 10010001 0011

Import javax.servlet.

HttpServlet.*JSP Servlet

MyJsp.jsp MyJsp_jsp.java MyJsp_jsp.class MyJsp_jsp Servlet

writes

Is translated to Compiles to Is loaded andInitialized as

Page 6: 1 Java Server Pages (JSP) - Sharad Ballepu. 2 Servlets & JSPs Agenda Introduction JSP Elements Implicit Objects Tag Libraries JSP Actions Error Handling.

6

Introduction – Comments

• JSP Comments <%-- {CODE HERE} --%> Does not show the comments on the page Does not show the comments in page source Can only be used outside JSP Elements

• HTML Comments <!– {CODE HERE} --> Does not show the comments on the page Shows the comments in page source Can only be used outside JSP Elements

• Single line Comments // {CODE HERE} When put outside JSP Elements, shows comments on the page & source When put inside Scriptlets/Declarations, does not show on page & source Can be used inside scriptlets/declarations and outside JSP Elements

Page 7: 1 Java Server Pages (JSP) - Sharad Ballepu. 2 Servlets & JSPs Agenda Introduction JSP Elements Implicit Objects Tag Libraries JSP Actions Error Handling.

7

JSP Elements – Intro

JSP Declarations :: Code that goes outside the service method

JSP Scriptlets :: Code that goes within the service method

JSP Expressions :: Code inside expressions is evaluated

JSP Directives :: Commands given to the JSP engine

• Need to write some Java in your HTML?

• Want to make your HTML more dynamic?

Page 8: 1 Java Server Pages (JSP) - Sharad Ballepu. 2 Servlets & JSPs Agenda Introduction JSP Elements Implicit Objects Tag Libraries JSP Actions Error Handling.

8

JSP Elements - Declarations

• What are declarations?– Whatever goes inside the “<%!{JAVA_HERE}%>” tags is called a

declaration– Everything you write in a declarations goes outside the service method– Treat them as instance methods and instance variables

• What do you declare in declarations?– You can declare methods and variables in declarations

• Why do you need declarations?– You have any variable that needs to be shared across different

requests.– You have repeated common code in you jsp, declare it in a method.

• Example<%! int instanceVar = 10; %>

Page 9: 1 Java Server Pages (JSP) - Sharad Ballepu. 2 Servlets & JSPs Agenda Introduction JSP Elements Implicit Objects Tag Libraries JSP Actions Error Handling.

9

JSP Elements - Declarations

Request 2

Request 3

Request 1

Service1 Service2 Service3

Declarations

Page 10: 1 Java Server Pages (JSP) - Sharad Ballepu. 2 Servlets & JSPs Agenda Introduction JSP Elements Implicit Objects Tag Libraries JSP Actions Error Handling.

10

JSP Elements - Scriptlets

• What are declarations?– Whatever goes inside the “<%{JAVA_HERE}%>” tags is called

a scriptlet– Everything you write in a scriptlets goes in the service method– Treat variables in scriptlets as method/local variables

• What do you put in scriptlets?– Business logic in JSPs are put in scriptlets. Set of java

statements

• Why do you need scriptlets?– Need to perform some small business logic (if logic is complex,

do in java)– Need to perform some basic validations

• Example<% int localVar = 10; %>

Page 11: 1 Java Server Pages (JSP) - Sharad Ballepu. 2 Servlets & JSPs Agenda Introduction JSP Elements Implicit Objects Tag Libraries JSP Actions Error Handling.

11

JSP Elements - Expressions

• What are expressions?– Whatever goes inside the “<%={JAVA_HERE}%>” tags is called

an expression– Code inside expressions is evaluated, and output is displayed– Whatever is put inside expressions should evaluate to a value

• What do you put in scriptlets?– Variables or methods that return some values

• Why do you need scriptlets?– Need to print some text onto the page

• Example<%= localVar %>

Page 12: 1 Java Server Pages (JSP) - Sharad Ballepu. 2 Servlets & JSPs Agenda Introduction JSP Elements Implicit Objects Tag Libraries JSP Actions Error Handling.

12

JSP Elements - Example

<html><head><title>JSP Elements Example</title> </head> <body> <%! int userCnt = 0; %>

<% String name = "Sharad"; userCnt++; %> <table> <tr><td> Welcome <%=name%>. You are user number <%=userCnt%> </td></tr> </table> </body></html>

Expressions

Declarations

Scriptlets

Page 13: 1 Java Server Pages (JSP) - Sharad Ballepu. 2 Servlets & JSPs Agenda Introduction JSP Elements Implicit Objects Tag Libraries JSP Actions Error Handling.

13

JSP Elements - Directives

• What are directives?– Whatever goes inside the “<%@{DIRECTIVES}%>” tags is

called a directive– Directives gives pre-processing commands to the JSP Engine.– Everything in directives are processed before JSP is translated

to Servlet

• What do you put in directives?– Processing commands to the JSP Engine.

• Why do you need directives?– To incorporate certain additional features into the JSP– Modifying the Servlet behaviour generated from the JSP– Include other html/jsp files in the JSP.– Provide tag libraries

Example<%@ page import=“java.util.ArrayList” %>

Page 14: 1 Java Server Pages (JSP) - Sharad Ballepu. 2 Servlets & JSPs Agenda Introduction JSP Elements Implicit Objects Tag Libraries JSP Actions Error Handling.

14

Directives – page directive

• Any number of the pre-defined attributes can be added to the page directive

<%@ page import = “{IMPORTED_CLASSES}” contentType = “{CONTENT_TYPE}” isThreadSafe = “{true/false} session = “{true/false}” buffer = “{BUFFER_SIZE}” autoflush = “{true/false}” extends = “{EXTENDS_FROM_PAGE}” info = “{PAGE_INFO”} errorPage = “{ERROR_PAGE_NAME}” isErrorPage = “{true/false}” language = “{LANGUAGE}”

Page 15: 1 Java Server Pages (JSP) - Sharad Ballepu. 2 Servlets & JSPs Agenda Introduction JSP Elements Implicit Objects Tag Libraries JSP Actions Error Handling.

15

Directives – include directive

• Including other page content into your JSP

<%@ include file = {PAGE_URL_TO_INCLUDE} %>• Includes files at translation time

• If included file is modified, the main jsp needs to be recompiled

Main page

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

<%@ include file =“footer.jsp"/><table><tr> <td>Contact Details</td><tr></table>

Hello <%=userName%>

header.jsp

footer.jspmain.jsp

Page 16: 1 Java Server Pages (JSP) - Sharad Ballepu. 2 Servlets & JSPs Agenda Introduction JSP Elements Implicit Objects Tag Libraries JSP Actions Error Handling.

16

Directives – taglib directive

• Providing output based on common custom logic

<%@ taglib uri=“{TLD_FILE}" prefix=“{PREFIX}" %>

• Components involved in tag libraries

Tag handler class Common custom logic and HTML generation

Descriptor configuration file Directive’s properties mapping information

taglib directive Used in JSPs to use the tag handler functionality

Page 17: 1 Java Server Pages (JSP) - Sharad Ballepu. 2 Servlets & JSPs Agenda Introduction JSP Elements Implicit Objects Tag Libraries JSP Actions Error Handling.

17

taglib directive – high-level overview

<%@ taglib uri=“sharmanjTags” prefix=“sharmanj” %>…..< sharmanj:txtBox length=“10“ name=“userName”/>….. test.jsp

<web-app> <taglib> <taglib-uri>sharmanjTags</taglib-uri> <taglib-location> sharmanj-taglib.tld </taglib-location> </taglib></web-app>

web.xml

<tag> <name>txtBox</name> <tagclass>TxtBoxTag</tagclass> <bodycontent>EMPTY</bodycontent> <attribute> <name>name</name> <required>true</required> …. </attribute>…</tag>

public class TxtBoxTag extends TagSupport { public int doStartTag() { …. }}

TxtBoxTag.java

sharmanj-taglib.tld

Page 18: 1 Java Server Pages (JSP) - Sharad Ballepu. 2 Servlets & JSPs Agenda Introduction JSP Elements Implicit Objects Tag Libraries JSP Actions Error Handling.

18

Implicit Objects - Introduction

• Set of predefined objects readily available for use.

– out: JspWriter

– request: HttpRequest

– response: HttpResponse

– session: HttpSession

– config: ServletConfig

– application: ServletContex

– page: JSP page

– pageContext: Special object

Page 19: 1 Java Server Pages (JSP) - Sharad Ballepu. 2 Servlets & JSPs Agenda Introduction JSP Elements Implicit Objects Tag Libraries JSP Actions Error Handling.

19

Implicit Objects - Example

<html> <head> <title>JSP Implicit objects Example</title> </head> <body> <% if (“YES”.equals(request.getAttribute(“SCOPE”))) { out.println(“REQUEST”); } else { if (“YES”.equals(session.getAttribute(“SCOPE”))) { out.println(“SESSION”);

} else { out.println(“NONE”);

} } %> </body></html>

Page 20: 1 Java Server Pages (JSP) - Sharad Ballepu. 2 Servlets & JSPs Agenda Introduction JSP Elements Implicit Objects Tag Libraries JSP Actions Error Handling.

20

Implicit Objects – out

• An instance of JspWriter

• Writes statements to the page

• The java way to display text on the webpage

• Displaying dynamic data

Page 21: 1 Java Server Pages (JSP) - Sharad Ballepu. 2 Servlets & JSPs Agenda Introduction JSP Elements Implicit Objects Tag Libraries JSP Actions Error Handling.

21

Implicit Objects – request

• Instance of HttpServletRequest

• Use the attributes stored in request object for display /basic validations in JSP

Servlet JSP

Helper Object

(a = 10)

Uses helper object

Forwards request to JSP

a = 10

request.setAttribute(“a”, “10”)Servlet JSP

Page 22: 1 Java Server Pages (JSP) - Sharad Ballepu. 2 Servlets & JSPs Agenda Introduction JSP Elements Implicit Objects Tag Libraries JSP Actions Error Handling.

22

Implicit Objects – response

• Instance of HttpServletResponse

• Send the response back to the client (HTML in most of the cases)

JSP1

Send response to client

JSP1Redirect to JSP2 JSP2

Send response to client

response.sendRedirect(“url”);

Page 23: 1 Java Server Pages (JSP) - Sharad Ballepu. 2 Servlets & JSPs Agenda Introduction JSP Elements Implicit Objects Tag Libraries JSP Actions Error Handling.

23

Implicit Objects – session

• Instance of HttpSession

• Retrieve and set the session attributes in JSP

• Remember the client across multiple requests

Web App CLIENT

Request 1

Request 1

Response1

Response2

SESSION

Page 24: 1 Java Server Pages (JSP) - Sharad Ballepu. 2 Servlets & JSPs Agenda Introduction JSP Elements Implicit Objects Tag Libraries JSP Actions Error Handling.

24

Implicit Objects – config and application

• config - Instance of ServletConfig• Application – instance of ServletContext

JSP 1

Servlet Context

Servlet Config Servlet ConfigServlet Config Servlet Config

JSP 1JSP 1JSP 1

Page 25: 1 Java Server Pages (JSP) - Sharad Ballepu. 2 Servlets & JSPs Agenda Introduction JSP Elements Implicit Objects Tag Libraries JSP Actions Error Handling.

25

Implicit Objects – page

Main page<table><tr> <td>Contact Details</td><tr></table>

Hello <%=userName%><jsp:include page=“/header.jsp"/>

<jsp:include page=“/footer.jsp"/>

header.jsp

footer.jspmain.jsp

Page 26: 1 Java Server Pages (JSP) - Sharad Ballepu. 2 Servlets & JSPs Agenda Introduction JSP Elements Implicit Objects Tag Libraries JSP Actions Error Handling.

26

Implicit Objects – pageContext

request

page

application

session

Lea

st v

isib

le t

o m

ost

vis

ible

pageContext

Page 27: 1 Java Server Pages (JSP) - Sharad Ballepu. 2 Servlets & JSPs Agenda Introduction JSP Elements Implicit Objects Tag Libraries JSP Actions Error Handling.

27

JSP Actions

<jsp:include>

<jsp:forward>

<jsp:param>

<jsp:useBean>

<jsp:getProperty>

<jsp:setProperty>

• Special tags which provides special features

• The container handles these tags in a special way

• Addresses certain common functionalities

• Achieve functionality with less code, and more standard way

Page 28: 1 Java Server Pages (JSP) - Sharad Ballepu. 2 Servlets & JSPs Agenda Introduction JSP Elements Implicit Objects Tag Libraries JSP Actions Error Handling.

28

JSP Actions - <jsp:include>

<jsp:include page="{PAGE_TO_INCLUDE}" flush="true" />

Definition:Includes a page at the given location in the main page

Syntax:

Page 29: 1 Java Server Pages (JSP) - Sharad Ballepu. 2 Servlets & JSPs Agenda Introduction JSP Elements Implicit Objects Tag Libraries JSP Actions Error Handling.

29

JSP Actions – Include Action v/s Include Directive

Include Directive Include Action

Translation time Run time

Copies the included file References to the included file

For static content For dynamic content

Cannot pass parameters Can pass parameters

Page 30: 1 Java Server Pages (JSP) - Sharad Ballepu. 2 Servlets & JSPs Agenda Introduction JSP Elements Implicit Objects Tag Libraries JSP Actions Error Handling.

30

JSP Actions - <jsp:forward>

<jsp:forward page=“{PAGE_TO_FORWARD}" />

Definition:Forwards the request to the given page

Syntax:

Page 31: 1 Java Server Pages (JSP) - Sharad Ballepu. 2 Servlets & JSPs Agenda Introduction JSP Elements Implicit Objects Tag Libraries JSP Actions Error Handling.

31

JSP Actions - <jsp:param>

<jsp:include page="{PAGE_TO_INCLUDE}" flush="true" > <jsp:param name=“{parameterName}” value="{paramValue}" /></jsp:include>

Definition:Pass parameters to the included/forwarded page

Syntax:

<jsp:forward page="{PAGE_TO_FORWARD}" flush="true" > <jsp:param name=“{parameterName}” value="{paramValue}" /></jsp:forward>

Page 32: 1 Java Server Pages (JSP) - Sharad Ballepu. 2 Servlets & JSPs Agenda Introduction JSP Elements Implicit Objects Tag Libraries JSP Actions Error Handling.

32

JSP Actions - <jsp:useBean>

Servlet JSP

bean

How can I use that bean?

getId();setId(..)getName()setName(…)

request.setAttribute(“userBean”, userBean”) <jsp:useBean …./>

Page 33: 1 Java Server Pages (JSP) - Sharad Ballepu. 2 Servlets & JSPs Agenda Introduction JSP Elements Implicit Objects Tag Libraries JSP Actions Error Handling.

33

JSP Actions - <jsp:useBean>

<jsp:useBean id=“{beanInstanceName}" scope="page|request|session|application" class=“{package.class}" type=“{package.class}" beanName=" {package.beanName}”></ jsp:useBean>

Definition:Instantiate a bean class, use bean properties, and set property values

Syntax:

UserBean ub = new UserBean();

Page 34: 1 Java Server Pages (JSP) - Sharad Ballepu. 2 Servlets & JSPs Agenda Introduction JSP Elements Implicit Objects Tag Libraries JSP Actions Error Handling.

34

JSP Actions - <jsp:getProperty>

<jsp:getProperty name=“{beanInstanceName}" property= “{propertyName}">

Definition:Gets property values of a Bean

Syntax:

Page 35: 1 Java Server Pages (JSP) - Sharad Ballepu. 2 Servlets & JSPs Agenda Introduction JSP Elements Implicit Objects Tag Libraries JSP Actions Error Handling.

35

JSP Actions - <jsp:setProperty>

<jsp:setProperty name=“{beanInstanceName}" property= "*" | property="propertyName" param=“{parameterName}" value="{paramValue}" } />

Definition:Sets property values in a Bean

Syntax:

Page 36: 1 Java Server Pages (JSP) - Sharad Ballepu. 2 Servlets & JSPs Agenda Introduction JSP Elements Implicit Objects Tag Libraries JSP Actions Error Handling.

36

JSP Actions – useBean

<jsp:useBean id=“userBean" scope="session“ class=“com.sharmanj.UserBean" >

<jsp:setProperty name=“userBean” property=“userName” value=“Sharad”/> </ jsp:useBean>

<jsp:getProperty name=“userBean" property=“userName" />

Page 37: 1 Java Server Pages (JSP) - Sharad Ballepu. 2 Servlets & JSPs Agenda Introduction JSP Elements Implicit Objects Tag Libraries JSP Actions Error Handling.

37

Error Handling – Types of errors

• Errors in java code in scriptlets

handle errors in try/catch block

may occur at runtime

• Errors in HTML

adhere to the HTML rules

can be caught during testing

Page 38: 1 Java Server Pages (JSP) - Sharad Ballepu. 2 Servlets & JSPs Agenda Introduction JSP Elements Implicit Objects Tag Libraries JSP Actions Error Handling.

38

Error Handling

Why is error handling important in JSPs?

Page 39: 1 Java Server Pages (JSP) - Sharad Ballepu. 2 Servlets & JSPs Agenda Introduction JSP Elements Implicit Objects Tag Libraries JSP Actions Error Handling.

39

Error Handling – Error page

• Error pages come to the rescue

<%@page isErrorPage="true" %> <html> <head> <title>My Error Page</title> </head> <body> We are sorry, the page you are trying to access is currently not available. Please try after some time </body></html>

Page 40: 1 Java Server Pages (JSP) - Sharad Ballepu. 2 Servlets & JSPs Agenda Introduction JSP Elements Implicit Objects Tag Libraries JSP Actions Error Handling.

40

Error Handling

• Specify error page in your main page

<%@page errorPage=“errPage.jsp" %><html> <head> <title>This is the main page</title> </head> <body> ………………….. …………………..

…………………… ……………………

// ERROR CODE GOES HERE

…………………. …………………. </body></html>

• Specify error page in web.xml

<web-app>…………….……………

<error-page> <exception-type>com.a.myExp</exception-type> <location>/error.jsp</location> </error-page>

<error-page> <error-code>404</error-code> <location>/errorServlet</location> </error-page>

………………..……………….</web-app>

Page 41: 1 Java Server Pages (JSP) - Sharad Ballepu. 2 Servlets & JSPs Agenda Introduction JSP Elements Implicit Objects Tag Libraries JSP Actions Error Handling.

41

Thanks