Java Server Pages JSP - PowerPoint PPT Presentation

1 / 83
About This Presentation
Title:

Java Server Pages JSP

Description:

Allowing web server to launch a program on the host machine ... a dynamic scripting capability for web pages ... Provide a front door to the enterprise's Java ... – PowerPoint PPT presentation

Number of Views:2552
Avg rating:3.0/5.0
Slides: 84
Provided by: selabIec
Category:
Tags: jsp | front | hosting | java | page | pages | server | web

less

Transcript and Presenter's Notes

Title: Java Server Pages JSP


1
Java Server Pages (JSP)
2
Generating dynamic content page
  • The most common way is CGI
  • Allowing web server to launch a program on the
    host machine
  • perform the necessary task and to communicate the
    result back to the web server.
  • Required loading/unloading of application each
    time.
  • Used interpreted languages usually.
  • Problem of CGI
  • Multiple users generate multiple programs
  • Heavy RAM/CPU requirements
  • Load and Unload time substantial

3
The technology we needed
  • Working on any web or application server
  • Separating the application logic from the
    appearance of the page
  • Allowing fast development and testing
  • Simplifying the process of developing interactive
    web-based applications

4
Alternatives
  • ASPs Active Server Pages
  • Microsoft technology (proprietary)
  • relies on COM architecture, bound to Windows
  • PHP
  • open source
  • available on Windows, Linux, other platforms
  • include scripting language commands (including
    range of function calls) in HTML
  • good database support

5
Alternatives Servlet
  • Write programs in Java that inherit from
    Servlet which can communicate with the web
    server
  • Extend HTTP Server,
  • Full access to Java APIs
  • Benefits
  • Conceivably faster since is partially compiled
    and hence its easier to interpret.
  • Load the JVM once (cache repeatedly loaded
    applets in memory too)
  • Platform independence
  • Problems (no MVC)
  • no separation between content and presentation
  • handle requests to database (data manipulation)
  • manage the overall work (controlling)
  • write output back to web client (presentation)

6
(No Transcript)
7
HTTP Requests Response
  • Client makes HTTP request
  • Request is resolved to Servlet
  • Container
  • creates servlet
  • invokes init()
  • creates request and response objects
  • invokes service()
  • Sevlet interact with response
  • Container replies to HTTP request
  • Container may
  • invoke destroy(), dispose servlet at anytime

8
A servlet example
  • public class HelloServlet extends HttpServlet
  • public void doGet(HttpServletRequest request,
  • HttpServletResponse response)
  • response.setContentType("text/plain")
  • PrintWriter out response.getWriter()
  • out.println("lthtmlgt")
  • out.println("Hello World!")
  • out.println("ltbrgt")
  • JspCalendar clock new JspCalender()
  • out.println("Today is")
  • out.println("ltulgt")
  • out.println("ltligtDay of month ")
  • out.println(clock.getDayofMonth())
  • out.println("ltligtYear ")
  • out.println(clock.getYear())
  • out.println("/ltulgt")
  • out.println("lt/htmlgt")

9
As a JSP page
  • lthtmlgt
  • Hello World!
  • ltbrgt
  • ltjspuseBean id"clock"
  • class"calendar.JspCalendar"gt
  • Today is
  • ltulgt
  • ltligtDay of monthltclock.getDayofMonth()gt
  • ltligtYear ltclock.getYear()gt
  • lt/ulgt
  • lt/htmlgt

10
JSP Basics
  • Contains Java or tag library code to help
    generate output for the page
  • Text format file
  • Looks much like a regular HTML page, but with
    active element sections
  • Essentially a form that other code helps fills in
  • Stored on the server
  • a dynamic scripting capability for web pages
  • A server side technology can't do any client
    side validation with it.
  • When the page is first requested, the JSP is
    compiled into a servlet form and executed.
  • Afterwards the JSP script exists as a compiled
    java byte-code (unless it is changed)

11
Why use JSP
  • JSPs isolate the presentation
  • separate processing from display of data
  • better implementation of model-view-controller
    (MVC) framework
  • The focus is on HTML.
  • Java and the JSP extensions assist in making the
    HTML more functional.
  • JSPs integrate well with other enterprise Java
    functionality
  • JDBC, Servlets, Java Beans, Enterprise Java
    Beans, others
  • JSP
  • Emphasize components
  • Provide a front door to the enterprises Java
    platform

12
(No Transcript)
13
Benefits of JSP
  • Easy and Rapid Web Development, Deployment and
    Maintenance
  • Emphasizing Reusable Components
  • Separating Content Generation from Presentation
  • Open Development and Widespread Industry Support
  • Platform Independence
  • Simplifying Page Development with Tags

14
How do JSPs Work
index.jsp
Servlet/JSP Server
checks
Browser
Forwards to
index.java
Generated Servlet
compiles
15
(No Transcript)
16
Model-1 Features
  • suitable for simple applications
  • separation of presentation from content
  • not be suitable for complex implementation
  • easily lead to an unclear definition of roles and
    allocation of responsibilities.

17
(No Transcript)
18
Model-2 Features
  • suitable for complex applications
  • clearest separation of presentation from content
  • clear definition of roles and responsibilities of
    the developments and page designers.
  • the downside of using the Model 2 approach is its
    complexity

19
JSP components
  • JSPs have one or more of two types of sections
  • 1) template text
  • HTML or other markup language
  • control the display format
  • 2) JSP element
  • Java code -or- tags from tag libraries
  • specify the data to be displayed

20
JSP Elements
  • 3 types
  • directive
  • information or step that is constant across
    requests
  • e.g. lt_at_ taglib gt
  • action
  • action based on information at time JSP is
    requested
  • standard or custom (e.g. JSP Standard Tag Library
    JSTL)
  • e.g. ltjspuseBeangt (standard) , ltcout gt
    (custom/JSTL)
  • scripting
  • action to include small piece of code based on
    information at time of request
  • e.g. lt out.println(Crust
    request.getParameterValue(Crust)) gt

21
Directives
  • lt-- a comment --gt - comment text
  • lt_at_ page gt - define page-dependent attributes
    re session tracking, error page, buffering, etc.
  • lt_at_ include gt - include a file (done when
    translating, not when executing)
  • lt_at_ taglib gt - declare a tag library
    containing actions that are used in the page

22
Page Directives
  • The page directive defines a number of page
    dependent attributes
  • lt_at_ page languageJava
  • extendsclassName
  • importimportList
  • session truefalse
  • buffernonesizekb
  • autoFlushtruefalse
  • isThreadSafetruefalse
  • errorPagexxx.html
  • isErrorPagetruefalse
  • gt

23
(No Transcript)
24
(No Transcript)
25
Example
  • Gotop
  • 4
  • page.jsp
  • Big5.jsp
  • MS950.jsp
  • Date.jsp
  • errorPage.jsp

26
Include Directive
  • The include directive is used to inline text
    and/or code at JSP page translation-time.
  • lt_at_ include filerelativeURL gt

27
Example
  • Gotop
  • 4
  • Include_html.jsp

28
Taglib directive
lt_at_ taglib prefix"tags" tagdir"/WEB-INF/tags"
gt lthtmlgt ltheadgt lttitlegtJSP 2.0 Examples -
Hello World Using a Tag Filelt/titlegt lt/headgt
ltbodygt lth1gtJSP 2.0 Examples - Hello World
Using a Tag Filelt/h1gt lthrgt ltpgtThis JSP
page invokes a custom tag that simply echos
"Hello, World!" The custom tag is generated
from a tag file in the /WEB-INF/tags
directory.lt/pgt ltpgtNotice that we did not need
to write a TLD for this tag. We just created
/WEB-INF/tags/helloWorld.tag, imported it using
the taglib directive, and used it!lt/pgt
ltbrgt ltbgtltugtResultlt/ugtlt/bgt
lttagshelloWorld/gt lt/bodygt lt/htmlgt
29
Example
  • jsp-examples
  • Hello World Tag

30
JSP Actions
  • The syntax for action elements is based on XML
  • they have a start tag, a body, and an end tag
  • The JSP specification includes some action types
    that are standard.
  • New action types are added using the taglib
    directive.

31
Standard Action Elements
  • ltjspuseBeangt - loading JavaBean
  • ltjspgetPropertygt - Displaying Dynamic Content,
    get a property value from a JavaBean and add to
    response
  • ltjspsetPropertygt - Initializing a Bean, set a
    JavaBean property value
  • ltjspincludegt - include response from servlet or
    JSP during request processing
  • ltjspforwardgt - forward processing of request to
    another servlet or JSP
  • ltjspparamgt - add a parameter value to a request
    handed off with jspinclude or jspforward
  • ltjspplugingt - generates HTML that contains
    browser-dependent elements needed to execute an
    applet with Java Plug-In software

32
Standard Actions
  • ltjspuseBeangt
  • Associates an instance of a bean to a variable to
    use with in the jsp page
  • ltjspuseBean idname scopepagerequestsession
    application classclassName typetypeNamegt
  • lt/jspuseBeangt

33
ltjspuseBeangt
  • id variable name to reference instance of class
  • scope
  • page javax.servlet.jsp.PageContext
  • Objects only accessible from within the page
  • request ServletRequest
  • Objects accessible in pages processing request
    where bean is created
  • session HttpSession
  • Objects accessible from user session
  • application ServletContext
  • Objects accessible in pages belonging to same
    application

34
Conti.
  • Class
  • Fully qualified class name that defines the
    implementation of the object
  • Type (optional)
  • Allows scripting variable to be cast to another
    type from implementation class, java casting
    rules apply.

35
ltjspsetPropertygt
  • Sets the value of properties in a bean
  • 4 cases
  • ltjspsetProperty name property /gt
  • ltjspsetProperty name property /gt
  • ltjspsetProperty name property
    paramName /gt
  • ltjspsetProperty name property
    value/gt

36
ltjspgetPropertygt
  • Gets the value of properties in a bean
  • ltjspgetProperty namebeanName
    propertypropertyName/gt
  • Name
  • Variable name as defined in useBean
  • Property
  • Name of the bean property to retrieve

37
Bean Example
  • lthtmlgt
  • lttitlegtRandom JSP Testlt/titlegt
  • ltbody bgcolorwhitegt
  • ltjspuseBean idrnd scopepage
    classrandom.NumberGenerator/gt
  • ltulgt
  • ltligtNext number is ltjspgetProperty namernd
    propertynextInt/gt
  • lt/ulgt
  • lt/bodygt
  • lt/htmlgt

38
Conti.
  • package random
  • import java.util.
  • public class NumberGenerator
  • Random rnd new Random()
  • public int getNextInt()
  • return rnd.nextInt()

39
Examples
  • Advjhtp1.adrotator.jsp
  • jsp-examples.cal.login.html

40
Cal1.jsp
Example JspCalendar
Cal2.jsp
41
ltjspincludegt
  • ltjspincludegt
  • Allows you to include resources in the same
    context as the current page
  • ltjspinclude pageurl flushtrue/gt
  • page
  • Relative url
  • flush
  • If true, buffer is flushed

42
Example
  • Gotop
  • 4
  • Jsp_include.jsp
  • News.jsp

43
ltjspforwardgt
  • ltjspforwardgt
  • Allows you to dispatch the request to a different
    page
  • ltjspforward pageurl/gt
  • Example
  • Advjhtp1
  • forward1.jsp ? forward2.jsp

44
ltjspparamgt
  • ltjspparamgt
  • Used to provide key/value information for
    ltjspincludegt, ltjspforwardgt, and ltjspplugingt
  • ltjspparam namename valuevalue/gt
  • Name and value are mandatory

45
ltjspplugingt
  • Creates HTML that contains OBJECT or EMBED
    constructs that result in Java Plugin download
    and execution of Applet
  • ltjspplugin typeapplet codeapplet.class
    codebase/htmlgt
  • ltjspfallbackgt
  • ltpgtCant display appletlt/pgt
  • lt/jspfallbackgt
  • lt/jspplugingt
  • Fallback is used if the plugin cannot be started

46
Scripting
  • Use directives to set stage
  • lt_at_ page languagejava importjava.util. gt
  • Several implicit objects
  • e.g. out javax.servlet.jsp.JspWriter
  • e.g. session javax.servlet.http.HttpSession
  • Add Java code
  • Using declarations, lt!.........gt.
  • With scriptlets, lt...........gt.
  • e.g. lt out.println(Crust
    request.getParameterValue(Crust)) gt
  • Expressions between lt.....gt.

47
Declarations Tag
  • Allows you to declare page wide variables and
    methods
  • lt! int counter 0 gt
  • lt! Vector beanList new Vector() gt

48
Scriptlet Tag
  • lt gt
  • Used to include small pieces of Java code
  • lt for(Enumeration e beanList.elements()
    e.hasMoreElements() )
  • UserBean uBean (UserBean) e.nextElement()
  • out.println( uBean.getUserName() )
  • gt

49
Expression Tag
  • lt gt
  • Accepts any Java expression, evaluates the
    expression, converts to a String, and displays.
  • lt counter gt
  • lt uBean.getUserName() gt
  • Short hand for
  • lt out.println( uBean.getUserName() ) gt

50
Example
  • Gotop
  • 4
  • 99.jsp
  • 99_html.jsp

51
Implicit Objects
  • Objects defined implicitly for use in scripting
    tags
  • request, response
  • pageContext
  • appcontext
  • session
  • out
  • in error pages exception

Example ltif(request.getParameter("first")nul
l) gt lt out.println(String) gt
52
(No Transcript)
53
(No Transcript)
54
Example
lt_at_ page import"hello.NameHandler" gt
ltjspuseBean id"mybean" scope"page

class"hello.NameHandler" /gt ltjspsetProperty
name"mybean" property"" /gt lthtmlgt
ltheadgtlttitlegtHello, Userlt/titlegtlt/headgt ltbody
bgcolor"ffffff" background"background.gif"gt ltta
ble border"0" width"700"gt lttrgt lttd
width"150"gt ltimg src"duke.waving.gif"gt lt/tdgt
lttd width"550"gt lth1gtMy name is Duke.
What's yours?lt/h1gt lt/tdgt lt/trgt
hellouser.jsp
55
lttrgt lttd width"150" nbsp lt/tdgt lttd
width"550"gt ltform method"get"gt
ltinput type"text" name"username" size"25"gt
ltbrgt ltinput type"submit"
value"Submit"gt ltinput type"reset"
value"Reset"gt lt/formgt lt/tdgt
lt/trgt lt/tablegt lt if (request.getParameter("userna
me") ! null ) gt lt_at_ include
file"response.jsp" gt lt
gt lt/bodygt lt/htmlgt
56
lttable border"0" width"700"gt lttrgt lttd
width"150"gt nbsp lt/tdgt lttd width"550"gt
lth1gtHello, ltjspgetProperty
name"mybean" property"username" /gt!
lt/h1gt lt/tdgt lt/trgt lt/tablegt
response.jsp
57
package hello public class NameHandler
private String username public
NameHandler() username null
public void setUsername(
String name ) username name
public String getUsername()
return username
namehandler.java
58
(No Transcript)
59
(No Transcript)
60
Custom Action Elements
  • Programmer can develop own actions to extend the
    JSP language
  • Example JSP Standard Tag Library (JSTL)
  • JSTL Expression Library (EL)
  • support expression evaluation
  • starts with , ends with
  • Other tag libraries now available
  • e.g. Jakarta taglib project
  • If cant find a tag library that meets your
    needs, can develop a new one

61
Expression language (EL)
62
EL - implicit object
63
Custom Tag Libraries
  • Custom-tag libraries
  • Encapsulates complex functionality for use in
    JSPs
  • Define custom tags
  • Used for creating dynamic content
  • Classes that implement interface Tag
  • Pacakge javax.servlet.jsp.tagext

64
Simple Custom Tag
lt-- taglib directive --gt lt_at_ taglib uri
"advjhtp1-taglib.tld" prefix "advjhtp1"
gt lthtml xmlns "http//www.w3.org/1999/xhtml"gt
ltheadgt lttitlegtSimple Custom Tag
Examplelt/titlegt lt/headgt ltbodygt
ltpgtThe following text demonstrates a custom
taglt/pgt lth1gt ltadvjhtp1welcome/gt
lt/h1gt lt/bodygt lt/htmlgt
customTagWelcome.jsp
65
lttaglibgt ltshortnamegtadvjhtp1lt/shortnamegt
lttaggt ltnamegtwelcomelt/namegt
lttagclassgt com.deitel.advjhtp1.js
p.taglibrary.WelcomeTagHandler
lt/tagclassgt lt/taglibgt
advjhtp1-taglib.tld
66
import java.io. // Java extension
packages import javax.servlet.jsp. import
javax.servlet.jsp.tagext. public class
WelcomeTagHandler extends TagSupport //
Method called to begin tag processing public
int doStartTag() throws JspException
// attempt tag processing try //
obtain JspWriter to output content
JspWriter out pageContext.getOut()
out.print( "Welcome to JSP Tag Libraries!" )
// rethrow IOException to JSP
container as JspException catch(
IOException ioException ) throw new
JspException( ioException.getMessage() )
return SKIP_BODY // ignore the
tag's body
67
Custom Tag with Attributes
  • Use attributes to customize functionality
  • Specify attributes for custom tags

lt-- taglib directive --gt lt_at_ taglib uri
"advjhtp1-taglib.tld" prefix "advjhtp1"
gt lthtml xmlns "http//www.w3.org/1999/xhtml"gt
ltheadgt lttitlegtSimple Custom Tag
Examplelt/titlegt lt/headgt ltbodygt ltpgtThe
following text demonstrates a custom taglt/pgt
lth1gt ltadvjhtp1welcome2 firstName
"Paul" /gt lt/h1gt lt/bodygt lt/htmlgt
customTagWelcome2.jsp
68
import java.io. import javax.servlet.jsp. impo
rt javax.servlet.jsp.tagext. public class
Welcome2TagHandler extends TagSupport
private String firstName "" // Method
called to begin tag processing public int
doStartTag() throws JspException try
JspWriter out
pageContext.getOut()
out.print( "Hello " firstName ",
ltbr /gtWelcome to JSP Tag Libraries!" )
// rethrow IOException to JSP
container as JspException catch(
IOException ioException ) throw new
JspException( ioException.getMessage() )
return SKIP_BODY // ignore the
tag's body // set firstName attribute
to the users first name public void
setFirstName( String username )
firstName username
69
Evaluating the Body of a Custom Tag
  • Custom tags
  • Particularly useful for processing element body
  • Example

guestBookLogin.jsp
70
lt_at_ taglib uri "advjhtp1-taglib.tld" prefix
"advjhtp1" gt lthtml xmlns "http//www.w3.org/19
99/xhtml"gt ltheadgt lttitlegtGuest
Listlt/titlegt ltstyle type "text/css"gt
body font-family tahoma,
helvetica, arial, sans-serif
table, tr, td, th text-align
center font-size .9em
border 3px groove padding 5px
background-color dddddd
lt/stylegt lt/headgt
guestBookLogin.jsp
71
ltbodygt ltp style "font-size 2em"gtGuest
Listlt/pgt lttablegt lttheadgt
ltth style "width 100px"gtLast namelt/thgt
ltth style "width 100px"gtFirst
namelt/thgt ltth style "width
200px"gtEmaillt/thgt lt/theadgt
lt-- guestlist custom tag --gt
ltadvjhtp1guestlistgt lttrgt
lttdgtlt lastName gtlt/tdgt
lttdgtlt firstName gtlt/tdgt lttdgt
lta href "mailtolt email gt"gt
lt email gtlt/agt
lt/tdgt lt/trgt
lt/advjhtp1guestlistgt lt/tablegt
lt/bodygt lt/htmlgt
This tag will be executed repeatedly until it
receives SKIP_BODY
guestBookLogin.jsp
72
lttaggt ltnamegtguestlistlt/namegt
lttagclassgt com.deitel.advjhtp1.jsp.taglib
rary.GuestBookTag lt/tagclassgt
ltteiclassgt com.deitel.advjhtp1.jsp.taglib
rary.GuestBookTagExtraInfo lt/teiclassgt
ltbodycontentgtJSPlt/bodycontentgt
ltinfogt Iterates over a list of GuestBean
objects lt/infogt lt/taggt
advjhtp1-taglib.tld
73
guestBookLogin.jsp
GuestBookTag
BodyTagSupport
doStartTag()
create guestData
if guestData ! null
processNextGuess
type of firstName?
Create a session object "firstName"
display "firstName"
74
TagSupport
doStartTag()
EVAL_BODY_INCLUDE
Execute body content
SKIP_BODY
SKIP_PAGE
EVAL_PAGE
doEndTag()
release
release
stop this page
Continue this page
75
BodyTagSupport
doStartTag()
EVAL_BODY_TAG
getBodyContent() doInitBody()
SKIP_BODY
Execute body content
EVAL_BODY_TAG
SKIP_PAGE
EVAL_PAGE
doEndTag()
doAfterBody()
release
release
stop this page
Continue this page
76
Container
SKIP_BODY
SKIP_BODY
doStartTag
doAfterBody
EVAL_BODY_TAG
EVAL_BODY_TAG
processNextGuest()
GuestBookTag ExtraInfo()
GuestBookTag.java
77
Tag library example-4
  • gotop.12.Myfont.jsp

In this program, MyFont.java has
implemented doEndTag, why?
78
Tag library example-5
  • gotop.12.Filter.jsp

79
File Upload
  • Use com.oreilly.servlet.MultipartRequest

ltform name"Form1" enctype"multipart/form-data"
method"post" action"Fil2.jsp"gt ltpgt ???? 1
ltinput type"file" name"File1" size"20"
maxlength"20"gt lt/pgt
MultipartRequest multi new MultipartRequest(requ
est , saveDirectory , maxPostSize )

upload
directory max size
80
Conti.
  • Example gotop.7.file.htm

81
Java Mail
  • Use mail.jar and activation.jar

lt_at_ page language"java" import"java.util.,java.
io." gt lt_at_ page import"javax.mail." gt lt_at_
page import"javax.mail.internet." gt lt_at_ page
import"javax.activation." gt
// ??????Mail ???????????? java.util.Properties
props System.getProperties()
props.put("mail.host",mailserver)
props.put("mail.transport.protocol","smtp")
82
// ????Session ?? javax.mail.Session
mailSession javax.mail.Session.getDefaultInst
ance(props,null) Message msg new
MimeMessage(mailSession) // ??????????
msg.setFrom(new InternetAddress(From)) //
????????????? address InternetAddress.parse(to
,false) msg.setRecipients(Message.RecipientType
.TO, address) // ???????, ??, MIME Type
msg.setSubject(Subject) msg.setSentDate(new
Date()) msg.setText(messageText) //
?? Transport.send(msg)
83
JavaMail sending mail with files
  • Use com.oreilly.servlet.MultipartRequest

File file new File(FileName)
// ????????,????????????
MimeBodyPart mbp1 new
MimeBodyPart() //
?????????? text/html ,?? HTML ??
mbp1.setContent(messageText.toString(),"text/html"
) // ????????
MimeBodyPart mbp2 new MimeBodyPart()
FileDataSource fds new FileDataSource(FileNa
me) mbp2.setDataHandler(new
DataHandler(fds))
mbp2.setFileName(fds.getName())
// ??????????,???????? Multipart mp
new MimeMultipart()
mp.addBodyPart(mbp1)
mp.addBodyPart(mbp2)
msg.setContent(mp)
Write a Comment
User Comments (0)
About PowerShow.com