Title: CS320 Web and Internet Programming JSP Scripting Elements and Page Directives
1CS320 Web and Internet ProgrammingJSP Scripting
Elements and Page Directives
- Chengyu Sun
- California State University, Los Angeles
2Java Server Page (JSP)
- Why?
- Its tedious to generate HTML using println()
- Separate presentation from processing
- How?
- Java code embedded in HTML documents
3HelloJSP1.jsp
lt!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN"gt ltHTMLgt ltHEADgtltTITLEgtHello JSP
1lt/TITLEgtlt/HEADgt ltBODYgtA JSP without J or
S.lt/BODYgt lt/HTMLgt
4HelloJSP2.jsp
lt!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN"gt ltHTMLgt ltHEADgtltTITLEgtJSP Hello
Worldlt/TITLEgtlt/HEADgt ltBODYgtHello World on lt new
java.util.Date() gt. lt/BODYgt lt/HTMLgt
5How Does JSP Work?
convert
compile
execute
JSP
Servlet
ByteCode
automatically done by server
- Look under CATALINA_HOME/work/Catalina/localhost/
context_name
6Some Simple Observations about the JSP/Servlets
- In package org.apache.jsp
- _jspService() handles everything
- replaces service() in HttpServlet
- What happened to doGet(), doPost(), ...??
- HTML text ? out.write(...)
7Pre-defined Variables
- request, response, out
- session, application
- config, pageContext
- page
The same request, response, session etc. that are
used in servlets see the Servlet API
documentation for what you can do with them.
8JSP Components
- HTML template text
- Code elements of Java
- Scripting elements
- Directives
- Beans
- Expression language
- Custom tag libraries
9Comments
- lt-- Hidden Comments --gt
- lt!-- Output (HTML) Comments --gt
10JSP Expressions
- lt Java expression gt
- Whats an expression??
lt expression gt in JSP
out.write( expression ) in _jspService()
11Example Add.jsp
- Add two integer parameters and display the sum
12JSP Scriptlets
- lt Java code gt
- All code goes inside _jspService()
13Example Add.jsp Again
- Add the code to validate the parameters
14Another Scriptlet Example
lt if( Math.random() lt 0.5) gt ltH1gtHave a
ltIgtnicelt/Igt day!lt/H1gt lt else gt ltH1gtHave a
ltIgtlousylt/Igt day!lt/H1gt lt gt
15JSP Declarations
- lt! class variables or methods gt
- All code goes outside _jspService()
16Example RequestCounter.jsp
- Initialize a counter as a class variable
- Increment the counter each time the JSP is
requested
17JSP Scripting Elements
- JSP Expressions
- JSP Scriptlets
- JSP Declarations
18Directives
- Affect the overall structure of the JSP
- lt_at_ type attrvalue ... gt
- Three type of directives
- page
- include
- taglib
19Some Page Directives
lt_at_ page importjava.util., java.util.zip.
gt lt_at_ page contentTypetext/html gt lt_at_ page
pageEncodingShift_JIS gt lt_at_ page
sessionfalse gt lt-- default is true --gt
- isELIgnored, errorPage, isErrorPage