Java Training Java Server Pages (JSP

)
Written by Jeff Smith

What is JSP -1  

JSP (Java Server Pages) is a server side scripting technology that is similar to ASP (Active Server Pages) and PHP is many respects. But where ASP relies on the windows specific COM standard for embedded objects (e.g. ADO), JSP uses platform neutral java beans. While ASP scripts are written in either VBScript (the default) or JScript, JSP scripts are written in Java

What is JSP -2   

When a browser requests a page with a '.jsp' extension, the JSP container on the web server runs the script as a servlet (each instance in a separate thread), after checking to see whether the JSP page needs compiling.  Tomcat is a popular (and free) JSP/servlet container JSP pages are generally a mixture of standard HTML tags and special JSP tags Multiple (simultaneous) requests for the same JSP page result in multiple threads being created (not multiple processes). Since threads require significantly fewer resources to create than processes, JSP pages are very efficient.

which results in even greater efficiency. JSP scales upwards quite well making it's performance compare very favorably with other server side technologies such as ColdFusion. By implementing JSP pages as compiled servlets which run in multiple threads. CGI/C++. and ASP.What is JSP -3   Some JSP containers support "in process" execution which allows the JSP servlet to run as part of the HTTP server itself. .

the following code would check for a parameter called username and if it exists. you use the <%= tag  e.JSP Scriptlets -1      You can imbed Java code in a JSP (this code is called a scriptlet) Note: this is similar to the way it is done in ASP and PHP You put your Java code between <% and %> tags To display a Java value in your HTML. .g. <%= myJavaString %> For example. it would assign that parameter to the variable userName and display it on the page.

%> <b> Welcome to our website.getParameter("userName"). <%= userName %> </b> </BODY> </HTML> . if ((userName == null) || (userName.JSP Scriptlets -2 <HTML> <BODY> <% String userName = request.length() < 1)) userName = "guest".

I passed in the parameter (userName=Jeff) in my URL. a webapps subdirectory).e.JSP Scriptlets -3  You can test this JSP by saving it to disk with a .jsp  Note that in the screenshot above.JSP extension and placing it in a Tomcat context (i.. . For example: c:\Tomcat5\webapps\mywebapp\test.

I would get the "guest" message instead.JSP Scriptlets -4  If I don't pass in a userName parameter. .

JSP Scriptlets -5  You can write a Java loop and have it dynamically generate HTML like so <% for (int i=0. i < 10. i++) { %> <b>Loop counter i=</b> <%= i %><br> <% } %> .

JSP Scriptlets -6  Here is the resulting HTML in a browser: .

your page may require java.util.io. <%@ page import="java.*" %> .io.*).*.JSP Scriptlets (import) -7  Use the page import directive to import a class into your JSP (for example. java.

The presentation (HTML) and implementation (Java) cannot be worked on separately. The Java code cannot be easily reused in other pages 2. Often times Java programmers aren't the best web design people (and many web page designers often don't know Java). But tightly coupling the java code and HTML in the same file results in two disadvantages: 1. .JSP Scriptlets (summary)  Writing JSP scriptlets is quick and easy.

Any other login should return a page saying "Access denied". µnoaa1') for his username/password. If the user enters (µnoaa'. a page should return saying he is logged into the system.   . this information should be sent to a JSP that validates the login using scriptlet code. When the user clicks on a "login" button.Scriptlets Exercise  Create a login web page using JSP. The user should type in his username and password into an HTML form.

has a no argument constructor 2. implements the Serializable interface 4. A JavaBean is simply a class that 1.JavaBeans -1 As an alternative to scriptlets. uses getter and setter methods to access all fields 3. you can separate your HTML from your Java code by writing JavaBeans and using the JSP tags to access the bean from your HTML. can optionally use events to communicate with other beans (more on this later on)   .

designing a Swing user interface using JBuilder or NetBeans) Visual tools can persist JavaBeans state (e. setting properties in a GUI development tool) because JavaBeans implement the serialization interface JBuilder and NetBeans have a "form designer" that enables you to "drop" JavaBean controls onto a form and then manipulate them  .JavaBeans -2   JavaBeans enable component based software development using visual tools (for example.g.

JavaBeans (JBuilder) -3 .

.JavaBeans (JBuilder) -4  The JBuilder form designer allows you to write event procedures for JavaBean components by clicking on a component (to select it) and then going to the events tab and dbl-clicking on an desired event procedure.

For example  JSP/Servlet based web applications  Java Swing and SWT graphical user interfaces .JavaBeans (JBuilder) -5   We'll talk more about JavaBeans and developing GUI applications in a later section of slides Remember that JavaBeans are not restricted to being GUI components--almost any class can be written as a JavaBean and utilized by JSP.

JSPs with JavaBeans -1  If you separate your HTML from your Java code by writing JavaBeans. you could create a LoginBean class that creates a single property (username) which is defaulted to "guest" in the constructor. (see next slide) .

noaa.JSPs with JavaBeans -2 package gov.login.io.Serializable { private String username.username = "guest". public LoginBean() //constructor takes no arguments { this.username = username. } public void setUsername(String username) { this. } //assign default value public String getUsername() { return username. } } . public class LoginBean implements java.

JSPs with JavaBeans -3  The JSP page which uses this JavaBean might look like: <HTML> <BODY> <jsp:useBean id="login" scope="session" class="com.LoginBean"/> <jsp:setProperty name="login" property="username" value="jsmith"/> <b> Welcome to our website.wms. <jsp:getProperty name="login" property="username"/> </b> </BODY> </HTML> .cexp.login.

JSPs with JavaBeans -4 


The <jsp:useBean> tag declares the bean to be used with this page, and identifies this bean as "login". The <jsp:setProperty> tag provides access to the "username" property and assigns it the value of the "jsmith" parameter passed into the page via a URL query string.  This invokes the setUserName() method inside the class Another example (code on next slide) -- if the URL requesting this page was 'http://www.mydomain.com/login.jsp?username=Jeff',  the query string is "username=Jeff"  the following HTML would appear in the user's browser: Welcome to our website, Jeff 

JSPs with JavaBeans -5 


<jsp> tag attributes can be in double quotes or single quotes (just like HTML form fields) You can also imbed scriplet code in a <jsp> tag to access form fields:

<HTML> <BODY> <jsp:useBean id="login" scope="session" class="com.cexp.wms.login.LoginBean"/> <jsp:setProperty name="login" property="username" value='<%= request.getParameter("username") %>'/> Welcome to our website, <jsp:getProperty name="login" property="username"/> </BODY> </HTML>

JSPs with JavaBeans -6 

To test this page, I compiled the Java class and copied to a Tomcat context called wms (i.e. /webapps/wms)

JSPs with JavaBeans -7  After restaring Tomcat. I invoked the JSP from my web browser: .

you don't have to bounce Tomcat. Tomcat won't pick up the change until you restart (bounce) Tomcat.  Setting "reloadable=true" won't make any difference (although this might work with Tomcat 6²I haven¶t tested this yet)  This is kind of a pain  When you only change the JSP file itself.  Any Java scriptlets (imbedded Java) are automatically recompiled .JSPs with JavaBeans -8  Tomcat Issue  When you recompile your JavaBean class.

However. by isolating the Java code (implementaion) from the HTML (presentation) we 1. websites are written using this methodology--the Java code is separated from the HTML presentation . complex. Real-world. Make it possible to have one person write the bean and a different person (perhaps a non-Java web designer) to create the layout without worrying about overwriting the other person's code. Create a bean which can reused in other JSP pages 2.JSPs with JavaBeans (summary)    The drawback of using JavaBeans is that it requires more upfront time to write the bean class and to write the separate HTML file.

If the user enters (µnoaa'. The user should type in his username and password into an HTML form. this information should be sent to a JSP that validates the login using a separate JavaBean class.   . µnoaa1') for his username/password.JavaBeans Exercise  Create a login web page using JSP. Any other login should return a page saying "Access denied". a page should return saying he is logged into the system. When the user clicks on a "login" button.

JSPs and Servlets -1   In many web applications. .  Unauthenticated users could be detoured to a login page. HTML forms are submitted to a Servlet which invokes application logic (in separate classes) and based on this processing returns different JSP pages. Some web apps use a Servlet for authentication control.  It is better to put this login in one place (an authentication Servlet) than in every JSP page. This Servlet could contain the code for authenticating the user before allowing them to view certain pages.

HttpServletResponse response) throws ServletException.sendRedirect("http://someURL/di/err. you might have the following code in your Servlet: public void doPost(HttpServletRequest request.) response.some condition. } .. IOException { if (..jsp").. For example.sendRedirect() method.JSPs and Servlets -2  A Servlet can simply redirect output to a JSP (or any other source) via the response..

JSPs and Servlets -3  Sample Servlet / JSP architecture  Original request handled by Servlet  Servlet authenticates user. does database query and/or executes application logic  Results are placed in JavaBeans  Request is forwarded to JSP for formatting/display .

your Servlet could read a request parameter to determine which JSP it should forward to .JSPs and Servlets -4  To Forward (or Dispatch) a request form a Servlet to a JSP  use the RequestDispatcher object  RequestDispatcher can forward a request (passing the request and response objects)  For example.

forward(request.g. . IOException { String url = "/inventory. the "wms" directory).jsp". dispatcher. response). //relative URL RequestDispatcher dispatcher = getServletContext().JSPs and Servlets -5  Here's an example of forwarding a request from a Servlet to a JSP public void doGet(HttpServletRequest request. }  The inventory. HttpServletResponse response) throws ServletException.getRequestDispatcher(url).jsp file referenced in the relative URL will need to reside in the root dir of your web context (e.

If the login fails.Servlet/JSP Exercise    Modify your JavaBeans exercise so that your HTML login form action points to a Servlet named LoginServlet. it should return a "success" JSP page. the Servlet should return a "failure" JSP page. This Servlet should validate the login and if it succeeds. .

JSP pages allow you to execute initialization code in a special method.  The initialization code is executed  the first time the JSP page is requested  The destruction code is executed when  the JSP container is shutting down  or when the JSP container unloads a JSP to conserve resources (and when the JSP hasn't been called recently) These two code sections would be a good place to establish and close a database connection pool .Initialization & Destruction -1   Like Servlets.

Initialization & Destruction -2  To add this code to your page. you write something like: <%! public void jspInit() { //put your initialization code here } public void jspDestroy() { //put your cleanup code here } %> .

javax.JSP Implicit Objects -1  Implicit objects are just objects that are available in every JSP (as a programmer.jsp.jsp.lang.servlet.HttpServletResponse javax.servlet.ServletConfig javax.JspWriter javax.HttpServletRequest javax.http.servlet.servlet.Throwable .servlet.HttpSession javax. uncaught exception config page request response out session application pageContext javax.http.servlet.servlet.servlet.HttpJspPage javax.http.PageContext exception java. you can access these objects).jsp.ServletContext Servlet config data servlet instance of page request data & parameters response data output stream for page user specific session data shared data (all pages) context data/page exec.

removes attribute from list .assoc a key with a value  getAttributeNames() -.JSP Implicit Objects -2   Implicit objects that can persist values (attributes) to enable state information to be transferred from one JSP to another  request  session  application  pageContext Common attribute persistence methods  setAttribute(key.gets list of all attributes  getAttribute(key) -. value) -.gets the attribute value for key  removeAttribute(key) -.

application.setAttribute("color". myColor). %>  Another JSP in this application could read this attribute <% String color = (String)application.getAttribute("color").JSP Implicit Objects -3  For example. %> The color was: <% color %> . one JSP in a web application could save a color by using the setAttribute() function <% String myColor = "Green".

getParameter("username").Request Implicit Object   The request object contains all the information associated with the HTTP request (just like with Servlets)  HTML form fields (parameters)  requested URL  cookies  headers See the javadocs for HttpServletRequest <% String username = request. %> .

setContentType("text/html").redirects response to another URL See the javadocs for HttpServletResponse  <% response.html or other MIME type  addCookie(cookie)  sendRedirect(url) -.println("<HTML>Greetings. out. %> .Response Implicit Object  The response object represents the response that will be sent back to the user (just as in Servlets)  setContentType() -. Earthlings</HTML>").

clears the contents of the output buffer  newLine() -.JspWriter JspWriter methods  println()  clear() -. %> . out.println("<HTML>Greetings. The out object is an instance of javax.inserts a line separator  close() -.setContentType("text/html").servlet. Earthlings</HTML>").closes the output stream See the javadocs for JspWriter <% response.jsp.Out Implicit Object     The out object represents the output stream for the page.

Session Implicit Object -1  The session object represents a user's current session  Only available if the session attribute of the page directive is specified in the JSP <%@ page session="true"%>   When a session has been created. all requests by the session user are considered to be part of the session  the session times out when no new requests have been received by the user for a certain length of time The session object is primarily used to persist state information between HTTP requests (through the use of attribute values) .

user). session. pwd). another JSP scriptlet (on the same page or a different page) could retrieve the login data by calling the session. %> Current user: <%= user.setAttribute("userlogin".Session Implicit Object -2  The following code creates a UserLogin object and adds this object to the session <% UserLogin user = new UserLogin(uname.getAttribute("userlogin"). %>  After the above code executes.getAttribute() method: <% UserLogin user = (UserLogin)session.getUname() %> .

For example. . the following JSP pages would be considered to be part of a single application http://localhost:8080/wms/inbound/x.jsp http://localhost:8080/wms/outbound/y.jsp  Application grouping can also be set explicitly in web application descriptor files.Application Implicit Object -1   JSP pages are grouped into applications based on their URLs. By default. most JSP containers treat the first directory name in a URL as an application.

application. you might store a database connection pool object in the application object: <%! public void jspInit() { ConnectionPool conPool = new ConnectionPool(..Application Implicit Object -2   You might use the application object to store information (objects) you want to be available to all JSPs in the application For example..setAttribute("conPool".). } %> . conPool).

Error JSP page that is returned in the event the regular JSP page threw an exception . Regular JSP that may throw an exception 2. So you have two pages 1.JSP Error Pages -1   The exception object is used to provide exception handling in your JSP application It enables you to specify a page that will be returned to a user in the event an unhandled exception is thrown.

%> <h1>Made it here</h1> </body> </html> .jsp" %> <h1>Attempting to divide by zero</h1> <% double x = 55/0.jsp: <html> <body> <%@ page errorPage="myErrorPage.jsp) that generates the exception regularPage.JSP Error Pages -2  Here is the "regular" JSP page (regularPage.

getMessage() %> </body> </html> . myErrorPage.jsp <%@ page isErrorPage="true" %> <html> <body> <b>The following exception was thrown:</b><br> <%= exception.JSP Error Pages -3  Here is the file.

JSP Error Pages -4  Here's what we see in the browser: .

custom. JSP error (exception) page and use it in all the JSPs in your web application This enables you to create a consistent and attractive look for your error pages.JSP Error Pages -5     You can define a single. Your error pages could also execute code that logs the exception message to a log or a database table Servlets in your web application can also use this JSP error page .

jsp</location> </error-page> </web-app> .lang.xml (assuming you¶ve created an error page named ErrorPage. some servlet mappings« <error-page> <exception-type>java.jsp) <web-app> .Exception</exception-type> <location>/ErrorPage. You need to add this to your web.JSP Error Pages and Servlets -1   You can forward a Servlet exception on to your JSP error page too...

jsp.forward(request.jspException". if (password == null) request.jsp in the event that no password was passed into the Servlet (presumably from an HTML form).JSP Error Pages and Servlets -2  For example.servlet.getParameter("password").setAttribute("javax. dispatcher. new Exception("missing password")). RequestDispatcher dispatcher = getServletContext(). response).jsp").getRequestDispatcher("/ErrPage. String password = request. . the following code generates an exception and forwards it to ErrPage.

JSP Composite Pages-1   You can include "incomplete" JSPs in other JSPs. You could also include a common footer page: <html> <body> <jsp:include page="header... <%@ include file="footer. you might want to use a common header file called header. Why would you do this? For example.jsp" flush="true"> ..jsp" %> </body> </html>  header.rest of page goes here..jsp might contain code for generating a site menu that you want on the top of every page in your website .jsp in all your pages.

Web Application Architectures-1    You can create a Page Centric architecture which consists entirely of JSPs. good for prototypes  Fast to develop for people proficient in Java and HTML Disadvantages  More difficult to maintain a complex web application (some coupling of Java and HTML is inevitable)  More difficult to enforce flow control (web users can invoke an JSP file they want in their browser in any order .  Some JSPs do the presentation  Other JSPs encapsulate the application logic  either through scriptlets or JSPs and JavaBeans Advantages  Simple architecture.

.Web Application Architectures-2    A Servlet Centric architecture  Servlets do flow control (all form actions point to one or more servlets)  Servlets and associated classes do the application logic  Servlets only return JSPs to the web browser (i.e. they are "thinner" and easier for non-Java people to develop  A single Servlet can manage user logins and flow Disadvantages  Slightly more complex architecture since we've added Servlets to the mix . all presentation is in the form of JSPs) Advantages  More flexible and maintainable for larger websites  Since there isn't any application logic in the JSPs.

Web Application Architectures-3  Servlet Centric Architecture .

 Based on the MVC (model view controller) design pattern Advantages  It makes it easier to organize.Web Application Architectures-4    Struts and JSF (Java Server Faces) are popular open source Java frameworks for building web applications.. You also have to learn how Struts works. and tag libraries later on. and maintain large web applications that contain Servlets. control flow.. . JSF. :-) more on Struts. JSPs and custom Struts tag libraries Disadvantages  More complex architecture (since you now have Struts or JSF in the mix).

CC type. JSPs. rock  song name  artist A customer should be able to "purchase" songs by selecting the ones they want and then pressing a "Buy Now" button. classical. a customer should receive a link to that enables him to download the song to his PC All song purchases should be recorded in the database . email address  The website should return an error page if the user omitted any of this required CC information  If all the required information was provided. the date. A new page should appear that prompts the customer for the following information:  name on credit card (CC). CC Exp. how much it cost. etc.  After purchasing a song. return a confirmation page for the purchase (what they purchased.). Also send out this information in a confirmation email.E-commerce Exercise -1     Design a website using Servlets. JDBC (possibly using SQLExecutor) to compete with Apple's iTunes Music Store Customers should be able to browse/search songs by  genre: rap. CC num.

The form action should point to your servlet  Your Servlet should read the request from the web page and do a database search for the matching song(s). it should pack the matching song(s) records into Java Beans and forward this information to a JSP for display. . song name. This database should probably have a ³song´ table  You¶ll need to insert some song records into your DB  You¶ll need a web page where people can choose the genre. or artist.E-commerce Exercise -2  Oh No! It¶s Too Complicated! How Do I Start?  Phase 1--just do the search-for-songs stuff first (don¶t worry about enabling users to purchase songs)  You¶ll need to create a script to generate your database. Next.

you need to add the ability to select songs for purchase  When the user has selected some songs and pressed some ³Purchase´ button. huh?  . you¶ll need to forward the songs selected for purchase to your servlet.  The servlet can pack these selected songs into Java Beans and forward them to a JSP which totals the cost and prompts the user for their credit card information  This JSP¶s form action should be a servlet (the same servlet?) that validates their credit card information and sends back a confirmation page (or an error page if they left out required information) Easy.E-commerce Exercise -3  Phase 2  When returning the songs that match the user¶s query.

an email message should be constructed (with this HTML as the message part) and this email should be sent to every customer who has purchased a song in the past 7 days. When the administrator clicks the "Send Email" button. If the login is successful. . display a admin page with all the sales information in a slick looking HTML table  Put an HTML form (with a textarea control) on the admin page that enables the administrator to paste in some HTML.E-commerce Exercise -4  Extra Credit:  Create an admin login page that enables an administrator to log in (with the appropriate password).

Sign up to vote on this title
UsefulNot useful