Advanced Java Server Pages - PowerPoint PPT Presentation

About This Presentation
Title:

Advanced Java Server Pages

Description:

... request, HttpServletResponse response) throws ServletException, IOException ... catch(java.io.IOException e) throw new JspTagException('IO Error: ' e.getMessage ... – PowerPoint PPT presentation

Number of Views:135
Avg rating:3.0/5.0
Slides: 34
Provided by: fredri9
Category:

less

Transcript and Presenter's Notes

Title: Advanced Java Server Pages


1
Advanced Java Server Pages
  • An more detailed look at JSPs

2
Custom methods in JSPs
  • Just as Servlets, JSPs have methods for
    initialization end destruction
  • JspInit() corresponds to init() in Servlets
  • JspDestroy corresponds to destroy() in Servlets
  • Both JspInit() and JspDestroy() can implemented
    in your JSPs, i.e you can override the base class
  • Think before you use them
  • If you need the init and destroy, is it really a
    JSP you should be writing? Probably not!

3
Servlets and JSPs
  • Servlets should be used as front ends for JSPs
  • The Servlet should handle the control logic
  • The Servlet can initialize Beans that the JSP can
    use
  • The Beans can talk to databases, EJBs and so on
  • This is basic MVC
  • But how is this done?

4
Before the explanation
  • Assume there is a Bean, DataBean that fetches
    records from a database
  • The records are fetched to the bean with the
    fetch() method
  • The records are returned from the bean with the
    getRecords() method

5
The Servlet part
  • Create the Bean instance
  • Call your methods on the Bean
  • Add the bean to the request or the session
  • Get a RequestDispatcher
  • Use the forward() method in the RequestDispatcher

6
The Servlet part, using the request
  • public void doGet(HttpServletRequest request,
    HttpServletResponse response) throws
    ServletException, IOException
  • DataBean db new DataBean()
  • db.fetch()
  • request.setAttribute("dbBean", db)
  • RequestDispatcher rd request.getRequestDispa
    tcher("jsppage.jsp")
  • rd.forward(request, response)

7
The Servlet part, using the session
  • public void doGet(HttpServletRequest request,
    HttpServletResponse response) throws
    ServletException, IOException
  • HttpSession ses request.getSession()
  • DataBean db new DataBean()
  • db.fetch()
  • ses.setAttribute("dbBean", db)
  • RequestDispatcher rd request.getRequestDispa
    tcher("jsppage.jsp")
  • rd.forward(request, response)

8
The JSP part
  • The JSP uses the ltjspuseBean ..gt to define the
    bean, but it should not result in a new instance.
  • The instance that was added in the Servlet is
    used
  • The same scope in ltjspuseBean gt as in the
    Servlet (request and session in our examples)
  • The same id in ltjspuseBean gt as the name in the
    Servlet
  • The JSP uses ltjspgetProperty gt to call methods
    in the Bean

9
The JSP part, with request
  • ltjspuseBean iddbBean" classbeans.DataBean"
    scoperequest"gt
  • Error, the bean should have been created in
    the servlet!
  • lt/jspuseBeangt
  • ltjspgetProperty namedbBean propertyrecords
    /gt
  • lt-- propertyrecords will look for
    getRecords() in the bean --gt

10
The JSP part, with session
  • ltjspuseBean iddbBean" classbeans.DataBean"
    scopesession"gt
  • Error, the bean should have been created in
    the servlet!
  • lt/jspuseBeangt
  • ltjspgetProperty namedbBean propertyrecords
    /gt
  • lt-- propertyrecords will look for
    getRecords() in the bean --gt

11
Custom Tags
  • We dont want Java code in our JSPs
  • The built in tags ltjspxxx gt is quite limited in
    functionality
  • What we need is a way to extend the built in tags
    with our own
  • Custom Tags

12
Custom Tags
  • Custom Tags separates the logic from the
    presentation even more that ltjspuseBean gt
  • In our BookShop for example, the JSP with a book
    list and the shopping cart can consist of two
    lines of code
  • ltbookshopbookList /gt
  • ltbookshopshoppingCart /gt

13
Two types of Custom Tags
  • Simple Tag (Tag)
  • A tag with or without arguments
  • Doesnt use the Tag body
  • Implements javax.servlet.jsp.tagext.Tag
  • Body Tag
  • With or without arguments
  • Evaluate the body of the tag
  • ltbookshopaTaggtThis is the bodylt/bookshopaTaggt
  • Implements javax.servlet.jsp.tagext.BodyTag

14
Simple Tag, an example
  • import javax.servlet.jsp.
  • import javax.servlet.jsp.tagext.
  • public class HelloWorldTag implements Tag
  • private PageContext pageContext
  • private Tag parent
  • /
  • Constructor
  • /
  • public HelloWorldTag()
  • super()
  • /
  • Method called at start of Tag
  • _at_return either a EVAL_BODY_INCLUDE or a
    SKIP_BODY

15
Simple Tag, an example
  • /
  • Method Called at end of Tag
  • _at_return either EVAL_PAGE or SKIP_PAGE
  • /
  • public int doEndTag() throws javax.servlet.jsp.J
    spTagException
  • try
  • pageContext.getOut().write("Hello World!")
  • catch(java.io.IOException e)
  • throw new JspTagException("IO Error "
    e.getMessage())
  • return EVAL_PAGE
  • /
  • Method called to releases all resources

16
Simple Tag, an example
  • / Method used by the JSP container to set the
    parent of the Tag
  • _at_param parent, the parent Tag
  • /
  • public void setParent(final javax.servlet.jsp.ta
    gext.Tag parent)
  • this.parentparent
  • / Method for retrieving the parent
  • _at_return the parent
  • /
  • public javax.servlet.jsp.tagext.Tag getParent()
  • return parent

17
Simple Tag
  • All methods in the interface must be implemented!
  • All work is done in the doStartTag() and
    doEndTag()
  • The doStartTag() is called at the start of the
    tag
  • The doEndTag() is called at the start of the tag
  • Instead of implementing Tag, extend TagSupport
  • A helper class included in the package that has
    implementation for all required methods. Just
    implement the one that you will use!

18
Simple Tag, with TagSupport (complete)
  • import javax.servlet.jsp.
  • import javax.servlet.jsp.tagext.
  • public class HelloWorldTag extends TagSupport
  • private PageContext pageContext
  • private Tag parent
  • /
  • Method Called at end of Tag
  • _at_return either EVAL_PAGE or SKIP_PAGE
  • /
  • public int doEndTag() throws javax.servlet.jsp.J
    spTagException
  • try
  • pageContext.getOut().write("Hello World!")
  • catch(java.io.IOException e)

19
Simple Tags
  • In other words, use TagSupport!
  • The HelloTag implements our simple tag
  • Custom Tags are defined in a Tag Library
    Descriptor (tld)

20
Tag Library Descriptor
  • lttaglibgt
  • lttlibversiongt1.0lt/tlibversiongt
  • ltjspversiongt1.1lt/jspversiongt
  • ltshortnamegtmtlt/shortnamegt
  • lturigt/mytaglt/urigt
  • ltinfogtMy first Tag librarylt/infogt
  • lttaggt
  • ltnamegthelloWorldlt/namegt
  • lttagclassgttags.HelloWorldTaglt/tagclassgt
  • ltbodycontentgtemptylt/bodycontentgt
  • ltinfogtA Hello world Taglt/infogt
  • lt/taggt
  • lt/taglibgt

21
Web.xml
  • The tld is referenced in web.xml
  • Web.xml binds a tag library to a web application
  • lttaglibgt
  • lttaglib-urigtmytagslt/taglib-urigt
  • lttaglib-locationgt/WEB-INF/taglib.tldlt/taglib-loca
    tiongt
  • lt/taglibgt

22
Using your tag
  • The uri specified in web.xml is used in the JSP
  • lt_at_ taglib uri"mytags" prefix"mt" gt
  • At the start of the page
  • ltmthelloTag /gt
  • Prints Hello World

23
Parameterized tags
  • Both Tag and BodyTag can take parameters
  • ltmthelloTag nameFredrik /gt
  • Just as in JavaBeans, use a set-method and a
    member variable
  • private String name
  • public void setName(_name) name_name

24
Parameterized tags
  • import javax.servlet.jsp.
  • import javax.servlet.jsp.tagext.
  • public class HelloNameTag extends TagSupport
  • private String name
  • public void setName(String _name)name_name
  • public int doEndTag() throws javax.servlet.jsp.Jsp
    TagException
  • try
  • pageContext.getOut().write("Hello
    name)
  • catch(java.io.IOException e)
  • throw new JspTagException("IO Error "
    e.getMessage())
  • return EVAL_PAGE

25
TLD for HelloName
  • lttaggtltnamegthellolt/namegtlttagclassgtHelloNameTaglt/t
    agclassgtltbodycontentgtemptylt/bodycontentgtltinfogtA
    Hello Taglt/infogtltattributegtltnamegtnamelt/namegtltre
    quiredgtfalselt/requiredgtltrtexprvaluegtfalselt/rtexpr
    valuegtlt/attributegt
  • lt/taggt

26
Using the parameterized tag
  • ltmthello nameFredrik/gt

27
BodyTag
  • Just as with Tag, there are a lot of methods to
    write if implementing BodyTag
  • There is a helper class call BodyTagSupport just
    as with TagSupport
  • BodyTag is often used for looping over some result

28
Body Tag
  • package se.upright.education.uu.pvk.tags
  • import javax.servlet.jsp.
  • import javax.servlet.jsp.tagext.
  • public class LoopTag extends BodyTagSupport
  • private int iterations 5
  • /
  • Method used by the JSP container to set the
    parameter Name.
  • /
  • public void setIterations(int _iterations)
  • this.iterations_iterations
  • /

29
Body Tag
  • public int doAfterBody() throws JspTagException
  • if(iterationsgt1)
  • //decrease the number of iterations left to
    do
  • iterations--
  • return EVAL_BODY_TAG
  • else
  • return SKIP_BODY

30
Body Tag
  • /
  • Method Called at end of tag
  • _at_return either EVAL_PAGE or SKIP_PAGE
  • /
  • public int doEndTag() throws JspTagException
  • try
  • if(bodyContent ! null) // Check if we even
    entered the body
  • bodyContent.writeOut(bodyContent.getEnclos
    ingWriter())
  • catch(java.io.IOException e)
  • throw new JspTagException("IO Error "
    e.getMessage())
  • return EVAL_PAGE

31
Body Tag tld
  • lttaggt
  • ltnamegtlooplt/namegt
  • lttag-classgtse.upright.education.uu.pvk.tag
    s.LoopTaglt/tag-classgt
  • ltbody-contentgtJSPlt/body-contentgt
  • ltattributegt
  • ltnamegtiterationslt/namegt
  • ltrequiredgttruelt/requiredgt
  • ltrtexprvaluegttruelt/rtexprvaluegt
  • lt/attributegt
  • lt/taggt

32
Using Body Tag
  • ltuuloop iterations"10"gt
  • Looping ltbr /gt
  • lt/uuloopgt

33
Next Time
  • Java Standard Tag Library
  • A Tag Library with common functionallity
  • XML
  • XSLT
Write a Comment
User Comments (0)
About PowerShow.com