Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
WEB TECHNOLOGIES A COMPUTER SCIENCE PERSPECTIVE JEFFREY C. JACKSON Separating Programming and Presentation: JSP Technology Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0 Get vs. Post Methods • In GET your entire form submission can be encapsulated in one URL, like a hyperlink. query length is limited to 255 characters, not secure, faster, quick and easy. The data is submitted as part of URL. • In POST data is submitted inside body of the HTTP request. The data is not visible on the URL and it is more secure. Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0 What is JSP • Java Server Pages (JSP) is a platform independent presentation layer technology that comes with SUN s J2EE platform. • JSPs are normal HTML pages with Java code pieces embedded in them. • JSP pages are saved to *.jsp files. • A JSP compiler is used in the background to generate a Servlet from the JSP page. Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0 What is JSP Technology • The JavaServer Pages technology enables you to generate dynamic web content, such as HTML, DHTML, XHTML, and XML files, to include in a Web application. • JSP files allow a Web server, such as Apache Tomcat, to add content dynamically to your HTML pages before they are sent to a requesting browser. • When you deploy a JSP file to a Web server that provides a servlet engine, it is preprocessed into a servlet that runs on the Web server. This is in contrast with client-side JavaScript™ (within SCRIPT tags), which is run in a browser. Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0 Why JSP? • Servlet/CGI approach: server-side code is a program with HTML embedded • JavaServer Pages (and PHP/ASP/ColdFusion) approach: server-side “code” is a document with program embedded – Supports cleaner separation of program logic from presentation – Facilitates division of labor between developers and designers Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0 JSP vs. Servlet JSP Servlet JSP is a webpage scripting language that can generate dynamic content. Servlets are Java programs that are already compiled which also creates dynamic web content JSP run slower compared to Servlet as it takes Servlets run faster compared to JSP. compilation time to convert into Java Servlets. It’s easier to code in JSP than in Java Servlets. Its little much code to write here. In MVC, jsp act as a view. In MVC, servlet act as a controller. JSP are generally preferred when there is not much servlets are best for use when there is more processing processing of data required. and manipulation involved. The advantage of JSP programming over servlets is that There is no such custom tag facility in servlets. we can build custom tags which can directly call Java beans. JSP is used mainly for presentation only. A JSP can only be HttpServlet that means the only supported protocol in JSP is HTTP. But a servlet can support any protocol like HTTP, FTP, SMTP etc 6 Simple Hello World in JSP <html> <head><title>Hello World JSP Page.</title></head> <body> <font size="10"><%="Hello World!" %></font> </body> </html> 7 Simple Hello World in Servlet import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorld extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException{ response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.println("<html>"); pw.println("<head><title>Hello World</title></title>"); pw.println("<body>"); pw.println("<h1>Hello World</h1>"); pw.println("</body></html>"); } } 8 Comments in JSP Two types • <%– JSP Comment –%> • <!– HTML Comment –> Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0 JSP by Example • JSP simply puts Java inside HTML pages. You can take any existing HTML page and change its extension to ".jsp" instead of ".html". • Take the HTML file you used in the previous exercise. Change its extension from ".html" to ".jsp". Now load the new file, with the ".jsp" extension, in your browser. • You will see the same output, but it will take longer! But only the first time. If you reload it again, it will load normally. • What is happening behind the scenes is that your JSP is being turned into a Java file, compiled and loaded. This compilation only happens once, so after the first load, the file doesn't take long to load anymore. (But everytime you change the JSP file, it will be re-compiled again.) 10 JSP Expressions • Put the following text in a file with .jsp extension (let us call it hello.jsp), place it in your JSP directory, and view it in a browser. <HTML> <BODY> Hello! The time is now <%= new java.util.Date() %> </BODY> </HTML> • Notice that each time you reload the page in the browser, it comes up with the current time. • The character sequences <%= and %> enclose Java expressions, which are evaluated at run time. • This is what makes it possible to use JSP to generate dyamic HTML pages that change in response to user actions or vary from user to user. 11 JSP Scriptlets • We have already seen how to embed Java expressions in JSP pages by putting them between the <%= and %> character sequences. • But it is difficult to do much programming just by putting Java expressions inside HTML. • JSP also allows you to write blocks of Java code inside the JSP. You do this by placing your Java code between <% and %> characters (just like expressions, but without the = sign at the start of the sequence.) 12 Scriptlet • A scriptlet can contain any number of language statements, variable or method declarations, or expressions that are valid in the page scripting language. • Within scriptlet tags, you can • Declare variables or methods to use later in the file (see also Declaration). • Write expressions valid in the page scripting language (see also Expression). • Use any of the JSP implicit objects or any object declared with a <jsp:useBean> tag. • You must write plain text, HTML-encoded text, or other JSP tags outside the scriptlet. • Scriptlets are executed at request time, when the JSP engine processes the client request. If the scriptlet produces output, the output is stored in the out object, from which you can display it. Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0 Variable inside Scriptlets • Variable declared inside declaration part is treated as a global variable. That means after conversion jsp file into servlet that variable will be in outside of service method or it will be declared as instance variable.And the scope is available to complete jsp and to complete in the converted servlet class. • If u declare a variable inside a scriplet that variable will be declared inside a service method and the scope is with in the service method. Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0 JSP Scriptlets • Here is a modified version of our JSP from previous section, adding in a scriptlet. <HTML> <BODY> <% // This is a scriptlet. Notice that the "date" // variable we declare here is available in the // embedded expression later on. System.out.println( "Evaluating date now" ); java.util.Date date = new java.util.Date(); %> Hello! The time is now <%= date %> </BODY> </HTML> 15 JSP Scriptlets • If you run the above example, you will notice the output from the "System.out.println" on the server log. • This is a convenient way to do simple debugging (some servers also have techniques of debugging the JSP in the IDE. 16 JSP Scriptlets - out variable • By itself a scriptlet does not generate HTML. If a scriptlet wants to generate HTML, it can use a variable called "out". This variable does not need to be declared. It is already predefined for scriptlets, along with some other variables. The following example shows how the scriptlet can generate HTML output. <HTML> <BODY> <% // This scriptlet declares and initializes "date" System.out.println( "Evaluating date now" ); java.util.Date date = new java.util.Date(); %> Hello! The time is now <% // This scriptlet generates HTML output out.println( String.valueOf( date )); %> </BODY> </HTML> 17 JSP Scriptlets - request variable • Another very useful pre-defined variable is "request". It is of type javax.servlet.http.HttpServletRequest • A "request" in server-side processing refers to the transaction between a browser and the server. When someone clicks or enters a URL, the browser sends a "request" to the server for that URL, and shows the data returned. As a part of this "request", various data is available, including the file the browser wants from the server, and if the request is coming from pressing a SUBMIT button, the information the user has entered in the form fields. • The JSP "request" variable is used to obtain information from the request as sent by the browser. For instance, you can find out the name of the client's host (if available, otherwise the IP address will be returned.) 18 JSP Scriptlets - request variable <HTML> <BODY> <% // This scriptlet declares and initializes "date" System.out.println( "Evaluating date now" ); java.util.Date date = new java.util.Date(); %> Hello! The time is now <% out.println( date ); out.println( "<BR>Your machine's address is " ); out.println( request.getRemoteHost()); %> </BODY> </HTML> 19 JSP Scriptlets - response variable • A similar variable is "response". • This can be used to affect the response being sent to the browser. • For instance, you can call response.sendRedirect( anotherUrl ); to send a response to the browser that it should load a different URL. • This response will actualy go all the way to the browser. • The browser will then send a different request, to "anotherUrl". • This is a little different from some other JSP mechanisms we will come across, for including another page or forwarding the browser to another page 20 JSP Directives • We have been fully qualifying the java.util.Date in the examples in the previous sections. • Perhaps you wondered why we don't just import java.util.*; • It is possible to use "import" statements in JSPs, but the syntax is a little different from normal Java. Try the following example: <%@ page import="java.util.*" %> <HTML> <BODY> <% System.out.println( "Evaluating date now" ); Date date = new Date(); %> Hello! The time is now <%= date %> </BODY> </HTML> • The first line in the above example is called a "directive". A JSP "directive" starts with <%@ characters. 21 JSP Directives • The page directive can contain the list of all imported packages. • To import more than one item, separate the package names by commas, e.g. <%@ page import="java.util.*,java.text.*" %> • There are a number of JSP directives, besides the page directive. Besides the page directives, the other most useful directives are include and taglib. • The include directive is used to physically include the contents of another file. The included file can be HTML or JSP or anything else -- the result is as if the original JSP file actually contained the included text. To see this directive in action, create a new JSP <HTML> <BODY> Going to include hello.jsp...<BR> <%@ include file="hello.jsp" %> </BODY> </HTML> • View this JSP in your browser, and you will see your original hello.jsp get included in the new JSP. 22 JSP Declarations •The JSP you write turns into a class definition. •All the scriptlets you write are placed inside a single method of this class. •You can also add variable and method declarations to this class. You can then use these variables and methods from your scriptlets and expressions. •To add a declaration, you must use the <%! and %> sequences to enclose your declarations, as shown below. <%@ page import="java.util.*" %> <HTML> <BODY> <%! Date theDate = new Date(); Date getDate() { System.out.println( "In getDate() method" ); return theDate; } %> Hello! The time is now <%= getDate() %> </BODY> </HTML> 23 JSP Tags • Another important syntax element of JSP are tags. • JSP tags do not use <%, but just the < character. • A JSP tag is somewhat like an HTML tag. JSP tags can have a "start tag", a "tag body" and an "end tag". • The start and end tag both use the tag name, enclosed in < and > characters. • The tag names have an embedded colon character : in them, the part before the colon describes the type of the tag. For instance: <some:tag> body </some:tag> • If the tag does not require a body, the start and end can be conveniently merged together, as <some:tag/> 24 JSP Tags • Tags can be of two types: loaded from an external tag library, or predefined tags. • Predefined tags start with jsp: characters. • For instance, jsp:include is a predefined tag that is used to include other pages. • We have already seen the include directive. jsp:include is similar. • But instead of loading the text of the included file in the original file, it actually calls the included target at run-time (the way a browser would call the included target. • In practice, this is actually a simulated request rather than a full round-trip between the browser and the server). • Following is an example of jsp:include usage <HTML> <BODY> Going to include hello.jsp...<BR> <jsp:include page="hello.jsp"/> </BODY> </HTML> 25 JSP Tags • Try it and see what you get by changing the "jsp:include" to "jsp:forward" and see what is the difference. • These two predefined tags are frequently very useful. 26 JSP Sessions • On a typical web site, a visitor might visit several pages and perform several interactions. • If you are programming the site, it is very helpful to be able to associate some data with each visitor. For this purpose, "session"s can be used in JSP. • A session is an object associated with a visitor. Data can be put in the session and retrieved from it, much like a Hashtable. A different set of data is kept for each visitor to the site. • Here is a set of pages that put a user's name in the session, and display it elsewhere. Try out installing and using these. • First we have a form, let us call it GetName.html 27 JSP Sessions <HTML> <BODY> <FORM METHOD=POST ACTION="SaveName.jsp"> What's your name? <INPUT TYPE=TEXT NAME=username SIZE=20> <P><INPUT TYPE=SUBMIT> </FORM> </BODY> </HTML> • The target of the form is "SaveName.jsp", which saves the user's name in the session. • Variable “session" is another variable that is normally made available in JSPs, just like out and request variables. 28 JSP Sessions <% String name = request.getParameter( "username" ); session.setAttribute( "theName", name ); %> <HTML> <BODY> <A HREF="NextPage.jsp">Continue</A> </BODY> </HTML> • The SaveName.jsp saves the user's name in the session, and puts a link to another page, NextPage.jsp. 29 JSP Sessions • NextPage.jsp shows how to retrieve the saved name. <HTML> <BODY> Hello, <%= session.getAttribute( "theName" ) %> </BODY> </HTML> • If you bring up two different browsers (not different windows of the same browser), or run two browsers from two different machines, you can put one name in one browser and another name in another browser, and both names will be kept track of. • The session is kept around until a timeout period. Then it is assumed the user is no longer visiting the site, and the session is discarded. 30 JavaBeans Classes • JSTL Core actions are designed to be used for simple, presentation-oriented programming tasks • More sophisticated programming tasks should still be performed with a language such as Java • JavaBeans technology allows a JSP document to call Java methods Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0 JavaBeans Classes • Using a JavaBeans class in JSP Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0 JavaBeans Classes • Using a JavaBeans class as shown: – Class must have a default (no-argument) constructor to be instantiated by useBean • Automatically supplied by Java in this example – Class should belong to a package (avoids need for an import) • This class would go in WEB-INF/classes/my/ directory • Instance of a JavaBeans class is a bean Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0 JavaBeans Classes • Simple property design patterns – Two types: getter and setter • Both require that the method be public • getter: – no arguments – returns a value – name begins with get (or is, if return type is boolean) followed by upper case letter • setter: – one argument (same type as setter return value) – void – name begins with set followed by upper case letter Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0 JavaBeans Classes • Simple property design pattern methods associate bean properties with beans – Name of bean property obtained by removing get/is/set method prefix and following the rule: • If remaining name begins with two or more upper case letters, bean property name is remaining name: setAValue() AValue • If remaining name begins with a single upper case letter, bean property name is remaining name with this letter converted to lower case: getWelcome() welcome Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0 JSP Beans • Forms are a very common method of interactions in web sites. JSP makes forms processing specially easy. • The standard way of handling forms in JSP is to define a "bean". This is not a full Java bean. • You just need to define a class that has a field corresponding to each field in the form. • The class fields must have "setters" that match the names of the form fields. • For instance, let us modify our GetName.html to also collect email address and age. 36 JSP Beans • The new version of GetName.html is <HTML> <BODY> <FORM METHOD=POST ACTION="SaveName.jsp"> What's your name? <INPUT TYPE=TEXT NAME=username SIZE=20><BR> What's your e-mail address? <INPUT TYPE=TEXT NAME=email SIZE=20><BR> What's your age? <INPUT TYPE=TEXT NAME=age SIZE=4> <P><INPUT TYPE=SUBMIT> </FORM> </BODY> </HTML> 37 JSP Beans • To collect this data, we define a Java class with fields "username", "email" and "age" and we provide setter methods "setUsername", "setEmail" and "setAge", as shown. • A "setter" method is just a method that starts with "set" followed by the name of the field. • The first character of the field name is upper-cased. • So if the field is "email", its "setter" method will be "setEmail". • Getter methods are defined similarly, with "get" instead of "set". Note that the setters (and getters) must be public. 38 JSP Beans package user; public class UserData { String username; String email; int age; public void setUsername( String value ) { username = value; } public void setEmail( String value ) { email = value; } public void setAge( int value ) { age = value; } public String getUsername() { return username; } public String getEmail() { return email; } public int getAge() { return age; } } 39 JSP Beans • Now let us change "SaveName.jsp" to use a bean to collect the data. <jsp:useBean id="user" class="user.UserData" scope="session"/> <jsp:setProperty name="user" property="*"/> <HTML> <BODY> <A HREF="NextPage.jsp">Continue</A> </BODY> </HTML> • All we need to do now is to add the jsp:useBean tag and the jsp:setProperty tag! • The useBean tag will look for an instance of the "user.UserData" in the session. If the instance is already there, it will update the old instance. • Otherwise, it will create a new instance of user.UserData (the instance of the user.UserData is called a bean), and put it in the session. • The setProperty tag will automatically collect the input data, match names against the bean method names, and place the data in the bean! 40 JSP Beans • Let us modify NextPage.jsp to retrieve the data from bean.. <jsp:useBean id="user" class="user.UserData" scope="session"/> <HTML> <BODY> You entered<BR> Name: <%= user.getUsername() %><BR> Email: <%= user.getEmail() %><BR> Age: <%= user.getAge() %><BR> </BODY> </HTML> 41 JSP Beans • Notice that the same useBean tag is repeated. • The bean is available as the variable named "user" of class "user.UserData". • The data entered by the user is all collected in the bean. • We do not actually need the "SaveName.jsp", the target of GetName.html could have been NextPage.jsp, and the data would still be available the same way as long as we added a jsp:setProperty tag. 42 JSP and Servlets • JSP documents are not executed directly – When a JSP document is first visited, Tomcat 1. Translates the JSP document to a servlet 2. Compiles the servlet – The servlet is executed • Exceptions provide traceback information for the servlet, not the JSP – The servlets are stored under Tomcat work directory Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0 JSP and Servlets • A JSP-generated servlet has a _jspService() method rather than doGet() or doPost() – This method begins by automatically creating a number of implicit object variables that can be accessed by scriptlets Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0 Web Applications • A web application is a collection of resources that are used together to implement some web-based functionality • Resources include – Components: servlets (including JSP-generated) – Other resources: HTML documents, style sheets, JavaScript, images, non-servlet Java classes, etc. Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0 Web Applications • Sharing data between components of a web application – Tomcat creates one ServletContext object per web application – Call to getServletContext() method of a servlet returns the associated ServletContext – ServletContext supports setAttribute()/getAttribute() methods Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0 Web Applications • Within Tomcat, all of the files of a simple web app are placed in a directory under webapps – JSP documents can go in the directory itself – “Hidden” files--such as servlet class files--go under a WEB-INF subdirectory (more later) • Once the web app files are all installed, use Tomcat Manager to deploy the app Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0 Web Applications • There are four URL patterns (from high to low precedence) • If no URL pattern matches, Tomcat treats path as a relative file name Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0 Web Applications • Methods on request object for obtaining path information: – Example: /HelloCounter/visitor/test.jsp – getContextPath(): returns /HelloCounter – getServletPath(): returns /visitor – getPathInfo(): returns /test.jsp Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0 JSP Expression Language (EL) • ${visits+1} is an example of an EL expression embedded in a JSP document – ${…} is the syntax used in JSP documents to mark the contained string as an EL expression – An EL expression can occur • In template data: evaluates to Java String • As (part of) the value of certain JSP attributes: evaluates to data type that depends on context Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0 JSP Expression Language (EL) • EL literals: – true, false – decimal integer, floating point, scientific-notation numeric literals – strings (single- or double-quoted) – null Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0 JSP Expression Language (EL) • EL variable names: like Java – Can contain letters, digits, _ , and $ – Must not begin with a digit – Must not be reserved: Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0 JSP Expression Language (EL) • EL operators: – Relational: <, >, <=, >=, ==, != • Or equivalents: lt, gt, le, ge, eq, ne – Logical: &&, ||, ! • Or equivalents: and, or, not – Arithmetic: • +, - (binary and unary), * • /, % (or div, mod) – empty: true if arg is null or empty string/array/Map/Collection – Conditional: ? : – Array access: [ ] (or object notation) – Parentheses for grouping Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0 JSP Markup • Three types of markup elements: – Scripting • Ex: scriptlet • Inserts Java code into servlet – Directive • Ex: directive.page • Instructs JSP translator – Action • Standard: provided by JSP itself • Custom: provided by a tag library such as JSTL Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0 JSP Markup • Two JSPX directives – directive.page; some attributes: • contentType • session: false to turn off use of session object • errorPage: component that will generate response if an exception is thrown • isErrorPage: true to access EL implicit exception object – directive.include: import well-formed XML Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0 JSP Markup Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0 JSP Markup • Common variables: – var • Name of a scoped variable that is assigned to by the action • Must be a string literal, not an EL expression – scope • Specifies scope of scoped variable as one of the literals page, request, session, or application • page default scope, unless otherwise specified Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0 JSP Markup • set action – Setting (and creating) a scoped variable – Setting/creating an element of Map Map Key • Actually, this fails at run time in JWSDP 1.3 (which treats EL implicit object Maps as read-only) Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0 JSP Markup • remove action – Only attributes are var and scope – Removes reference to the specified scoped variable from the scope object <c:remove var=“visits” scope=“application” /> Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0 JSP Markup • out action – Normally used to write a string to the out JSP implicit object – Automatically escapes all five XML special characters – If value is null output is empty string • Override by declaring default attribute Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0 JSP Markup • url action – value attribute value is a URL to be written to the out JSP implicit object – URL’s beginning with / are assumed relative to context path – param elements can be used to define parameters that will be URL encoded Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0 JSP Markup • Alternative to the value attribute (set and param elements) – If element has content, this is processed to produce a String used for value – Even out element will produce string, not write to the out object Assigns value of variable messy (XML escaped) to scoped variable clean Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0 JSP Markup • if action – General form includes scoped variable to receive test value Assigned Boolean value of test attribute • The element can be empty if var is present Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0 JSP Markup • choose action <c:choose> <c:when test=“${visits eq 1}”> Hi!</c:when> <c:when test=“${visits eq 2}”> Welcome back!</c:when> <c:otherwise> You’re a regular!</c:otherwise> </c:choose> Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0 JSP Markup • forEach action – Used to increment a variable: – Used to iterate over a data structure: Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0 JSP Markup • forEach action – Can iterate over array, Map, Collection, Iterator, Enumeration – Elements of Map are Map.Entry, which support key and value EL properties: Tag Libraries • Wouldn’t it be nicer to write the mortgage app as Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0 Tag Libraries Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0 Tag Libraries • Place custom tag definition in a tag file having the name of the custom action – mortgage.tagx • Place tag file in a tag library (e.g., directory containing tag files) – /WEB-INF/tags • Add namespace declaration for tag library Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0 MVC • Many web apps are based on the Model-ViewController (MVC) architecture pattern Model Components View Controller HTTP request HTTP response Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0 MVC • Typical JSP implementation of MVC Model Components (beans, DBMS) Controller (Java servlet) HTTP request View (JSP document) HTTP response Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0 MVC • Forwarding an HTTP request from a servlet to another component: – By URL Ex: /HelloCounter.jspx – By name Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0 MVC Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0 MVC • How does the controller know which component to forward to? – getPathInfo() value of URL’s can be used – Example: • servlet mapping pattern in web.xml: • URL ends with: • getPathInfo() returns: Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0 MVC • JSP include action Execute specified component and include its output in place of the include element Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0 MVC • Adding parameters to the request object seen by an included component: request object seen by navbar.jspx will include parameter named currentPage with value home Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0