JSP Java Server Pages Representation and Management of
- Slides: 105
JSP – Java Server Pages Representation and Management of Data on the Internet
Introduction
What is JSP Good For? • Servlets allow us to write dynamic Web pages - Easy access to request, session and context data - Easy manipulation of the response (cookies, etc. ) - And lots more. . . • It is not convenient to write and maintain long static HTML using Servlets out. println("<h 1>Bla Bla</h 1>" + "bla bla bla" + "lots more here. . . ")
JSP Idea • Use HTML for most of the page • Write Servlet code directly in the HTML page, marked with special tags • The server automatically translates a JSP page to a Servlet class and the latter is actually invoked - In Tomcat 5. 0 you can find the generated Servlet code under $CATALINA_BASE/work/
Relationships • Servlets: HTML code is printed from Java code • JSP: Java code is embedded in HTML code Java HTML Java
Example <HTML> <HEAD> <TITLE>Hello World</TITLE> </HEAD> <BODY> <H 2><I><%= new java. util. Date() %></I></H 2> <H 1>Hello World</H 1> </BODY> </HTML> Tomcat 5. 0 Generated Servlet
JSP Limitations and Advantages • JSP can only do what a Servlet can do • Easier to write and maintain HTML • Easier to separate HTML from code • Can use a "reverse engineering technique": create static HTML and then replace static data with Java code
Basic JSP Elements
Elements in a JSP file • HTML code: <html-tag>content</html-tag> • HTML comment: <!-- comment --> • JSP Comment: <%-- comment --%> • Expressions: <%= expression %> • Scriptlets: <% code %> • Declarations: <%! code %> • Directives: <%@ directive attribute="value" %> • Actions: discussed later
JSP Expressions • A JSP expression is used to insert Java values directly into the output • It has the form: <%= expression %> , where expression can be a Java object, a numerical expression, a method call that returns a value, etc. . . • For example: <%= new java. util. Date() %> <%= "Hello"+" World" %> <%= (int)(100*Math. random()) %>
JSP Expressions • A JSP Expression is evaluated • The result is converted to a string • The string is inserted into the page • This evaluation is performed at runtime (when the page is requested), and thus has full access to information about the request, the session, etc. . .
Expression Translation <H 1>A Random Number</H 1> <%= Math. random() %> public void _jsp. Service(Http. Servlet. Request request, Http. Servlet. Response response) throws java. io. IOException, Servlet. Exception {. . . response. set. Content. Type("text/html"); . . . out. write("<H 1>A Random Number</H 1>rn"); out. print( Math. random() ); out. write("rn"); . . . }
Predefined Variables (Implicit Objects) • The following predefined variables can be used: - request: the Http. Servlet. Request - response: the Http. Servlet. Response - session: the Http. Session associated with the request - out: the Print. Writer (a buffered version of type Jsp. Writer) used to fill the response content - application: The Servlet. Context • These variables and more will be discussed in details
<HTML> <HEAD> <TITLE>JSP Expressions</TITLE></HEAD> <BODY> <H 2>JSP Expressions</H 2> <UL> <LI>Current time: <%= new java. util. Date() %> <LI>Your hostname: <%= request. get. Remote. Host() %> <LI>Your session ID: <%= session. get. Id() %> <LI>The <CODE>test. Param</CODE> form parameter: <%= request. get. Parameter("test. Param") %> </UL> </BODY> </HTML>
JSP Scriplets • JSP scriptlets let you insert arbitrary code into the Servlet service method ( _jsp. Service ) • Scriptlets have the form: <% Java Code %> • The code is inserted verbatim into the service method, according to the location of the scriplet • Scriptlets have access to the same automatically defined variables as expressions
Scriptlet Translation <%= foo() %> <% bar(); %> public void _jsp. Service(Http. Servlet. Request request, Http. Servlet. Response response) throws Servlet. Exception, IOException {. . . response. set. Content. Type("text/html"); . . . out. print(foo()); bar(); . . . }
An Interesting Example Scriptlets don't have to be complete code blocks: <% if (Math. random() < 0. 5) { %> You <B>won</B> the game! <% } else { %> You <B>lost</B> the game! <% } %> if (Math. random() < 0. 5) { out. write("You <B>won</B> the game!"); } else { out. write("You <B>lost</B> the game!"); }
JSP Declarations • A JSP declaration lets you define methods or members that get inserted into the Servlet class (outside of all methods) • It has the following form: <%! Java Code %> • For example: <%! private int some. Field = 5; %> <%! private void some. Method(. . . ) {. . . } %> • It is usually of better design to define methods in a separate Java class. . .
Declaration Example • Print the number of times the current page has been requested since the server booted (or the Servlet class was changed and reloaded): <%! private int access. Count = 0; %> <%! private synchronized int inc. Access() { return ++access. Count; } %> <H 1>Accesses to page since server reboot: <%= inc. Access() %> </H 1>
public class service. Count_jsp extends. . . implements. . . throws. . . { private int access. Count = 0; private synchronized int inc. Access() { return ++access. Count; } public void _jsp. Service(Http. Servlet. Request request, Http. Servlet. Response response) throws Servlet. Exception, IOException { . . . out. write("<H 1>Accesses to page since server reboot: "); out. print(inc. Access()); . . . }
jsp. Init and jsp. Destroy • In JSP pages, like regular Servlets, sometimes want to use init and destroy • It is illegal to use JSP declarations to override init or destroy, since they (usually) are already implemented by the generated Servlet • Instead, override the methods jsp. Init and jsp. Destroy - The generated servlet is guaranteed to call these methods from init and destroy respectively - The standard versions of jsp. Init and jsp. Destroy are empty (placeholders for you to override)
JSP Directives • A JSP directive affects the structure of the Servlet class that is generated from the JSP page • It usually has the following form: <%@ directive attribute="value" %> • Multiple attribute settings for a single directive can be combined: <%@ directive attribute 1="value 1". . . attribute. N="value. N" %> • Two types discussed in this section: page and include
page-Directive Attributes • import attribute: A comma separated list of classes/packages to import <%@ page import="java. util. *, java. io. *" %> • content. Type attribute: Sets the MIME-Type of the resulting document (default is text/html) <%@ page content. Type="text/plain" %> • Note that instead of using the content. Type attribute, you can write <% response. set. Content. Type("text/plain"); %>
More page-Directive Attributes • session="true|false" - use a session? • buffer="sizekb|none" - Specifies the content-buffer size (out) • error. Page="url " - Defines a JSP page that handles uncaught exceptions - The page in url must have true in the page-directive: • is. Error. Page="true|false" - The variable exception holds the exception thrown by the calling JSP
show. Table. A. jsp <HTML> <HEAD> <TITLE>Reading From Database</TITLE></HEAD> <BODY> <%@ page import="java. sql. *" %> <%@ page error. Page="error. Page. jsp" %> <% Class. for. Name("oracle. jdbc. driver. Oracle. Driver"); Connection con = Driver. Manager. get. Connection("jdbc: oracle: thin: " + "snoopy/snoopy@sol 4: 1521: stud"); Statement stmt = con. create. Statement(); Result. Set rs = stmt. execute. Query("Select * from a"); Result. Set. Meta. Data md = rs. get. Meta. Data(); int col = md. get. Column. Count(); %>
<TABLE border="2"> <% while (rs. next()) { %> <TR> <% for (int i = 1 ; i <= col ; i++) { %> <TD><%= rs. get. String(i) %></TD> <% } %> </TR> <% } %> </TABLE> </BODY> </HTML>
error. Page. jsp <HTML> <HEAD> <TITLE>Reading From Database</TITLE></HEAD> <BODY> <%@ page is. Error. Page="true" %> <h 1>Oops. There was an error when you accessed the database. </h 1> <h 2>Here is the stack trace: </h 2> <font color="red"> <pre> <% exception. print. Stack. Trace(new Print. Writer(out)); %> </pre></font> </BODY> </HTML>
Table A exists!
Table A does not exist!
The include Directive • This directive lets you include files at the time the JSP page is translated into a Servlet • The directive looks like this: <%@ include file="url" %> • JSP content can affect main page • In Tomcat 5. x, generated Servlet is updated when included files change (unlike old versions. . . )
<HTML> <HEAD> <TITLE>Including JSP</TITLE></HEAD> <BODY> Here is an interesting page. Bla, Bla. <%@ include file="Access. Count. jsp" %> </BODY> </HTML> Bla. jsp <hr> Access. Count. jsp Page Created for Dbi Course. Email us <a href="mailto: dbi@cs. huji. ac. il">here</a>. <%! private int access. Count = 0; %> Accesses to page since server reboot: <%= ++access. Count %>
out. write("<HTML> rn"); out. write("<HEAD> <TITLE>Including JSP</TITLE></HEAD>rn"); out. write("<BODY>rn"); out. write("Here is an interesting page. rn"); out. write("Bla, Bla. rn"); out. write("<hr>rn"); out. write("Page Created for Dbi Course. Email us rn"); out. write("<a href="mailto: dbi@cs. huji. ac. il">here</a>. rn"); out. write("Accesses to page since server reboot: rn"); out. print( ++access. Count ); out. write("rn"); out. write("</BODY>rn"); out. write("</HTML> ");
Writing JSP in XML (and vice versa) • We can replace the JSP tags with XML tags that represent - Expressions - Scriptlets - Declarations - Directives
<%= Expression %> <jsp: expression> Expression </jsp: expression> <% Code %> <jsp: scriptlet> Code </jsp: scriptlet> <%! Declaration %> <jsp: declaration> Declaration </jsp: declaration> <%@ Directive %> <jsp: directive. type Attribute="value"/>
<? xml version="1. 0" encoding="UTF-8"? > <jsp: root xmlns: jsp="http: //java. sun. com/JSP/Page" version="2. 0"> <numbers> <jsp: scriptlet> for(int i=1; i< =10; ++i) { </jsp: scriptlet> <number> <jsp: expression> i </jsp: expression> </number> <jsp: scriptlet> } </jsp: scriptlet> </numbers> </jsp: root>
Variables in JSP
Implicit Objects • As seen before, some useful variables, like request and session are predefined • These variables are called implicit objects • Implicit objects are defined in the scope of the service method - Can these be used in JSP declarations? • Implicit objects are part of the JSP specifications
The objects request and response • request and response are the Http. Servlet. Request and Http. Servlet. Response arguments of the service method • Using these objects, you can: • Read request parameters • Set response headers • etc. (everything we learned in Servlet lectures)
The object out • This is the Writer used to add write output into the response body • This object implements the interface Jsp. Writer, which supports auto-flush • Recall that you can adjust the buffer size, or turn buffering off, through use of the buffer attribute of the page directive
The object page • Simply a synonym for (Object)this • page is not very useful in JSP pages • It was created as a placeholder for the time when the scripting language could be something other than Java
The object page. Context • page. Context is a new object introduced by JSP • This object encapsulates use of server-specific features (e. g. higher performance Jsp. Writers) • Access server-specific features through this class rather than directly, so your code will conform to JSP spec. and not be server dependent • This object is also used to store page-scoped Java Beans (discussed later)
The object session • This is the Http. Session object associated with the request • If the session attribute in the page directive is turned off (<%@ page session="false" %>) then this object is not available • Recall that a session is created by default
The object config • This is the Servlet. Config of the page, as received in the init() method • Remember: Contains Servlet specific initialization parameters • Later, we will study how initialization parameters are passed to JSP pages in Tomcat • You can get the Servlet. Context from config
The object application • This is the Servlet. Context as obtained via get. Servlet. Config(). get. Context() • Remember: - The Servlet. Context is shared by all Web-application Servlets (including ones generated from JSP) - Getting and setting attributes is with get. Attribute and set. Attribute of Servlet. Context - You can use this object to get application-wide initialization parameters
Review: Variable Scope
Review: Variable Scope
Review: Variable Scope
Review: Variable Scope
Servlet Package and Helper Classes • The generated Servlet has a named package • In Tomcat, this package is: org. apache. jsp • In Java, you cannot use classes from the default package (i. e. with no package declaration) from a named package! • Therefore, helper classes used by JSP pages must have a named package
JSP Actions
Actions • JSP actions use constructs in XML syntax to control the behavior of the Servlet engine • Using actions, you can - dynamically insert a resource content - forward the user to another page - reuse Java Beans and custom tags - briefly discussed later
The forward Action • jsp: forward - Forwards the requester to a new resource <jsp: forward page="{relative. URL|<%= expression %>}"> <jsp: param name="parameter. Name" value="{parameter. Value | <%= expression %>}" /> * </jsp: forward> • This action is translated to an invocation of the Request. Dispatcher
The include Action • jsp: include - Include a resource content at run time <jsp: include page="{relative. URL|<%= expression %>}" flush="true| false" > <jsp: param name="parameter. Name" value="{parameter. Value | <%= expression %>}" />* </jsp: include> • This action is also translated to an invocation of the Request. Dispatcher
include Directive vs. Action • When a file is included using the include directive, the file itself is included verbatim into the JSP code, prior to the Servlet generation • When a resource is included using the include action, the generated Servlet uses the dispatcher to include its content at runtime • Question: using which of the latter options can the included element change the HTTP headers or status?
JSP Life Cycle
JSP Life Cycle The following table describes the life cycle of JSP generated Servlet in details:
JSP Life Cycle JSP page Request Request #1 #2 #3 #4 #5 #6 Yes No No No Yes No Yes No Yes Yes Yes translated into servlet loaded into server's memory init (or Page modified instantiated and Server restarted Servlet Page first written Servlet compiled equivalent) called do. Get (or equivalent) called Written by Marty Hall. Core Servlets & JSP book: www. coreservlets. com
JSP Translation • When the JSP file is modified, JSP is translated into a Servlet - Application need not be reloaded when JSP file is modified - In Tomcat 5. 0, translation is done even if included files (through the include directive) are modified • Server does not generate the Servlet class after startup, if the latter already exists - Generated Servlet acts just like any other Servlet
init() and destroy() • init() of the generated Servlet is called every time the Servlet class is loaded into memory and instantiated • destroy() of the generated Servlet is called every time the generated Servlet is removed • The latter two happen even if the reason is modification of the JSP file
Thread Synchronization • After the Servlet is generated, one instance of it services requests in different threads, just like any other Servlet • In particular, the service method (_jsp. Service) may be executed by several concurrent threads • Thus, like Servlets, JSP code should deal with concurrency
JSP in Tomcat 5. 0
Tomcat 5. 0 Generated Servlet <HTML> <HEAD> <TITLE>Hello World</TITLE> </HEAD> <BODY> <H 2><I><%= new java. util. Date() %></I></H 2> <H 1>Hello World</H 1> </BODY> </HTML> Tomcat 5. 0 Generated Servlet
Generated Servlet Hierarchy (Tomcat 5. 0 Implementation) Sun Specifications Apache Implementation different packages Generated Servlet
Implementation vs. Specification • JSP files should conform to JSP specifications and be container independent • For example, JSP files that assume extension of Http. Servlet will compile and run correctly under Tomcat, but may fail to compile under other containers • The implicit object page. Context exists for this reason
JSP Initial Parameters • Like Servlets, initial parameters can be passed to JSP files using the <servlet> element of the application configuration file web. xml • Use the sub-element <jsp-file> instead of the sub -element <servlet-class> • A <servlet-mapping> is also needed - Use the JSP file as the <url-pattern>
<web-app> <context-param> <param-name>db. Login</param-name> <param-value>snoopy</param-value> </context-param> <param-name>db. Password</param-name> <param-value>snoopass</param-value> </context-param>
<servlet> <servlet-name>Param. Page</servlet-name> <jsp-file>/param. Page. jsp</jsp-file> <init-param> <param-name>table. Name</param-name> <param-value>users</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>Param. Page</servlet-name> <url-pattern>/init. Param. jsp</url-pattern> </servlet-mapping> </web-app>
<HTML> <HEAD><TITLE>JSP initial parameters</TITLE></HEAD> <BODY> <H 1>Hello</H 1> <H 2>I should use the table <I><%= config. get. Init. Parameter("table. Name") %></I>. </H 2> <H 2>To access the Database, I should use the login <I><%= application. get. Init. Parameter("db. Login") %></I> and the password <I><%= application. get. Init. Parameter("db. Password") %></I>. </H 2> </BODY> </HTML>
Appendix 1: Java Beans in JSP
Motivation • Software components (e. g. objects, data structures, primitives) are extensively used in Web applications • For example: - Service local variables - Attributes forwarded in requests - Session attributes, like users information - Application attributes, like access counters
Motivation • Standard actions are used to manipulate components: declaration, reading from the suitable context, setting of new values (according to input parameters), storing inside the suitable context, etc. • Java Beans provide a specification for automatic handling and manipulation of software components in JSP (and other technologies. . . )
Java Beans: The Idea • Wrap your data, in a standard fashion, inside a Java class (Java Bean) • Use special JSP actions to access and manipulate the bean • Use special action attributes to specify the properties of the bean, like its scope
Example 1: Access Counter In the following example, we use a Bean to maintain an access counter for requests to the pages
package dbi; Bean must reside in a package public class Counter. Bean { private int counter; Bean is created by an empty constructor public Counter. Bean() { counter = 0; } public int get. Counter() { return counter; } public void set. Counter(int i) { counter = i; } get. Counter and set. Counter define the property counter public void increment() { ++counter; } } other methods can be used
page. A. jsp <jsp: use. Bean id="access. Counter" class="dbi. Counter. Bean" scope="application"/> <% access. Counter. increment(); %> <H 1>Welcome to Page A</H 1> <H 2>Accesses to this application: <jsp: get. Property name="access. Counter" property="counter"/></H 2> <A HREF="page. B. jsp">Page B</a> invokes get. Counter()
page. B. jsp <jsp: use. Bean id="access. Counter" class="dbi. Counter. Bean" scope="application"/> <% access. Counter. increment(); %> <H 1>Welcome to Page B</H 1> <H 2>Accesses to this application: <jsp: get. Property name="access. Counter" property="counter"/></H 2> <A HREF="page. A. jsp">Page A</a>
Example 2: Session Data In the following example, we use a Bean in order to keep a user's details throughout the session
package dbi; public class User. Info. Bean { private String first. Name; private String last. Name; public User. Info. Bean() { first. Name = last. Name = null; } public String get. First. Name() {return first. Name; } public String get. Last. Name() { return last. Name; } public void set. First. Name(String string) {first. Name = string; } public void set. Last. Name(String string) {last. Name = string; } }
info. Form. html <HTML> <HEAD><TITLE>User Info</TITLE></HEAD> <BODY><H 1>Fill in your details: </H 1> <FORM ACTION="info. A. jsp"> Your First Name: <INPUT TYPE="text" NAME="first. Name"> <BR> Your Last Name: <INPUT TYPE="text" NAME="last. Name"> <BR> <INPUT TYPE="submit"> </FORM> </BODY> </HTML>
info. A. jsp Match parameters to corresponding properties <jsp: use. Bean id="user. Info" class="dbi. User. Info. Bean" scope="session"/> <jsp: set. Property name="user. Info" property="*"/> <H 1> <jsp: get. Property name="user. Info" property="first. Name"/> <jsp: get. Property name="user. Info" property="last. Name"/>, </H 1> <H 1>Have a nice session!</H 1> <A HREF="info. B. jsp">User Info B</a>
info. B. jsp <jsp: use. Bean id="user. Info" class="dbi. User. Info. Bean" scope="session"/> <jsp: set. Property name="user. Info" property="*"/> <H 1> <jsp: get. Property name="user. Info" property="first. Name"/> <jsp: get. Property name="user. Info" property="last. Name"/>, </H 1> <H 1>Have a nice session!</H 1> <A HREF="info. A. jsp">User Info A</a>
Advantages of Java Beans • Easy and standard management of data - Automatic management of bean sharing and lots more • Good programming style - Allow standard but not direct access to members - You can add code to the setters and getters (e. g. constraint checks) without changing the client code - You can change the internal representation of the data without changing the client code • Increase of separation between business logic (written by programmers) and HTML (written by GUI artists)
Appendix 2: Custom JSP Tags
Custom JSP Tags • JSP code may use custom tags - tags that are defined and implemented by the programmer • The programmer defines how each of the custom tags is translated into Java code • There are two methods to define custom tags: - Tag libraries - used in old versions of JSP - Tag files - much simpler, introduced in JSP 2. 0
Tag Libraries • A tag library consists of: - Tag handlers - Java classes that define how each of the new tags is translated into Java code - A TLD (Tag Library Descriptor) file, which is an XML file that defines the structure and the implementing class of each tag
A Simple Tag. Lib Example package dbi; Date. Tag. java import javax. servlet. jsp. Jsp. Exception; import javax. servlet. jsp. tagext. Simple. Tag. Support; import java. io. IOException; public class Date. Tag extends Simple. Tag. Support { public void do. Tag() throws Jsp. Exception, IOException { get. Jsp. Context(). get. Out(). print(new java. util. Date()); } }
<? xml version="1. 0" encoding="ISO-8859 -1" ? > <taglib version="2. 0"> <tlib-version>1. 0</tlib-version> dbi-taglib. tld <tag> <name>date</name> <tagclass>dbi. Date. Tag</tagclass> <body-content>empty</body-content> </taglib> <%@ taglib prefix="dbitag" uri="/WEB-INF/tags/dbi-taglib. tld" %> <html><body> taglibuse. jsp <h 1>Hello. The time is: <dbitag: date/></h 1> </body></html>
Tag Files • The new version of JSP (2. 0) provides an extremely simplified way of defining tags • The idea: for each custom tag, write a tag file tag. Name. tag that implements the tag translation using JSP code • This way, the programmer can avoid creating tag handlers and TLD files
The Simplified Example <%= new java. util. Date() %> date. tag <%@ taglib prefix="dbitag" tagdir="/WEB-INF/tags/" %> <html><body> <h 1>Hello. The time is: <dbitag: date/></h 1> </body></html> taguse. jsp
Other Capabilities of Custom Tags • Attributes - You can define the possible attributes of the Tags - These can be accessed during the Tag translation • Tag Body - Tag translation may choose to ignore, include or change the tag body
- What is jsp file
- Java server pages life cycle
- Java server pages
- Java server pages
- Jsp o que é
- Printed pages vs web pages
- Active server pages paradigma
- Java jsp
- Java jsp
- Servlet tutorial
- Java vs jsp
- Java ee jsp
- Representation invariant java
- Pircbot
- Java irc
- Tcp and udp socket programming in java
- Java.rmi.server.codebase
- Lập trình socket giao tiếp tcp client/server java
- Knock knock server java
- Pages 294 and 295
- A process is busy swapping pages in and out. *
- What is jsp
- Comment préparer son oral de brevet
- Jsp bus
- Anatomy of jsp page
- Jsp539
- Climatic injuries
- Jsp engine
- Jsp engine
- Jsp anatomy
- Introduction of jsp
- Mvc architecture in jsp
- Actioncart
- Jsp jdbc
- Jsp page directive
- Html에서 jsp include
- What is jsp
- Introduction to jsp
- Standard actions in jsp
- Exercice 1 page
- Jsp overview
- Korean.jsp?include= site:com
- Jsp xss 취약점 해결
- Jsp standard tag library
- Jsp database access
- Jsp architecture diagram
- Etiquetas jsp
- Define jsp
- How to create a dynamic web page in jsp
- Jsp 1
- Mineresepter.no/mineresepter/velkommen.jsp
- Etiquetas jsp
- Spring boot jsp
- Payroll card
- Custom tags in jsp
- Javascript framework
- Jsp 539
- Commentaire jsp
- Jsp 구구단
- Comentarios en jsp
- Import java.lang.*
- Import java.util.*
- Import javax.swing.*
- Import util scanner java
- Import java.io.file;
- Import java.util.scanner;
- Import java util random
- What is readline in java
- Import.java.util.*
- Java thread import
- Perbedaan swing dan awt
- Import java.awt.event.*
- Programming language b
- What is rmi and ejb in java
- Sql server management studio tips and tricks
- Dominant rules
- The collection
- The lorax saying
- Jose pages hijo
- What symbolic number is engraved on montag's helmet?
- Fahrenheit 451 english
- Seashell cs136
- 3 pages double spaced
- House of leaves decoded
- Fahrenheit 451 pages 93-110 summary
- Erg 2008
- Artist research page
- Is the standard page description language for web pages
- Fahrenheit 451 pages
- Banner admin pages
- Yearbook avenue practice pages
- Science fusion landing pages
- Eamhttps://inside.amazon.com/pages/default.aspx
- Https://forms.office.c
- Heart of darkness setting
- Chapter 14 esperanza rising summary
- The catcher in the rye poem
- How to write fractions in pages
- Citing pages
- Abnormality pages
- Mla format pages
- Slotted page structure
- Yellow pages api
- 1035 yellow pages
- Dynamic website
- Les pages suivantes