440 likes | 477 Views
Learn about JavaServer Pages (JSP), a server-side programming concept that allows the creation of dynamic web pages using Java code and HTML. Explore JSP scripting elements, directives, and actions, and understand how JSP pages are compiled into servlets to run on a web server. Gain insights into managing session attributes, request parameters, and more with JSP. This guide provides detailed examples and explanations to help you become proficient in JSP development.
E N D
Concept:Server-side programming • CGI scripts • servlet • Java program that runs on webserver • Called from html page • Follows Sun servlet standard • JavaServer page (JSP) • Contains html and • Java or JavaScript • Compiled into a servlet and run on server
JSP is servlet • follows request-response model • loaded into webserver • webserver manages instance • typical logic • examine request: • parameters, session, cookies, context • produce response • add to output stream
JSP page • stored with extension “.jsp” • contains • html • JSP scripting elements • JSP directives • JSP actions • JSP comment • <%-- --%>
JSP scripting elements • declaration • <%! %> • expression • <%= %> • scriptlet • <% %>
JSP declaration • placed into servlet outside of service method • <%! int accessCount = 0; %>
JSP expression • expression is evaluated and placed into output This page has been accessed <%= accessCount %> times
JSP scriptlet • code that is inserted into service method • <% accessCount += 1; %>
first JSP example <html> <head><title>Very Simple JSP</title></head> <body> <h1>Very Simple JSP</h1> <%! int accessCount = 0; %> This page has been accessed <%= accessCount %> times <% accessCount += 1; %> </body> </html>
JSP directives • control overall structure of servlet • include • used to include another file • <%@ include file=“relative URL” %> • URL may start with “/”
JSP directive: page • has attributes • import • to add import statements to servlet • <%@ page import=“java.util.*” %> • content-type • isThreadSafe • value “true” is default • “false” makes servlet implement SingleThreadModel
JSP page directive:more attributes • session • value “true” is default • “false” disables session management • buffer="sizekb|none“ • specifies the buffer size for the JspWriter out • autoflush="true|false” • extends="package.class” • info="message” • errorPage="url” • isErrorPage="true|false” • language="java"
Predefined variables • request • instance of HttpServletRequest • ex: request.getParameter(“username); • response • instance of HttpServletResponse • ex: response.addCookie(myCookie);
Predefined variables • out • instance of JSPWriter • buffered version of output stream • ex: out.println(“hello world”); • same as html text outside of <% … %>
Predefined variables • session • instance of HttpSession • only available if session attribute of <%@ page %> directive is true • ex: session.setAttribte(“user”, “John Doe”); • ex: name = (String) session.getAttribute(“user”);
Predefined variables • application • instance of HttpContext • ex: application.setAttribute(“user”, “John Doe”); • ex: name = (String)application.getAttribute(“user); • config • instance of HttpConfig • page • same as “this” in Java
JSP example: second.jsp <html><head><title>Session JSP</title></head><body> <h1>Welcome to our World</h1> <%@ page session="true" %> <form action="second.jsp"> <% if (session.isNew()) { %> Enter your ID: <input type="text" name="username"> <% } else { String name = request.getParameter("username"); if (name == null) name = (String)session.getAttribute("user"); else session.setAttribute("user", name); %> Welcome back <%= name %> <% } %> <input type="submit"></form> </body></html>
JSP actions • jsp:include • include a file at the time the page is requested • jsp:forward • forward the requester to a new page • jsp:useBean • find or instantiate a JavaBean • jsp:setProperty • set the property of a JavaBean • jsp:getProperty • insert the property of a JavaBean into the output • jsp:plugin
jsp:include action <jsp:include page="relative URL" flush="true" /> • inserts the file at the time the JSP page is translated into a servlet • similar to “include” method of RequestDispatcher
jsp:forward action <jsp:forward page="relative URL" /> • forwards the request to another page • similar to “forward” method of RequestDispatcher • examples: <jsp:forward page="errorReporter.jsp" />
Greeting.html <html><head> <title>Shopping cart example</title></head> <body><h1>Welcome to the Mini Store</h1> <form action="MiniStore.jsp" method="post"> Please select one or more of our products:<br> <select name="products" multiple> <option>product 1 <option>product 2 <option>product 3 <option>product 4 <option>product 5 <option>product 6 </select> <input type="submit"> </form> </body></html>
MiniStore.jsp (1/3) <%@ page import="java.util.*" %> <HTML><BODY> <% if (session.isNew()) { %> <h1>Welcome Newcomer</h1> <% } else { %> <h1>Welcome Back</h1> <% } %>
MiniStore.jsp (2/3) <% Vector list = (Vector) session.getAttribute("cart"); if (list == null) list = new Vector(); String products[] = request.getParameterValues("products"); if (products != null) for (int i = 0; i < products.length; i++) list.addElement(products[i]); session.setAttribute("cart", list); %>
MiniStore.jsp (3/3) <H2>Thanks for your selection:</H2> <TABLE><TR><TH>Product</TH></TR> <% Enumeration all = list.elements(); while (all.hasMoreElements()) out.println("<TR><TD>" + all.nextElement() +"</TD>"); %> </tr></table> <jsp:include page="continue.html"/> </body></html>
continue.html <form action="Greeting.html"> <input type="submit" value="Continue Shopping"> </form>
jsp:useBean action <jsp:useBean id="name" class="package.class" /> • instantiates an object of the specified class • binds it to a variable with id “name” • variable can be used to invoke bean methods or to handle its properties • bean can be associated with scope
jsp:useBean actionscope attribute <jsp:useBean id="name" class="package.class" scope=“value”/> • values can be • page (default) • request • session • application • makes bean accessible within scope
jsp:setProperty action <jsp:setProperty name="orderBean" property="numberOfItems" value=“21" /> <jsp:setProperty name="orderBean" property="numberOfItems" param="numItems" /> • sets value of bean property
jsp:getProperty action <jsp:getProperty name="itemBean" property="numItems" /> • value of bean property is returned
Bean example package jspexamples; public class Counter { private int value = 0; public int getValue() { return value; } public void setValue(int newValue) { value = newValue; } }
JSP example <html> <head> <title>Bean JSP example</title> </head> <body> <jsp:useBean id="counter" class="jspexamples.Counter"/> <jsp:setProperty name="counter" property="value" value="10"/> Current value is <jsp:getProperty name="counter" property="value"/> </body></html>
Variation in scope • request • make bean accessible via the request variable • request is shared in “forward” or “include” JSP • example <jsp:useBean id=“counter" class=“jspexamples.Counter" scope=“request”/>
Variation in scope • <jsp:useBean …> action • will find existing bean within scope • other scopes • session • application • available to all servlets within the same ServletContext
Jsp example (1/2) <html><head> <title>Bean JSP example</title> </head><body> <jsp:useBean id="counter" class="jspexamples.Counter” scope="request"/> <jsp:setProperty name="counter“ property="value" value="10"/> <jsp:forward page="BeanTest2.jsp"/> </body></html>
Jsp example (2/2): BeanTest2.jsp <html><head> <title>Bean JSP example</title> </head><body> <jsp:useBean id="counter" class="jspexamples.Counter“ scope="request"/> Value is now: <jsp:getProperty name="counter" property="value"/> </body></html>
Advanced Exercise • create Shopping cart bean • share with session scope
ShoppingCart bean package mypackage; import java.util.*; public class ShoppingCart { private Vector<String> products = new Vector<String>(); public String getTable() { StringBuffer buf = new StringBuffer(); Enumeration all = products.elements(); while (all.hasMoreElements()) buf.append("<TR><TD>" + all.nextElement() + "</TD>"); return buf.toString(); } public void setAddOns(String[] addOns) { for (int i = 0; i < addOns.length; i++) products.addElement(addOns[i]); } }
MiniBeans.jsp <HTML><BODY> <H2>Thank you for your selection</H2> <jsp:useBean id="cart" class=“mypackage.ShoppingCart" scope="session"/> <jsp:setProperty name="cart" property="addOns" param="products"/> <TABLE><TR><TH>Content of Shopping Cart:</TH></TR> <jsp:getProperty name="cart" property="Table"/> </TR></TABLE> <jsp:include page="continue.html" /> </BODY></HTML>