Popular in Course
verified elite notetaker
Popular in ComputerScienence
This 0 page Class Notes was uploaded by Amira Cormier on Monday November 2, 2015. The Class Notes belongs to CS6320 at California State University - East Bay taught by Staff in Fall. Since its upload, it has received 25 views. For similar materials see /class/234374/cs6320-california-state-university-east-bay in ComputerScienence at California State University - East Bay.
Reviews for SoftwareEngineeringofWeb
Report this Material
What is Karma?
Karma is the currency of StudySoup.
Date Created: 11/02/15
TRAINING amp REFERENCE murach39s Java and JSP Chapter 1 Thanks for downloading this chapter from Murach s lava Servlets and lSP 2nd Edition We hope it will show you how easy it is to learn from any Murach book with its pairedpages presentation its howto headings its practical coding examples and its clear concise style To view the full table of contents for this book you can go to our web site From there you can read more about this book you can nd out about any additional downloads that are available and you can review our other books for professional developers Thanks for your interest in our books MIKE MURACH amp ASSOCIATES INC 18002215528 559 4409071 Fax 559 4400963 murachbooks1nurachcom wwwmurachcom Copyright 2008 Mike Murach amp Associates All rights reserved Contents Introduction Section 1 Chapter 1 Chapter 2 Chapter 3 Section 2 Chapter 4 Chapter 5 Chapter 6 Chapter 7 Chapter 8 Chapter 9 Chapter 10 Chapter 11 Chapter 12 Section 3 Chapter 13 Chapter 14 Section 4 Chapter 15 Chapter 16 Chapter 17 Chapter 18 Chapter 19 Chapter 20 Section 5 Chapter 21 Chapter 22 Chapter 23 Chapter 24 Resources Appendix A Index Introduction to servlet and JSP programming An introduction to web programming with Java How to install and use Tomcat How to use the NetBeans IDE Essential servlet and JSP skills A crash course in HTML How to develop JavaServer Pages How to develop servlets How to structure a web application with the MVC pattern How to work with sessions and cookies How to use standard I SP tags with JavaBeans How to use the J SP Expression Language EL How to use the J SP Standard Tag Library J STL How to use custom J SP tags Essential database skills How to use MySQL as the database management system How to use JDBC to work with a database Advanced servlet and JSP skills How to use JavaMail to send email How to use SSL to work with a secure connection How to restrict access to a web resource How to work with HTTP requests and responses How to work with listeners How to work with filters The Music Store web site An introduction to the Music Store web site The Download application The Cart application The Admin application How to set up your computer for this book xvii 29 61 105 137 173 201 243 287 311 337 375 415 441 487 513 531 555 583 599 623 649 661 683 703 719 1 An introduction to web programming with Java This chapter introduces you to the concepts and terms that you need for working with servlets and J avaServer Pages J SPs as you create web applications In particular this chapter introduces you to the software that you need to be able to write deploy and run servlets and J SPs An introduction to web applications 4 A typical web armlicatinn 4 The components of a web application How static web pages wor How dynamic web pages work An introduction to Java web programming The components of a Java web application An introduction to J avaServer Pages An introduction to servlets How to combine servlets and J SPs in a web application An introduction to Java web development Three environments for servlet and J SP development The architecture for a Java web application lDEs for developing Java web applications Tools for deploying Java web applications 39 r Section 1 Introduction to servlet and JSP programming An introduction to web applications A web application is a set of web pages that are generated in response to user requests The Internet has many different types of web applications such as search engines online stores auctions news sites discussion groups and games A typical web application Figure 1 1 shows the first two pages of the shopping cart application that s available from wwwmurachcom Here the first page presents some informa tion about our beginning Java book This page contains two buttons a View Cart button and an Add To Cart button When you click the Add To Cart button the web application adds the book to your cart and displays the second page in this figure which shows all of the items in your cart The second page lets you change the quantity for an item or remove an item from the cart It also lets you continue shopping or begin the checkout process In this book you ll learn all the skills you need to create a shopping cart appli cation like this one If you take a closer look at these web pages you can learn a little bit about how this application works For the first page the Address box of the browser shows an address that has an htm extension This means that the HTML code for this page is probably stored in file with an htm extension In contrast the Address box for the second page shows the address of a servlet that was mapped to the cartdisplayCart URL This means that the HTML code for this page was generated by the servlet After the servlet ad dress you can see a question mark and one parameter named productCode that has a value of jse6 This is the parameter that was passed from the first page Chapter 1 An introduction to web programing with Java The first page of a shopping cart application a Murach s Java SE 5 rMicrqut Ingernet aggroer HE D g 37 gr I 5 lg i 6 Q1 3 m quotEnnisFemininth enact emu mi Em WM Fuhllsher Mmees anal Programming Banks 7 1 an i 39 MURACH 51 u alums ream 9m enm 2am swim nnw ust 53675 quotitL39EJDNJalarVDX tcum giu lolhe m m marsh is e Mm ii iEW DfTi f v Coegm s39irihei i Even euer noursmmgioieemu in seems we m use rm rJaua m 2 reamed firm m m r mm chM Thais whaluns detel l ar Mule us emmne JDK 5 edilmn m mircnrern mi Haw Ynu can exuectllialsame piactical iHnWmUsean DE ysrsmnauava JavaSEE M i m EEEEQOWMGOO What you39ll learn from the SE E euman v e1 We 9 Wm The second page of a shopping cart application v I Ll39ieem limsulavcamvmdunia Publisher of Prolessional Programmmg Books vrwm MURACH Your cart 7 Descnpliun lluracli s iiamvreme COBOL nemwe To change memanmy antenna new uuanm and cllcl39 an we update mmen Continue Shopping Proceed lu Checkout Ei Do on have a promouon conem DDly no this order llsu emerilhere i E O Intim t Figure 11 A typical web application Section 1 Introduction to servlet and JSP programming The components of a web application Figure 1 2 shows the basic components that make up a web application Because a web application is a type of clientserver application the components of a web application are stored on either the client computer or the server computer To access a web application you use a web browser that runs on a client computer The most widely used web browser is Microsoft s Intemet Explorer and the most popular alternative is Mozilla Firefox The web application itself is stored on the server computer This computer runs web server software that enables it to send web pages to web browsers Although there are many web servers the most popular one for Java web applications is the Apache Software Foundation s Apache HTTP Server which is usually just called Apache Because most web applications work with data that s stored in a database most servers also run a database management system DBMS Two of the most popular for Java development are Oracle and MySQL Note however that the DBMS doesn t have to run on the same server as the web server software In fact a separate database server is often used to improve an application s overall performance Although this figure shows the client and server computers connected via the Internet this isn t the only way a client can connect to a server in a web application If the client and the server are on the same Local Area Network LAN they function as an intranet Since an intranet uses the same protocols as the Internet a web application works the same on an intranet as it does on the Internet Chapter 1 Components of a web application Sewer computer Client computer Internet connection Web browser W6b server Database server Description Figure 12 Web applications are a type of clientserver application In a clientserver application a user at a client computer accesses an application at a server computer For a web appli cation the client and server computers are connected via the Internet or an intranet In a web application the user works with a web browser at the client computer The web browser provides the user interface for the application The most widely used web browser is Microsoft s Intemet Explorer but other web browsers such as Mozilla Firefox are also widely used A web application runs on the server computer under the control of web server software For Java web applications the Apache server is the most widely used web server For most web applications the server computer also runs a database management system DBMS For servlet and JSP applications Oracle and MySQL are two of the most popular database management systems The components of a web application An introduction to web programming with Java Section 1 Introduction to servlet and JSP programming How static web pages work HTML Hypertext Markup Language is the language that the browser renders to the web pages that make up a web application s user interface Many of these web pages are static web pages which are the same each time they are viewed In other words they don t change in response to user input Figure 1 3 shows how a web server handles static web pages The process begins when a user at a web browser requests a web page This can occur when the user enters a web address into the browser s Address box or when the user clicks a link that leads to another page In either case the web browser uses a standard Internet protocol known as Hypertext Transfer Protocol HTTP to send a request known as an HTTP request to the web site s server When the web server receives an HTTP request from a browser the server gets the requested HTML le from disk and sends the le back to the browser in the form of an HTTP response The HTTP response includes the HTML document that the user requested along with any other resources speci ed by the HTML code such as graphics les When the browser receives the HTTP response it renders the HTML document into a web page that the user can view Then when the user requests another page either by clicking a link or typing another web address in the browser s Address box the process begins again Chapter 1 An introduction to web programming with Java How a web server processes static web pages Client Server H39I39I39P request Browser I Web server HTML file I HTTP response Description Hypertext Markup Language HTML is the language that the web browser converts into the web pages of a web application A static web page is an HTML document that s stored in a file and does not change in response to user input Static web pages have a lename with an extension of him or Hypertext Transfer Protocol HTTP is the protocol that web browsers and web servers use to communicate A web browser requests a page from a web server by sending the server a message known as an HTTP request For a static web page the HTTP request includes the name of the HTML le that s requested 0 A web server replies to an HTTP request by sending a message known as an HTTP response back to the browser For a static web page the HTTP response includes the HTML document that s stored in the HTML le Figure 13 How static web pages work 10 Section 1 Introduction to servlet and JSP programming How dynamic web pages work In contrast to a static web page a dynamic web page changes based on the parameters that are sent to the web application from another page For instance when the Add To Cait button in the rst page in gure 1 1 is clicked the static web page calls the web application and sends one parameter to it Then the web application generates the dynamic web page and sends the HTML for it back to the browser Figure 1 4 shows how this works When a user enters data into a web page and clicks the appropriate button the browser sends an HTTP request to the server This request contains the address of the next web page along with any data entered by the user Then when the web server receives this request and determines that it is a request for a dynamic web page it passes the request back to the web application When the web application receives the request it processes the data that the user entered and generates an HTML document Next it sends that document to the web server which sends the document back to the browser in the form of an HTTP response Then the browser displays the HTML document that s in cluded in the response so the process can stait over again Chapter 1 An introduction to web programming with Java 1 1 How a web server processes dynamic web pages Client Server HTTP request Browser Web server I HTTP response Description 0 A dynamic web page is an HTML document that s generated by a web application Often the web page changes according to parameters that are sent to the web application by the web browser Web application When a web server receives a request for a dynamic web page the server passes the request to the web application Then the application generates a response which is usually an HTML document and returns it to the web server The web server in turn wraps the generated HTML document in an HTTP response and sends it back to the browser The browser doesn t know or care whether the HTML was retrieved from a static HTML le or was dynamically generated by the web application Either way the browser displays the HTML document that is returned Figure 14 How dynamic web pages work Section 1 Introduction to servlet and JSP programming An introduction to Java web programming In the early days of J ava Java received much attention for its ability to create applets These are Java applications that can be downloaded from a web site and run within a web browser However once Microsoft s Internet Explorer stopped supporting new versions of J ava applets lost much of their appeal As a result many developers switched their attention to servlets and JavaServer Pages JSPs These technologies allow developers to write Java web applica tions that run on the server The components of a Java web application Figure 1 5 shows the primary software components for a Java web applica tion By now you should understand why the server must run web server software To run a Java application though the server must also run a software product known as a servletJSP engine or servletJSP container This software allows a web server to run servlets and J SPs Sun s Java Enterprise Edition Java EE speci cation describes how a servletJ SP engine should interact with a web server Since all servletJ SP engines must implement this specification all servletJ SP engines should work similarly In theory this makes servletJ SP code portable between servletJSP engines and web servers In practice though there are minor differences between each servletJ SP engine and web server As a result you may need to make some modifications to your code when switching servletJ SP engines or web servers Tomcat is a free open source servletJ SP engine that was developed by the Jakarta project at the Apache Software Foundation This engine is the official reference implementation of the servletJ SP specification set forth by Sun and it s one of the most popular servletJ SP engines In the next chapter you ll learn how to install and use Tomcat on your own computer For a servletJ SP engine to work properly the engine must be able to access the Java Development Kit JDK that comes as part of the Java Standard Edition Java SE The JDK contains the Java compiler and the core classes for working with Java It also contains the Java Rantime Environment JRE that s necessary for running compiled Java classes Since this book assumes that you already have some Java experience you should already be familiar with the JDK and the J RE Many large websites also use a Java technology known as Enterprise JavaBeans EJBs To use EJBs the server must run an additional piece of software known as an EJB server or EJB container Although there are some benefits to using EJBs they re more difficult to use when you re first learning how to code Java web applications and they can make web applications unnec essarily complex That s why this book shows 110w to develop web applications without using EJBs Chapter 1 An introduction to web programming with Java 13 The components of a Java web application Client Browser HTTP request HTTP response Server Web server ServletJSP engine Java Development Kit JDK Database server Description lava web applications consist of JavaServer Pages and servlets You ll learn more about them in the next two gures A servletJSP engine or servletJSP container is the software that allows the web server to work with servlets and JSPs The Java Enterprise Edition Java EE speci cation describes how web servers can interact with servletJ SP engines Tomcat is one of the most popular servletJ SP engines It was developed by the Jakarta project at the Apache Software Foundation For a servletJ SP engine to work it must have access to Java s Java Development Kit JDK which comes as part of the Java Standard Edition Java SE Among other things the DK contains the core Java class libraries the Java compiler and the Java Rantime Environment JRE lava web applications that use Enterprise JavaBeans EJBs require an additional server component known as an EJB server or EJB container As a result they won t run on the Tomcat server Figure 15 The components of a Java web application 14 Section 1 Introduction to servlet and JSP programming An introduction to JavaServer Pages To give you a better idea how JavaServer Pages JSPS work part 1 of gure 1 6 shows a simple I SP displayed in a browser Then part 2 of this gure shows the code for the J SP In the Address box of the browser the address of the J SP ends with a jsp extension After that the address includes a question mark followed by the parameters that are passed to the J SP Finally the body of the web page displays the values of these parameters in a table For example the value of the rstName parameter is John and this value is displayed in the rst row of the table Chapter I An introduction to web programing with Java A JSP that displays three parameters entered by the user i 1 5 gag 695in E Thanks for joining our email list Here is the mfmnmh that you entered First name i John Lu name i Smith Email address Jinn 4 To enter another Email address dick on the Back button in m hm ser m the Return button Sham below new ugtqzsimam Description 0 A JavaServer Page or JSP consists of Java code that is embedded within HTML code This makes it easy to write the HTML portion of a JSP but harder to write the Java code 0 When a JSP is rst requested the JSP engine translates it into a servlet and compiles it Then the servlet is run by the servlet engine Figure 16 An introduction to JavaSener Pages part 1 of 2 15 16 Section 1 Introduction to servlet and JSP programming In part 2 of this figure you can see the code for this JSP If you re already familiar with HTML you can see that most of this code consists of HTML code In fact the only Java code in this J SP is shaded That makes J SPs easy to write if you know HTML and if you are able to keep the Java code to a mini mum If a J SP requires extensive Java programming though it s easier to write the Java code with a servlet In practice web designers often write the HTML portions of the J SPs while web programmers write the Java portions In case you re interested the rst three lines of Java code in this J SP get three parameters from the request object that has been passed to it To do that the code uses the getParameter method of the built in request object and it stores the values of these parameters in three String variables Then the three Java expressions that are used later in the J SP refer to the String variables that store the values of the parameters When a J SP is requested for the rst time the JSP engine which is part of the servletJ SP engine converts the J SP code into a servlet and compiles the servlet Then the J SP engine loads that servlet into the servlet engine which runs it For subsequent requests the J SP engine runs the servlet that corre sponds to the J SP In chapter 4 you ll get a crash course in HTML that will teach you all the HTML you need to know for writing J SPs Then in chapter 5 you ll learn how to combine HTML code with Java code as you write J SPs When you re done with those chapters you ll know how to write signi th J SPs of your own quotgt lthtmlgt ltheadgt lttitlegtMurach39s Java Servlets and JSPlttitlegt ltheadgt ltbodygt lt96 get parameters from the request String firstName requestgetParameterquotfirstNamequoti String lastName equestgetParameterquotlastNamequot String emailAddress requestgetParameterquotemailAddressquoti gt lthlgtThanks for joining our email listlthlgt ltpgtHere is the information that you enteredltpgt lttable cellspacingquot lttrgt cellpadding39 quot border lttd alignquotrightquotgtFirst namelttdgt lttdgtlt firstName gtlttdgt lttrgt lttrgt lttd alignquotrightquotgtLast namelttdgt lttdgtlt lastName gtlttdgt lttrgt lttrgt lttd alignquotrightquotgtEmail addresslttdgt lttdgtlt emailAddress gtlttdgt lttrgt lttablegt ltpgtTo enter another email address click on the Back ltbrgt button in your browser or the Return button shown ltbrgt belowltpgt ltform actionquotjoin7emaililisthtmlquot met hodquotgetquotgt put typequotsubmitquot valuequotReturnquotgt ltformgt ltbodygt lthtmlgt Figure 16 An introduction to JavaServer Pages part 2 of 2 18 Section 1 Introduction to servlet and JSP programming An introduction to servlets To give you a better idea of how servlets work gure 1 7 shows a servlet that generates the same web page as the J SP in gure 1 6 In short a servlet is a Java class that runs on a server and does the processing for the dynamic web pages of a web application That s why servlets for a web application are written by web programmers not web designers After the processing is done a servlet can return HTML code to the browser by using the println method of an out object Note however that this makes it more dif cult to code the HTML If you study the code in this gure you can see that each servlet is a Java class that extends or inherits the HttpServlet class Then each servlet can override the doGet method of the inherited class which receives both a request and a response object from the web server and the servlet can get the param eters that have been passed to it by using the getParameter method of the request object After that the servlet can do whatever processing is required by using normal Java code In chapter 6 you ll learn the details for coding servlets When you complete that chapter you ll be able to write signi cant servlets of our own How to combine servlets and JSPs in a web application When you re developing Java web applications you will usually want to use a combination of servlets and J SPs so you get the bene ts of both As you have seen servlets are actually Java classes As a result it makes sense to use them for the processing requirements of a web application Similarly J SPs are primarily HTML code so it makes sense to use them for the design of the web pages in an application But how can you do that in an ef cient way The solution is for the servlets to do the processing for the application and then forward the request and response objects to a J SP That way the servlet does the processing and the J SP provides the HTML for the user interface With this approach the J SP requires a minimum of embedded Java code And that means that the web designer can write the J SPs with minimal interaction with the Java programmer and the Java programmer can write the servlets without worrying about the HTML In chapter 7 you ll learn how to use this approach for developing web applications You ll also learn how to use the Model Controller View MVC pattern to structure your applications so they re easy to manage and maintain When you nish that chapter you ll know how to develop Java web applica tions in a thoroughly professional manner Chapter 1 An introduction to web programming with Java 19 The code for a servlet that works the same as the JSP in figure 16 package email import javaio import javaxservlet import javaxservlethttp public class DisplayEmailListServlet extends HttpServlet protected void doGet HttpServletRequest request HttpServletResponse response throws ServletException IOException get parameters from the request String firstName requestgetParameterquotfirstNamequoti String lastName requestgetParameterquotlastNamequoti requestgetParameterquotemailAddressquoti String emailAddress return response to browser responsesetContentTypequottexthtmlcharsetUTF Bquoti PrintWriter out responsegetWriter outprintln quotltidoctype html public quot W3CDTD HTML 40 TransitionalENquotgtnquot quotlthtmlgtnquot quotltheadgtnquot quot lttitlegtMurach s Java Servlets and JSPlttitlegtnquot quotltheadgtnquot quotltbodygtnquot quotlthlgtThanks for joining our email listlthlgtnquot quotltpgtHere is the information that ou enteredltpgtnquot table cellspacingquot5quot cellpaddingquot5quot borderquotlquotgtnquot quot lttrgtlttd alignquotrightquotgtFirst namelttdgtnquot quot lttdgtquot firstName quotlttdgtnquot quot lttrgtnquot quot lttrgtlttd alignquotrightquotgtLast namelttdgtnquot quot lttdgtquot lastName quotlttdgt nquot quot lttrgtnquot lttrgtlttd alignquotrightquotgtEmail addresslttdgtnquot quot lttdgtquot emailAddress quotlttdgtnquot quot lttrgtnquot quot lttablegtnquot quotltpgtTo enter another email address click on the Back ltbrgtnquot IIbutton in your browser or the Return button shown ltbrgt quot quotbelowltpgtnquot quotltform actionquotjoiniemaililisthtmlquot gtnquot quot ltinput typequotsubmitquot valuequotReturnquotgtnquot quotltformgtnquot quotltbodygtnquot quotlthtmlgtnquot outclose i Figure 17 An introduction to servlets 20 Section 1 Introduction to servlet and JSP programming An introduction to Java web development This topic introduces you to servletJ SP development In particular it presents some of the hardware and software options that you have as you develop Java web applications Three environments for servlet and JSP development Figure 1 8 shows the three possible environments that you can use to develop servlets and JSPs First you can use a single computer Second you can use a Local Area Network or LAN Third you can use the Intemet When you use a single computer you need to install all of the required software on that computer That includes the JDK the web server software the servletJ SP engine and the database management system To make this easy you can use Tomcat as both the web server and the servletJ SP engine Then you can use MySQL as the database server In the next chapter you ll learn how to install Tomcat and you can learn how to install the other components in appendix A When you work over a LAN it functions as an intranet In this development environment you can use the same software components as you do on your own computer but you divide them between client and server To compile and run servlets on the server the server requires the JDK a web server and servletJ SP engine like Tomcat and a DBMS like MySQL Then the client just needs the JDK and the JAR les for any classes that aren t available from the JDK For example to compile servlets on a client the client requires the servletjar file which contains all of the classes required for servlet development These JAR files come with Tomcat and you ll learn more about them in the next chapter When you work over the Intemet you use the same general components as you do when you work over an intranet To improve performance though you can use a dedicated web server like Apache together with a dedicated servlet J SP engine like Tomcat If necessary you can also improve the performance of an intranet application by using Apache as the web server Since the JDK Apache Tomcat and MySQL can be run by most operating systems Java web developers aren t tied to a specific operating system In fact the Windows operating system is commonly used for the client computers during development But when the applications are ready for use they are often deployed to a Unix or Solaris server Chapter 1 An introduction to web programming with Java 21 Three environments for servlet and JSP development Standalone development JDK Java EE JAR files JDK Tomcat MySQL LAN connection Client Internet development JDK JDK Java EE JAR files Tomcat Apache Internet MySQL connection Client Sener Description 0 When you develop web applications you can set up your development environment in several different ways 0 If you want to develop web applications on your own computer you need to install the JDK a web server a servletJ SP engine and a DBMS In this case it s common to use Tomcat as both the web server and the servletJ SP engine and MySQL as the DB MS 0 If you re working in a group over an intranet the server can run Tomcat as the web server and the servletJSP engine and it can run MySQL as the DBMS Then the client just needs the JDK and the JAR files for any classes that aren t available from the JDK At the least the client will need the servlet apijar jsp apijar and el apijar les that contain standard Java EE classes for working with servlets and JSPs o If you re working in a group over the Intemet you may want to use a web server such as Apache and a dedicated servletJ SP engine like Tomcat Otherwise this works the same as when you re working over a LAN Figure 18 Three environments for servlet and JSP development 22 Section 1 Introduction to servlet and JSP programming The architecture for a Java web application Figure 1 9 shows the architecture for a typical web application that uses servlets and J SPs This architecture uses three layers 1 the presentation layer or user interface layer 2 the business rules layer and 3 the data access layer In theory the programmer tries to keep these layers as separate and independent as possible In practice though these layers are often interrelated and that s especially true for the business and data access layers The presentation layer consists of HTML pages and J SPs Typically a web designer will work on the HTML stored in these pages to create the look and feel of the user interface Later a Java programmer may need to edit these pages so they work properly with the servlets of the application The business rules layer uses servlets to control the ow of the application These servlets may call other Java classes to store or retrieve data from a database and they may forward the results to a J SP or to another servlet Within the business layer Java programmers often use a special type of Java class known as a JavaBean to temporarily store and process data A J avaB ean is typically used to define a business object such as a User or Invoice object The data layer works with data that s stored on the server s disk For a serious web application this data is usually stored in a relational database However this data can also be stored in text les and binary files In addition the data for an application can be stored in an Extensible Markup Language XML file Chapter 1 An introduction to web programming with Java 23 The architecture for a typical Java web application Presentation layer HTML files JSP files Business rules layer Senlets JavaBeans OtherJava classes Data access layer Data access classes Database Binanl files Description 0 The presentation layer for a typical Java web application consists of HTML pages and SPs The business rules layer for a typical lava web application consists of servlets These servlets may call other Java classes including a special type of Java class known as a JavaBean In chapters 9 and 10 you ll learn how to use several special types of tags within a J SP to work with JavaBeans The data access layer for a typical Java web application consists of classes that read and write data that s stored on the server s disk drive For a serious web application the data is usually stored in a relational database How ever it may also be stored in binary les in text les or in Extensible Markup Language or XML les Figure 19 The architecture for a Java web application 24 Section I Introduction to servlet and JSP programming lDEs for developing Java web applications In the early days of Java web programming programmers commonly used text editors to enter edit compile and test the HT ML J SP Java servlet and XML les that make up a web application Today however many Integrated Development Environments IDES are available that make Java web program ming far more ef cient Two of the most popular lDEs for developing Java web applications are NetBeans and Eclipse Both are open source and both are available for free Of the two we think that NetB eans is easier to use especially when you re getting started with web programming That s why we recommend that you use NetBeans with this book In figure 1 10 for example you can see the NetBeans lDE with the project for chapter 7 in the Projects window the code for a servlet class in the editor window and nultime messages in the Output window This is similar to what you ll find in most IDEs As a result once you re done with this book you can easily apply the skills that you learn with NetB eans to another lDE Although we recommend using NetB eans with this book you should be able to use another lDE with this book if you prefer To do that though you will need to gure out how to import the source code for this book into your lDE so you can compile and run the sample applications and complete the exercises In addition you will need to use the documentation that s available for your lDE to learn 110w to perform the tasks presented in chapter 3 Chapter I An introduction to web programming with Java 25 The NetBeans IDE tiara Web Pages mmw Mam in m m aispiwmai m is fake by a ESPD email ESPNASE nsEi WEMWSEMEW chums VlecExcEptlmA IOExcEptlon YestPazkaqes requestQEEPaLam i Scrlng lair Zuni ge a a Scrlng emalllddxess riquesngecPazam r Started mummy a new pm chmemi mp llacahs Emumama Popular lDEs for Java web development NetBeans Eclipse JBuilder IntelliJ IDEA Description An Integrated Development Environment IDE is a tool that provides all of the function ality that you need for developing web applications NetBeans and Eclipse are popular lDEs for Java web development that are opensource and ree In chapter 3 you will learn how to use NetBeans for developing Java web applications This is the IDE that we recommend for use with this book Figure 110 IDES for developing Java web applications 26 Section 1 Introduction to servlet and JSP programming Tools for deploying Java web applications Once you ve tested your servlets and JSPs on your own computer or an intranet you may want to deploy your web application on the Internet To do that you need to get a web host One way to do that is to nd an Internet service provider ISP that provides web hosting that supports servlets and JSPs If you read the text for the ISP on the web page shown in gure 1 11 for example you can see that this ISP supports servlets and JSPs If you search the web you ll be able to nd many other ISPs and web hosts Just make sure that the one you choose not only supports servlet and JSP development but also the database management system that your application requires When you select a web host you get an IP address like 647117986 that uniquely identi es your web site IP stands for Intemet Protocol Then you can get a domain name like wwwmurachcom To do that you can use any number of companies that you can nd on the Internet Until you get your domain name you can use the IP address to access your site After you get a web host you need to transfer your les to the web server To do that you can use File Transfer Protocol FTP The easiest way to use FTP is to use an FT P client such as the FileZilla client shown in this gure A11 FTP client like this one lets you upload les from your computer to your web server and download les from your web server to your computer Chapter 1 An introduction to web programing with Java An ISP that provides web hosting that supports servlets and JSPs Lia refnx web hosting sales lt716gt 5291593 MM r r Nani mnAlumlman Private sum mm qtw Account Dam ia iE a domain an 522 W ymirs is avaiiahie by checking mm b 39 cnwi gcmw 49 9 Maggian 23 W 53 JSF hustng and seniet hustng accuunts with advanced scziabie ssmsrtschhuiugies iiks Senleis Java Server Pages JSP Emerprise Java sans Java Develuner Links m resiiit is a cuntmuuus upgrade path that iets smaii businesses iaunch websites innit un prmsn tshhuiug139that can grow as vuu achi uncess witimut we need The FileZilla m2 Javasener iaSErMEr Page iziszms s z Figure 111 Tools for deploying Java web applications 27 28 Section 1 Introduction to servlet and JSP programming Perspective The goal of this chapter has been to provide the background that you need for developing servlets and J SPs Now if this chapter has succeeded you should be ready to install Tomcat on your own computer as shown in the next chapter Then you ll be ready to install the NetBeans IDE on your computer as shown in chapter 3 Summary A web application is a set of web pages that are generated in response to user requests To run a web application the client requires a web browser and the server requires web server software The server may also require a database management system DBMS Hypertext Markup Language HTML is the language that the browser converts into the user interface while Hypertext Transfer Protocol HTTP is the protocol that web browsers and web servers use to communicate A web browser requests a page from a web server by sending an HTTP request A web server replies by sending an HTTP response back to the browser A static web page is generated from an HTML document that doesn t change while a dynamic web page is generated by a web application based on the param eters that are included in the HTTP request To run Java web applications the server requires the Java Development Kit JDK and a servletJSP engine like Tomcat A JavaServer Page JSP consists of HTML with embedded Java code When it is requested the J SP engine generates a servlet from the J SP and compiles that servlet Then the servlet engine runs that servlet A servlet is a Java class that runs on a server For web applications a servlet extends the HttpServlet class To pass HTML back to the browser a servlet can use the println method of the out object When you develop a Java web application you can use servlets to do the process ing that s required and J SPs to present the user interface You can develop servlets and J SPs on your own computer on a Local Area Network LAN that functions as an intranet and on the Internet When you use the Intemet it s common to use a web server that s separate from the servletJ SP engine As you develop a Java web application you try to divide its classes into three layers presentation business rules and data access This makes it easier to manage and maintain the application TRAINING amp REFERENCE murach39s Java and JSP Chapter 1 1 Thanks for downloading this chapter from Murach s lava Servlets and lSP 2nd Edition We hope it will show you how easy it is to learn from any Murach book with its pairedpages presentation its howto headings its practical coding examples and its clear concise style To view the full table of contents for this book you can go to our web site From there you can read more about this book you can nd out about any additional downloads that are available and you can review our other books for professional developers Thanks for your interest in our books MIKE MURACH amp ASSOCIATES INC 18002215528 559 4409071 Fax 559 4400963 murachbooks1nurachcom wwwmurachcom Copyright 2008 Mike Murach amp Associates All rights reserved Contents Introduction Section 1 Chapter 1 Chapter 2 Chapter 3 Section 2 Chapter 4 Chapter 5 Chapter 6 Chapter 7 Chapter 8 Chapter 9 Chapter 10 Chapter 11 Chapter 12 Section 3 Chapter 13 Chapter 14 Section 4 Chapter 15 Chapter 16 Chapter 17 Chapter 18 Chapter 19 Chapter 20 Section 5 Chapter 21 Chapter 22 Chapter 23 Chapter 24 Resources Appendix A Index Introduction to servlet and JSP programming An introduction to web programming with Java How to install and use Tomcat How to use the NetBeans IDE Essential servlet and JSP skills A crash course in HTML How to develop JavaServer Pages How to develop servlets How to structure a web application with the MVC pattern How to work with sessions and cookies How to use standard I SP tags with JavaBeans How to use the J SP Expression Language EL How to use the J SP Standard Tag Library J STL How to use custom J SP tags Essential database skills How to use MySQL as the database management system How to use JDBC to work with a database Advanced servlet and JSP skills How to use JavaMail to send email How to use SSL to work with a secure connection How to restrict access to a web resource How to work with HTTP requests and responses How to work with listeners How to work with filters The Music Store web site An introduction to the Music Store web site The Download application The Cart application The Admin application How to set up your computer for this book xvii 29 61 105 137 173 201 243 287 311 337 375 415 441 487 513 531 555 583 599 623 649 661 683 703 719 11 How to use the JSP Standard Tag Library JSTL In chapter 10 you learned how to use the Expression Language EL that was introduced with J SP 20 to reduce the amount of scripting in your applications Now in this chapter you ll learn how to use the J SP Standard Tag Library JSTL to further reduce the amount of scripting in your applications In fact for most applications using JSTL and EL together makes it possible to remove all scripting to JSTI An 39 39 The J STL libraries How to make the JSTL JAR les available to your application How to code the taglib directive How to code a JSTL tag How to view the documentation for a library How to work with the JSTL core library 342 How to use the url tag How to use the forEach tag How to use the forTokens tag Four more attributes for looping How to use the if tag How to use the choose tag How to use the import tag Other tags in the JSTL core library The Cart application 358 The user interface 358 The code for the business classes 360 The code for the servlets and JSPs 364 r 372 338 Section 2 Essential servlet and JSP skills An introduction to JSTL The JSP Standard Tag Library JSTL provides tags for common tasks that need to be performed in JSPs The JSTL libraries Figure 11 1 shows the five tag libraries that are included with JSTL 11 In this chapter you ll learn the details for working with the common tags in the core library This library contains tags that you can use to encode URLs loop through collections and code ifelse statements If you use the MVC pattern the tags in the core library are often the only JSTL tags you ll need as you develop your JSPs If necessary though you can use the other four libraries to work with internationalization databases XML or strings How to make the JSTL JAR files available to your application Before you can use JSTL tags within an application you must make the jstl jar and standard jar files available to the application With the NetBeans IDE for example you can add the JSTL ll library to the application as shown in figure 3 17 in chapter 3 Then the jstljar and standardjar files will be shown beneath the Libraries folder in the Projects window How to code the taglib directive Before you can use JSTL tags within a JSP you must code a taglib directive to specify the URI and prefix for the JSTL library In this figure for example the taglib directive specifies the URI for the JSTL core library with a prefix of c which is the prefix that s typically used for this library In fact all of the ex amples in this chapter assume that the page includes a taglib directive like this one before the JSTL tags are used Although you can use different pre xes than the ones in this figure we recommend using the standard prefixes How to code a JSTL tag Once you ve added the appropriate JAR files to your application and used the taglib directive to identify a library you can code a JSTL tag In this figure for example the url tag is used to encode a URL that refers to the indexjsp file in the web applications root directory Note how the pre x for this tag is c Also note how this tag looks more like an HTML tag which makes it easier to code and read than the equivalent J SP script especially for web designers and other nonprogrammers who are used to HTML syntax Chapter 11 How to use the JSP Standard Tag Library JSTL 339 The primary JSTL libraries r r r 1 Core e httpIhavasuneomhsphstleore Contains the core tags for oommon tasks such as looping and ifelse statements Formatting fmt httpIhavasuneomhsphstlhnt Provides tags for formatting numbers times and dates so they work correctly with internationalization i18n SQL sql httpIhavasuneomhsphstlsql Provides tags for work39 g with SQL queries and data souroes XML x httpjavasuneomhsphstlrrml Provides tags for manipulating XML documents Functions fn hw 39 39 39 39 Pr id 39 be used to manipulate strings The NetBeans IDE after the JSTL 11 library has been added Pro 115 n x Files Rumlme ark g9 rnllr w m1y my r 5 Deraulll its su The taglib directive that specifies the JSTL core library lt aglib pref1xquotcquot ur1quothpjavasuneomjspjs1eorequot gt An example that uses JSTL to encode a URL JSP code with JSTL lta hrefquotltcur1 vaiue1ndexjsp gtquotgtcon1nue Shoppingltagt Equivalent script hrefquotltresponseencodeURL indexjsp gtquotgtContinue Shoppingltagt Description 0 The JSP Standard Tag Library JSTL provides tags for common JSP tasks 0 Before you can use JSTL tags within an application you must make thejstljar and standardjar les available to the application To do that for NetBeans you can add the JSTL 11 class library to your project as in figure 3717 in chapter 3 Otherwise you can consult the documentation for your IDE Before you can use JSTL tags within a JSP you must code a taglib directive that identir fies the JSTL library and its pre x Figure 111 An introduction to JSTL 340 Section 2 Essential servlet and JSP skills How to View the documentation for a library As you progress through this chapter you ll learn how to code the tags in the JSTL core library that you ll use most of the time If necessary though you can view the documentation for any of the tags in this library as shown in gure 1 12 If for example you want to learn more about the url tag in the core library you can click on the JSTL core link in the upper left window Then you can click on the curl link in the lower left window to display the documentation for this tag in the window on the right This documentation provides a general description of the tag a list of all available attributes for the tag and detailed information about each of these attributes You can also use this documentation to learn more about the JSTL libraries that aren t covered in this chapter If for example you want to learn more about the formatting library for working with internationalization you can click on the JSTL fmt link in the upper left window Then you can click on the tags in the lower left window to display information in the window on the right Inciden tally i18n is sometimes used as an abbreviation for internatianalizatian because internatianalizatian begins with an i followed by 18 letters followed by an n Chapter 11 How to use the JSP Standard Tag Library JSTL 341 The URL forthe JSTL11 documentation hm5P 39 quotquot J I J u11 html A browser that displays the JSTL documentation TLDDoc Gener2 Overview leram Helg AiiTJgs Fundim WES WM 51 core Tag url Creates 1 L121 mm optional query parameters JSTL core T Description 0 To View the documentation for the JSTL ll library use your browser to visit the URL shown above Then you can use the upper left window to select the JSTL library the lower left window to select the tag and the window on the right to get information about the tag Figure 112 How to view the documentation for a library 342 Section 2 Essential servlet and JSP skills How to work with the JSTL core library Now that you have a general idea of 110w JSTL works you re ready to learn the details for coding the most commonly used JSTL tags All of these tags are available from the JSTL core library How to use the url tag In chapter 8 you learned how to encode the URLs that are returned to the client so your application can track sessions even if the client doesn t support cookies Since you usually want your application to do that you typically encode the URLs in your applications Without JSTL though this requires calling the encodeURL method of the response object from a script within a l SP With lSTL you can use the url tag to encode URLs without using script mg Figure 11 3 shows 110w to use the url tag Here the first example shows the same url tag that s presented in figure 11 1 This url tag encodes a relative URL that refers to the indexjsp file in the root directory for the web application Its value attribute is used to specify the URL When you specify JSTL tags you need to be aware that they use XML syntax not HTML syntax As a result you must use the exact capitalization shown in this example for the name of the tag and its attributes In addition attributes must be enclosed in either single quotes or double quotes In this figure I have used both single and double quotes to differentiate between the href attribute of the A tag which uses double quotes and the value attribute of the url tag which uses single quotes I think this improves the readability of this code The second example shows 110w to use the url tag to encode a URL that includes a parameter named productCode with a hard coded value of 8601 Then the third example shows 110w to use the url tag to encode a URL that includes a parameter named productCode with a value that s supplied by an EL expression Here the EL expression gets the code property of a Product object named product The third example also shows how you can code a JSTL param tag within a url tag to specify the name and value for a parameter The benefit of using this tag is that it automatically encodes any unsafe characters in the URL such as spaces with special characters such as plus signs If you compare the url tags in these examples with the equivalent scripting I think you ll agree that the JSTL tags are easier to code read and maintain In addition the syntax is closer to HTML than scripting which makes it easier for web designers and other nonprogrammers to use Chapter 11 How to use the JSP Standard Tag Library JSTL 343 An example that encodes a URL JSP code with JSTL lta hrefquotltcurl value39indexjsp39 gtquotgtContinue Shoppingltagt Equivalent scripting lta hrefquotltresponseencodeURLquotindexjspquotgtquotgtContinue Shoppingltagt An example that adds a parameter to the URL JSP code with JSTL lta hrefquotltcurl value39cartproductCode860139 gtquotgt Add To Cart ltagt Equivalent scripting lta hrefquotltresponseencodeURLquotcartproductCode8601quotgtquotgt Add To Cart ltagt An example that uses EL to specify the value of a parameter value JSP code with JSTL lta hrefquotltcurl value39cartproductCodeproductcode39 gtquotgt Add To Cart ltagt The same code with the JSTL param tag lta hrefquot ltcurl value39cart39gt ltczparam name39productCode39 value39productcode39 gt ltcurlgt IIgtAdd To Cartltagt Equivalent scripting lt page importquotbusinessProductquot gt lt Product product Product sessiongetAttributequotproductquoti String cartUrl quotcartproductCodequot productgetCode gt lta hrefquotltresponseencodeURLcartUrlgtquotgtAdd To Cartltagt Description 0 You can use the url tag to encode URLs within your web application This tag will automatically rewrite the URL to include a unique session 1D whenever the client doesn t suppOIt cookies You can use the JSTL param tag if you want to automatically encode unsafe characters such as spaces with special characters such as plus signs Figure 113 How to use the url tag 344 Section 2 Essential servlet and JSP skills How to use the forEach tag You can use the forEach tag to loop through items that are stored in most collections including arrays For example gure ll 4 shows how to use the forEach tag to loop through the Lineltem objects that are available from the items property of the cart attribute Here the var attribute specifies a variable name of item to access each item within the collection Then the items attribute uses EL to specify the collection that stores the data In this case the collection is the ArrayListltLineItemgt object that s returned by the getltems method of the Cart object for the current session This Cart object has been stored as an attribute with a name of cart Within the forEach loop the J SP code creates one row with four columns for each item in the cart Here each column uses EL to display the data that s available from the Lineltem object In particular the first column displays the quantity the second column displays the product description the third column displays the price per item and the fourth column displays the total amount quantity multiplied by price Note that the Lineltem object includes code that applies currency formatting to the price and amount If you have trouble understanding the examples in this figure you may want to study the code for the Cart Lineltem and Product objects that are presented in figure 11 12 In particular note how a Cart object can contain multiple Lineltem objects and how a Lineltem object must contain one Product object Also note how the appropriate get methods are provided for all of the properties that are accessed by EL For example the Cart class provides a method named getltems that retums an ArrayList of Lineltem objects As a result with EL you can use the items property of the cart attribute to get this ArrayList object If necessary you can nest one forEach tag within another For example if you wanted to display several Invoice objects on a single web page you could use an outer forEach tag to loop through the Invoice objects Then you could use an inner forEach tag to loop through the Lineltem objects within each invoice However for most JSPs you won t need to nest forEach statements If you compare the JSTL tags shown in this figure with the equivalent scripting I think you ll agree that the benefits of the JSTL tags are even more apparent in this figure than in the last one In particular the J SP code that uses ISTL is much shorter and easier to read than the equivalent scripting As a result it s easier for web designers and other nonprogrammers to work with this code Chapter 11 How to use the JSP Standard Tag Library JSTL 345 An example that uses JSTL to loop through a collection JSP code with JSTL varquotitemquot itemsquotcartitemsquotgt p gt ltdgts1emquan1yltdgt tam roducdescriptionlttdgt lttdgtitamtproduct ricecurrencyFormatlttdgt lttdgtiemtotalcurrencyFormatlttdgt A n H lt m t Lu ltrgt ltcforEachgt The result that s displayed in the browser for a cart that has two items Your cart Quantity Desrriptinn i Price Amount 1 5 the band 7 True Ln e Snug and Pictures 1 Paddlefmr 7 Th Brit CD Equivalent scripting lt page imporquotbusiness javauilArrayListquot 2 lt2 car car Cart sessiongetAttributequotcartquot 2 ArrayListltLineItemgt items carge1enus 2 for LineItem item items slsgt ltr valignquoto quotgt lttdgtltitemgetQuantitygtltdgt lttdgtlt 1temgetProductgetDescriptiongtlttdgt n n m lttdgtltite ltrgt lt2 a gtlt dgt mgeTotalCurrencyFormat gtltdgt Description 0 You can use the forEach tag to loop through most types of collections including arrays You can use the var attribute to specify the variable name that will be used to access each item within the collection You can use the items attribute to specify the collection that stores the data If necessary you can nest one forEach tag within another Figure 114 How to use the forEach tag 346 Section 2 Essential servlet and JSP skills How to use the forTokens tag You can use the forTokens tag to loop through items that are stored in a string as long as the items in the string are separated by one or more delimiters which are characters that are used to separate the items For instance the string in the first example in figure ll S uses a comma as the delimiter As a result this string can be referred to as a commadelimited String The first example in this figure also shows how to use the forTokens tag to loop through the four product codes that are stored in the string Here the var attribute specifies a variable name of productCode to identify each product code in the list Then the items attribute uses EL to specify the productCodes at tribute as the string that stores the items Finally the delims attribute specifies the comma as the delimiter To keep this example simple the servlet code creates the productCodes attribute by storing a hard coded list of four product codes that are separated by commas In a more realistic example of course the servlet code would dynarni cally generate this list The second example works similarly to the first example but it uses two delirniters instead of one In particular the delims attribute specifies the at symbol as the first delimiter and the period as the second delimiter As a result the loop processes three items one for each part of the email address If necessary you can nest one forTokens tag within another Or you can nest a forTokens tag within a forEach tag However since you ll rarely need to nest forTokens tags this technique isn t illustrated in this figure Description Figure 115 Chapter 11 How to use the JSP Standard Tag Library JSTL 347 An example that uses JSTL to loop through a commadelimited string Servlet code 1 n JSP code ltpgtProduct codeslt brgt quotMm nFn1 nFn7 101quot 4 lt11gtproductcodelt11gt delimsquot gt ltcforTokensgt ltpgt The result that s displayed in the browser Pmductcnda 1 An example that uses JSTL to parse a string Servlet code 1 n 1Addrn u 1 ramquot JSP code ltpgtEmail partsltbrgt ltczforTokens varquotparquot itemsquotemailAddressquot delims lt1igtsparlt1igt ltcforTokensgt ltpgt The result that s displayed in the browser Emadpms A ismith mall cam You can use the forTokens tag to loop through delimited values that are stored in a string You can use the var attribute to specify the variable name that will be used to access each delimited string You can use the items attribute to specify the string that stores the data You can use the delims attribute to specify the character or characters that are used as the delimiters for the string If necessary you can nest one forTokens tag within another How to use the forTokens tag 348 Section 2 Essential servlet and JSP skills Four more attributes for looping When working with collections the servlet code typically creates a collec tion and passes it to the J SP so the collection can be displayed to the user Then the I SP uses the forEach tag to loop through the collection and display it to the user as shown in gure ll 4 However there may be times when the J SP will need to do some additional processing For example the J SP may need to know whether the item is the first or last item so it can apply special formatting to that item Or the J SP may need to know the item number so it can apply shading to altemating items In that case you can use the attributes described in gure 11 6 These attributes work the same for the forEach and the forTokens tags The example in this gure shows how to work with the begin end and step attributes that are available for the forEach and forTokens tags Here the begin attribute speci es the starting index for the loop the end attribute speci es the last index for the loop and the step attribute speci es the amount to increment the index each time through the loop If you understand how a for loop works in Java you shouldn t have much trouble understanding these attributes In this example these attributes are used to print the first 10 numbers that are stored in an array of 30 int values This example also shows how to use the varStatus attribute This attribute speci es the name of a variable that can be used to get information about the status of the loop In particular this variable provides four properties named first last index and count that you can use within the body of a loop For example you can use the first and last properties to return a Boolean value that indicates whether the item is the rst or last item in the collection Or you can use the index and count properties to return an integer value for the item Note however that the index property returns an integer value that s one less than the count value That s because the index property starts at 0 while the count property starts at l Chapter 11 How to use the JSP Standard Tag library JSTL 349 Attributes that you can use for advanced loops t t l 3 tn li t begin Speci es the rst index for the loop end Speci es the last index for the loop step Specifies the amount to increment the index each time through the loop varStatus r 39 minute L can be u ed quot quot h h loop This variable provides the first last index and oount properties An example that uses all four attributes Servlet code in 1 numbers 1 new intlBO i for in i 30 i numberEli 11 sessionsetAttributequotnumbersquot numbers JSP code ltpgtNumbersltbrgt ltczforEach items be numbersquot var 39nunlberquot end 9 stepquot1 statusquotgt lt11gtsnumber i First ssaus 1rs i Index ssaus1ndex i Count sta ltcforEachgt ltpgt L s statuslast i useount lt11gt The result that s displayed in the browser a First tt se L2H First false Last a Last Description 0 The begin end step and varStatus attributes work for both the forEach and forTokens tags Figure 116 Four more attributes for looping 350 Section 2 Essential servlet and JSP skills How to use the if tag When coding a JSP you may need to perform conditional processing to change the appearance of the page depending on the values of the attributes that are available to the page To do that you can use the if tag as shown in gure 1 17 To start you code an opening if tag that includes the test attribute In the example in this figure this test attribute uses EL to get the count property of the cart attribute which indicates the number of items that are in the cart Then the code within the opening and closing if tags displays a message that s appropri ate for the number of items in the cart In particular the first if tag displays a message if the cart contains 1 item and the second if tag displays a message if the cart contains more than one item The main difference between the two messages is that the second message uses the plural items while the first uses the singular item If necessary you can use the var and scope attributes to expose the Boolean condition in the test attribute as a variable with the speci ed scope Then you can reuse the Boolean condition in other if statements This works similarly to the set tag that s brie y described later in this chapter However since you ll rarely need to use these attributes they aren t illustrated in this gure As with the forEach and forTokens tags you can nest one if tag within another Or you can nest an if tag within a forEach or forTokens tag In short as you might expect by now you can usually nest JSTL tags within one another whenever that s necessary Chapter 11 How to use the JSP Standard Tag Library JSTL 351 An example that uses JSTL to code an if statement JSP code with JSTL ltczif esquotscarcoun 1quotgt ltpgtYou have 1 item in your carltpgt ltcifgt ltczif esquotscarcoun gt 1 quotgt ltpgtYou have 5carcoun items in your carltpgt ltcifgt The result that s displayed in the browser for a cart that has two items Your cart Quaniiry Description i Price Amount and 7 True Life Songs and Picture A Paddlefmt r The rst CD Ya hm e 2 items in mu can Equivalent scripting lt page imporquotbusinesscart javau11ArrayListquot gt lt2 car car Cart if cargecoun outprint1nquotltpgtYou if cargecoun gt outprin1nquotltpgtYou have quot cargecoun talus in your carltpgtquot a sessiongetAttribute quotcartquot 2 have 1 item in your carltpgtquot 1 Description You can use the if tag to peIfoIm conditional processing that s similar to an if statement in Java You can use the test attribute to specify the Boolean condition for the if statement If necessary you can nest one if tag within another Figure 117 How to use the if tag 352 Section 2 Essential servlet and JSP skills How to use the choose tag In the last gure you learned how to code multiple if tags This is the equivalent of coding multiple if statements in Java However there are times when you will need to code the equivalent of an ifelse statement Then you can use the choose tag as described in gure 11 8 To stait you code the opening and closing choose tags Within those tags you can code one or more when tags For instance in the example in this gure the rst when tag uses the test attribute to check if the can contains zero items Then the second tag uses the test attribute to check if the cart contains one item In either case the when tag displays an appropriate message After the when tags but before the closing choose tag you can code a single otherwise tag that s executed if none of the conditions in the when tags evaluate to true In this example the otherwise tag displays an appropriate message if the can doesn t contain zero or one items Since the number of items in a cart can t be negative this means that the otherwise tag uses EL to display an appropriate message whenever the cart contains two or more items Chapter 11 How to use the JSP Standard Tag Library JSTL 353 An example that uses JSTL to code an ifelse statement JSP code with JSTL ltczchoosegt ltczwhen testquotscartcount oquotgt ltpgtYour cart is emptyltpgt ltcwhengt ltczwhen testquotscartcount 1quotgt gtYou have 1 item in your certltpgt ltcwhengt ltczotherwisegt ltpgtYou have 5cartcount items in your cartltpgt egt The result that s displayed in the browser for a cart that has two items Your cart Description i Price Amount band 7 True the Songs and Picture 1 Paddiei eei r The rst CD Ya hm e 2 items in mu can Equivalent scripting lt page importeIbusinesscert jeveuti1ArreyList 2 lt2 Cart cart Cart sessiongetAttributequotcartquot i if certgetcount 0 outprin1nquotltpgtYour car is emptyltpgtquot else if certgetcount outprin1n ltpgtYou have 1 item in your carltpgtquot e1se outprint1n quot pgtYou have quot cartgetcount quot items in your carltpgtquot 96gt Description You can use the choose tag to perform conditional processing similar to an ifelse statement in Java To do that you can code multiple when tags and a single otherwise tag within the choose tag You can use the test attribute to specify the Boolean condition for a when tag If necessary you can nest one choose tag within another Figure 118 How to use the choose tag 354 Section 2 Essential servlet and JSP skills How to use the import tag In chapter 7 you learned two ways to work with includes The import tag shown in gure 11 9 provides another way to work with includes and it works like the standard I SP include tag In other words it includes the file at rzmtime not at compile time Neither the standard I SP include tag or the JSTL import tag uses scripting As a result it usually doesn t matter which tag you use However the JSTL import tag does provide one advantage it lets you include files from other applications and web servers For instance the second last example in this figure shows how to use the import tag to include the footer jsp file that s available from the musicStore application that s running on the same local server as the current web applica tion Then the last example shows how to use the import tag to include the footer jsp file that s available from the remote server for the wwwmurachcom web site Chapter 11 How to use the JSP Standard Tag Library JSTL 355 An example that imports a header file JSP code with JSTL ltczimport urlquotincludesheaderhtmlquot gt Equivalent standard JSP tag ltjspzinclude pagequotincludesheaderhtmlquot gt An example that imports a footer file JSP code with JSTL ltczimport urlquotincludesfooterjspquot gt Equivalent standard JSP tag ltjspzinclude pagequotincludesfooterjspquot gt An example that imports a file from another application ltczimport urlquothttplocalhostB080musicStoreincludesfooterjspquot gt An example that imports a file from another web server ltczimport urlquotwwwmurachcomincludesfooterjspquot gt Description 0 The import tag includes the le at rantime not at compile time much like the standard I SP include tag described in chapter 7 0 One advantage of the import tag over the standard I SP include tag is that it lets you include les from other applications and web servers Figure 119 How to use the import tag 356 Section 2 Essential servlet and JSP skills Other tags in the JSTL core library Figure ll lO shows six more tags in the JSTL core library However if you use the MVC pattem you probably won t need to use these tags As a result I ve only provided brief examples to give you an idea of how these tags work If you do need to use them though you can look them up in the documentation for the JSTL core library as described in gure 11 2 If you need to be able to display special characters in your JSPs you can use the out tag as illustrated by the first example in this figure Then this tag auto matically handles any special characters before they are displayed on the J SP If for example you try to use EL by itself to display a string that contains the left and right angle brackets lt gt the J SP interprets those brackets as an HTML tag and the string isn t displayed correctly However if you use the out tag these characters display correctly on the J SP If you need to set the value of an attribute in a scope you can use the set tag For instance the second example in this figure shows how to set an attribute named message with a value of Test message in session scope You can also use the set tag if you need to set the value of a property of an attribute within a speci ed scope However instead of using the var attribute to specify the name of the attribute you use the target attribute to specify the attribute that contains the property To do that you use EL within the target attribute to specify a reference to the attribute This is illustrated by the third example The fourth example shows how to use the remove tag to remove an attribute from a scope When you use this tag you use the var attribute to specify the name of the attribute that you want to remove and you use the scope attribute to specify the scope that contains the attribute If your J SP includes code that may cause an exception to be thrown you can use the catch tag to catch the exceptions This is illustrated by the fifth example Here the opening and closing catch tags are coded around a Java scriptlet that causes an ArithmeticException to be thrown due to a divide by zero error Then when the exception is thrown execution jumps over the Java expression that displays the result of the calculation However the catch tag also exposes the exception as a variable named e As a result the if tag that follows the catch tag is able to display an appropriate error message Of course if you edit the Java scriptlet that s in the catch tag so it performs a legal calculation no exception will be thrown In that case the result of the calculation will be displayed and the error message won t be displayed The sixth example shows how to use the redirect tag to redirect a client to a new URL In this case the redirect tag is coded within an if tag so the client isn t redirected unless the condition in the if statement is true Although this figure doesn t include an example of the param tag figure 11 3 does illustrate the use of this tag within the url tag If you read through the documentation for the param tag you ll find that you can also use it with other tags such as the import tag Chapter 11 How to use the JSP Standard Tag Library JSTL 357 L core library It Other tags in the JST out Uses EL to display a value automatically handling most special characters such as the left angle bracket lt and right angle bracket gt set Sets the value of an attribute in a scope remove Removes an attribute from a scope catch Catches any exception that occurs in its body and optionally creates an EL variable that refers to the Throwable object for the exception redirect Redirects the client browser to a new URL param Adds a parameter to the parent tag An out tag that displays a message Using the Value attribute ltcout valuequotmessagequot defaultquotNo messagequot gt Using the tag s body ltcout valuequotmessagequotgt No message ltcoutgt A set tag that sets a value in an attribute ltcset varquotmessagequot scopequotsessionquot valuequotTest messagequot gt A set tag that sets a value in a JavaBean JSP code with JSTL ltcset targetquotuserquot propertyquotfirstNamequot valuequotJohnquot gt Equivalent standard JSP tag ltjspzsetProperty namequotuserquot propertyquotfirstNamequot valuequotJohnquotgt A remove tag that removes an attribute ltcremove varquotmessagequot scopequotsessionquot gt A catch tag that catches an exception ltccatch varquotequotgt lt this scriptlet statement will throw an exception int i 1 0 gt ltpgtResultz lt i gtltpgt ltccatchgt ltcif testquote l nullquotgt ltpgtAn exception occurred Message emessageltpgt ltcifgt A redirect tag that redirects to another page ltcif testquote l nullquotgt ltcredirect urlquoterror7javajspquot gt ltcifgt Figure 1110 Other tags in the JSTL core library 358 Section 2 Essential servlet and JSP skills The Cart application Now that you ve learned the details for coding JSTL tags you re ready to see how they re used within the context of an application To show that this chapter nishes by showing a Cart application that maintains a simple shopping cart for a user Since this application uses the MVC pattem the JSPs don t require extensive use of JSTL tags However the url tag is needed to encode URLs and the forEach tag is needed to display the items in the user s cart The user interface Figure 11 11 shows the user interface for the Cart application From the Index page you can click on the Add To Cart link for any of the four CDs to add the CD to your cart Then the Cart page will display all of the items that have been added to your cart On the Cart page you can update the quantity for an item by entering a new quantity in the Quantity column and clicking on the Update button Or you can remove an item from the cart by clicking on its Remove Item button Finally you can return to the Index page by clicking on the Continue Shopping button or you can begin the checkout process by clicking on the Checkout button Chapter 11 How to use the JSP Standard Tag Library JSTL 359 The Index page mm menial Explorer ac Q 51 g mu Mnan Igwj ih fi i V Eea m emquot 9 mm 5 the band 7 True ere gangs and 12mm Paddlefonl r The rst CD Tne Rut r Genume Wand Gramed nish 514 9 Add To Lart El u m mane The Cart page rasaft Internet Explorer 49E 6mquot Er Your cart Quantity Descriptinn 7 e Amnnm 1 Updaqe 86mebaudermeLfeSon andPxHures 31435 51495 Rgmuvehem 1 Update PaddlefnmrThe 39stCD Tn change the quamity enter the new quth and chuk on the upde button Cunhnue snappmg gum grmmm Figure 1111 The user interface for the Cart applicah39on 360 Section 2 Essential servlet and JSP skills The code for the business classes Figure 11 12 shows the three business classes for the Cart application These classes are the Model in the MVC pattern All of these classes follow the rules for creating a JavaBean and implement the Serializable interface as described in chapter 9 Part 1 shows the Product class This class stores information about each product that s available from the web site In particular it provides get and set methods for the code description and price elds for the product In addition this class provides the getPriceCurrencyFormat method which gets a string for the price after the currency format has been applied to the price For example for a double value of 115 this method returns a string of 1150 which is usually the format that you want to display on a J SP Part 2 shows the LineItem class This class stores information about each line item that s stored in the cart To do that this class uses a Product object as one of its instance variables to store the product information for the line item In addition this class always calculates the value of the total field by multiplying the product price by the quantity As a result there s no need to provide a set method for this field Finally this class provides a getTotalCurrencyFormat method that applies currency formatting to the double value that s returned by the getTotal method Part 3 shows the Cart class This class stores each line item that has been added to the cart To do that the Cart class uses an ArrayList to store zero or more LineItem objects When you use the constructor to create a Cart object the constructor initializes the ArrayList object Then you can use the addItem method to add an item or you can use the removeItem method to remove an item In addition you can use the getItems method to return the ArrayList object or you can use the getCount method to get the number of items that are stored in the cart Chapter 11 How to use the JSP Standard Tag Library JSTL 361 The code for the Product class package business import javaioSerializable import javatextNumberFormat public class Product implements Serializable private String code private String description private double price public Product code quotquot description price 0 public void setCodeString code thiscode code public String getCode return code public void setDescriptionString description thisdescription description public String getDescription return description public void setPricedouble price thisprice price public double getPrice return price public String getPriceCurrencyFormat NumberFormatgetCurrencyInstance NumberFormat currency return currencyformatprice Figure 1112 The code for the business classes part 1 of 3 362 Section 2 Essential servlet and JSP skills The code for the Lineltem class package business import javaioSerializable import javatextNumberFormat public class LineItem implements Serializable private Product product private int quantity public LineItem public void setProductProduct p product p public Product getProduct return product public void setQuantityint quantity thisquantity quantity public int getQuantity return quantity public double getTotalO double total productgetPrice quantity return total public String getTotalCurrencyFormatO NumberFormat currency NumberFormatgetCurrencyInstance return currencyformatthisgetTotal Figure 1112 The code for the business classes part 2 of 3 Chapter 11 How to use the JSP Standard Tag Library JSTL 363 The code for the Cart class package business import javaioSerializable import javautilArrayList public class Cart implements Serializable private ArrayListltLineItemgt items public Cart items new ArrayListltLineItemgt public ArrayListltLineItemgt getItems return items public int getCount return itemssize public void addItemLineItem item String code int quantity for int i 0 itemgetProduct getCode i itemgetQuantity i lt itemssize 7 i LineItem lineItem itemsgeti if lineItemgetProduct getCode equals code lineItemsetQuantityquantityi return items add item 7 public void removeItemLineItem item String code itemgetProductgetCode for int i 0 i lt itemssize i LineItem lineItem itemsgeti if lineItemgetProduct getCode equals code itemsremovei return Figure 1112 The code for the business classes part 3 of 3 364 Section 2 Essential servlet and JSP skills The code for the servlets and JSPs Figure ll l3 shows the one servlet and two JSPs for the Can application Here the servlet is the Controller and the two JSPs are the View in the MVC pattern Part 1 shows the J SP code for the Index page that s displayed when the Cart application rst stans This page includes a taglib directive that imports the JSTL core library Then this page displays a table where there is one row for each product Here each product row includes an Add To Cart link that uses the JSTL url tag to encode the URL that s used to add each product to the cart This code works because the CartSeeret shown in part 2 of this gure has been mapped to the cart URL Although these four rows are hard coded for this page the product data could also be read from a database and stored in an ArrayList Then you could use a forEach tag to display each product in the ArrayList The technique for doing this is similar to the technique for displaying each line item in the cart as shown in gure ll 4 Chapter 11 How to use the JSP Standard Tag Library JSTL 365 The code for the indexjsp file ltldoctype html public quot W3CDTD HTML 40 TransitionalENquotgt lthtmlgt ltheadgt lttitlegtMurach39s Java Servlets and JSPlttitlegt ltheadgt ltbodygt lt taglib prefixquotcquot uriquothttpjavasuncomjspjstlcorequot gt lthlgtCD listlthlgt lttable cellpaddingquot quot borderlgt lttr valignquotbottomquotgt ign 39leftquotgtltbgtDescriptionltbgtlttdgt lttd alignquotleftquotgtltbgtPriceltbgtlttdgt lttd alignquotleftquotgtlttdgt lttrgt lttr valignquottopquotgt lttdgt86 the band lttdgtl495lttdgt lttdgtlta hrefquotltcurl value39cartproductCode860139 gtquotgt Add To Cartltagtlttdgt lttrgt True Life Songs and Pictureslttdgt lttr valignquottopquotgt lttdgtPaddlefoot The first CDlttdgt lttdgtl295lttdgt lttdgtlta hrefquotltcurl value39cartproductCodepf0139 gtquotgt Add To Cartltagtlttdgt lttrgt lttr valignquottopquotgt lttdgtPaddlefoot The second CDlttdgt lttdgtl495lttdgt lttdgtlta hrefquotltcurl value39cartproductCodepf0239 gtquotgt Add To Cartltagtlttdgt lttrgt lttr valignquottopquotgt lttdgtJoe Rut Genuine Wood Grained Finishlttdgt lttdgtl495lttdgt lttdgtlta hrefquotltcurl value39cartproductCodejr0139 gtquotgt Add To Cartltagtlttdgt lttrgt lttablegt ltbodygt lthtmlgt Figure 1113 The code for the servlets and JSPs page 1 of 4 366 Section 2 Essential servlet and JSP skills Part 2 shows the servlet code for the CartServlet To start this code gets the value of the productCode parameter from the request object This parameter uniquely identifies the Product object Then this code gets the value of the quantity parameter if there is one However unless the user clicked on the Update button from the Cart page this parameter will be equal to a null value After getting the parameter values from the request this servlet uses the getAttribute method to get the Cart object from a session attribute named cart If this method returns a null value this servlet creates a new Cart object After the Cart object has been retrieved or created this servlet sets the value of the quantity variable To do that it starts by setting the quantity variable to a default value of 1 Then if the quantityString variable contains an invalid integer value such as a null value the parselnt method of the Integer class will throw an exception This also causes the quantity to be set to 1 However if the user enters a valid integer such as 0 or 2 or 2 the quantity will be set to that value Finally if the quantity is a negative number the quantity will be set to 1 After the quantity variable has been set this servlet uses the getProduct method of the Producth class to read the Product object that corresponds with the productCode variable from a text file named productstxt that s stored in the application s WEB INF directory To do that this code specifies the productCode variable as the first argument of the getProduct method Although this application stores data in a text file to keep things simple a more realistic application would probably read this data from a database as described in section 3 of this book After the Product object has been read from the text file this servlet creates a Lineltem object and sets its Product object and quantity Then if the quantity is greater than 0 this code adds the Lineltem object to the Cart object However if the quantity is 0 this code removes the item from the Cart object Finally this servlet sets the Cart object as a session attribute named cart Then it forwards the request and response to the Cart page As you review this code you may notice that the CartServlet only provides an HTTP Get method As a result you can t use the HTTP Post method to call this servlet However this servlet doesn t write any data to the server and a user can request this servlet multiple times in a row without causing any problems As a result you don t need to implement the HTTP Post method for this servlet Chapter 11 How to use the JSP Standard Tag Library JSTL 367 The code for the CartServlet class package cart import javaio import javaxservlet import javaxservlethttp import business import data public class CartServlet extends HttpServlet protected void doGetHttpServletRequest request pServletResponse response throws ServletException IOException requestgetParameterquotproductCodequot requestgetParameterquotquantityquot String productCode String quantityString requestgetSession HttpSession session Cart cart Cart sessiongetAttributequotcartquotI if car null cart new Cart int quantity l r quantity IntegerparseIntquantityStringi if quantity lt quantity l catchNumberFormatException nfe quantity l ServletContext sc getServletContext String path scgetRealPathquotWEB INFproductstxtquoti Product product ProductIOgetProductproductCode path LineItem lineItem new LineItem lineItemsetProductproducti lineItemsetQuantityquantityi if quantity gt m cartaddItemlineItem else if quantity 0 artremoveItemlineItemi sessionsetAttributequotcartquot cart String url quotcartjspquot RequestDispatcher dispatcher etServletContextgetRequestDispatcherurli response 7 dispatcherforwardrequest Figure 1113 The code for the servlets and JSPs page 2 of 4 368 Section 2 Essential servlet and JSP skills Part 3 shows the J SP code for the Cart page Like the Index page this page uses the taglib directive to import the JSTL core library Then it uses a table to display one row for each item in the cart To do that it uses a forEach tag to loop through each LineItem object in the ArrayList that s returned by the items property of the cart attribute and it uses EL to display the data for each line item At first glance the code for this row seems complicated because the rst and last columns contain HTML forms that include text boxes hidden text boxes and buttons For example the first column contains a form that includes a hidden text box that sets the productCode parameter for the form a text box that allows the user to enter a quantity for the form and a button that submits the form to the CartSeeret Similarly the last column contains a hidden text box that sets the productCode parameter for the form another hidden text box that sets the quantity parameter to 0 which causes the item to be removed from the cart and a button that submits the form to the CartSeeret However if you study this code you shouldn t have much trouble understanding how it works Chapter 11 How to use the JSP Standard Tag Library JSTL 369 The code for the cartjsp file ltldoctype html public quot W3CDTD HTML 40 TransitionalENquotgt lthtmlgt ltheadgt Page 1 lttitlegtMurach39s Java Servlets and JSPlttitlegt ltheadgt ltbodygt lthlgtYour cartlthlgt lttable borderquot1quot lttrgt ltthgtQuantityltthgt ltthgtDescriptionltthgt ltthgtPriceltthgt ltthgtAmountltthgt lttrgt cellpaddingquot5quotgt lt taglib prefixquotcquot uriquothttpjavasuncomjspjstlcorequot gt ltczforEach varquotitemquot itemsquotcartitemsquotgt lttr valignquottopquotgt lttdgt ltform actionquot czurl value39cart39 gtquotgt ltinput type hiddenquot namequotproductCodequot valuequotitemproductcodequotgt ltinput typetext size2 namequotquantityquot valuequotitemquantityquotgt ltinput typequotsubmitquot valuequotUpdatequotgt ltformgt lttdgt lttdgtitemproductdescriptionlttdgt lttdgtitemproductpriceCurrencyFormatlttdgt lttdgtitemtotalCurrencyFormatlttdgt lttdgt ltform actionquot czurl value39cart39 gtquotgt ltinput type hiddenquot namequotproductCodequot valuequotitemproductcodequotgt ltinput typequothiddenquot namequotquantityquot value 0quotgt ltinput typequotsubmitquot valuequotRemove Itemquotgt ltformgt lttdgt lttrgt ltcforEachgt lttrgt lttd colspanquot3quotgt ltpgtltbgtTo change the quantityltbgt enter the new quantity and click on the Update buttonltpgt lttdgt lttrgt lttablegt Figure 1113 The code for the servlets and JSPs page 3 of 4 370 Section 2 Essential servlet and JSP skills Part 4 shows the rest of the J SP code for the Cart page This code contains two forms where each form contains a single button The button on the first form displays the Index page and the button on the second form displays the Checkout page which isn t shown or described in this chapter If you review the use of the JSTL and EL code in the Index and Cart pages you ll see that the url tag is used to encode all of the URLs As a result the Cart application will be able to track sessions even if the user has disabled cookies You ll also see that the only other JSTL tag that s used is the forEach tag in the Cart page Finally you ll see that EL is used to display the nested properties that are available from the Product Lineltein and Cart objects This is a typical JSTL and EL usage for applications that use the MVC pattern Chapter 11 How to use the JSP Standard Tag Library JSTL 371 The code for the cartjsp file Page 2 ltbrgt ltform actionquotltcurl value39indexjsp39 gtquot methodquotpostquotgt ltinput typequotsubmitquot valuequotContinue Shoppingquotgt ltformgt ltform actionquotltcurl value39checkoutjsp39 gtquot methodquotpostquotgt ltinput typequotsubmitquot valuequotCheckoutquotgt ltformgt ltbodygt lthtmlgt Note 0 In the webxm1 le the CartSeeret class is mapped to the ca1t URL Figure 1113 The code for the servlets and JSPs page 4 of 4 372 Section 2 Essential servlet and JSP skills Perspective The goal of this chapter has been to show you how to use JSTL with EL to eliminate or reduce scripting from your JSPs However it isn t always possible to remove all scripting from your applications by using JSTL In that case you may occasionally want to use scripting Another option though is to create and use custom tags that are stored in a custom tag library as described in the next chapter Summary The JSP Standard Tag Library JSTL provides tags for common tasks that need to be performed in JSPs Before you can use JSTL tags you must make the jstljar and standardjar files available to the application Before you can use JSTL tags in a JSP you must code a taglib directive for the library that you want to use You can use a web browser to view the documentation for JSTL You can use the url tag to encode URLs so the application can track sessions even if the client browser has cookies disabled You can use the forEach tag to loop through most types of collections including regular arrays You can use the forTokens tag to loop through items in a delimited string You can use the if tag to code the equivalent of a Java if statement You can use the choose tag to code the equivalent of a Java ifelse statement You can use the import tag to include files at runtime This works like the standard I SP include tag but it can be used to include les from other web applications even when they re running on remote web servers Exercise 111 Chapter 11 How to use the JSP Standard Tag Library JSTL 373 Use JSTL in the Download application In this exercise you ll enhance the Download application that you used in exercise 10 2 of the last chapter 1 Open the chl ldownload project in the existarts directory Then run the application to refresh your memory about how it works Use your lDE to add the JSTL library to this project With NetBeans you can do that by right clicking on the Libraries folder for the project and selecting the Add Libraries command from the resulting menu Open the JSPs for this project Then add the taglib directive for the core ISTL library to the beginning of these pages Finally use the url tag to encode all the URLs in this application Test the application to make sure it works correctly Open the indexjsp file Then modify it so it uses the if tag to only display the welcome message if the cookie for the first name doesn t contain a null value Test the application to make sure it works correctly Exercise 112 Use JSTL in the Cart application In this exercise you ll use JSTL to loop through an array list of Product objects 1 2 Open the chl lcart project in the existarts directory Open the webxml le Note that the ProductsServlet class is called when this application starts This means that the browser will issue an HTTP Get request for the ProductsServlet class so its doGet method will be called Open the ProductsServletj ava file Note how this servlet uses the processRequest method to read an ArrayList of Product objects from the proj ectstxt file and store them as an attribute of the session object Note too that this method is called from both the doGet and doPost methods Test the application to make sure it works correctly Add the JSTL library to this project Then open the indexjsp le and add the taglib directive that imports the core JSTL library In the indexjsp le add a forEach tag that loops through the ArrayList of Product objects and displays one row for each product To do that you can use EL to display the properties of each Product object Be sure to delete any old code that you no longer need Test the application to make sure that it works correctly Chapter 1 Introduction 1 Operating System Concepts 8 Edition SilherSCha Z GalVin and Gagne 2009 Mani Wag ilk Chapter 1 Introduction Operating System Concepts 8 Edition What Operating Systems Do ComputerSystem Organization Computer System Architecture OperatingSystem Structure OperatingSystem Operations Process Management Memory Management Storage Management Protection and Security Distributed Systems SpecialPurpose Systems Computing Environments OpenSource Operating Systems g 43 Silberschamz Galvin and Gagne 2009 A Objectives I To provide a grand tour of the major operating systems components I To provide coverage of basic computer system organization Operating System Concepts 8 Edition 13 SilherSCha Z GalVin and Gagne 2009 4w What is an Operating System I A program that acts as an intermediary between a user of a computer and the computer hardware I Operating system goals 0 Execute user programs and make solving user problems easier 0 Make the computer system convenient to use 0 Use the computer hardware in an efficient manner an 4 Operating System Concepts 8 Edition 14 SilherSCha Z GalVin and Gagne 2009 its Mimi Computer System Structure I Computer system can be divided into four components 0 Hardware provides basic computing resources gt CPU memory lO devices 0 Operating system gt Controls and coordinates use of hardware among various applications and users 0 Application programs define the ways in which the system resources are used to solve the computing problems of the users gt Word processors compilers web browsers database systems video games 0 Users gt People machines other computers we 43 Operating System Concepts 8 Edition SilherSCha Z GalVin and Gagne 2009 R Four Components of a Computer System user user user user 1 2 3 39 39 39 n compiler assembier text editor database system system and application programs operating system computer hardware 394 Operating System Concepts 8th Edition 16 SilherSCha Zy 33an and Gagne 2009 Operating System Definition I 08 is a resource allocator o Manages all resources 0 Decides between conflicting requests for efficient and fair resource use I 08 is a control program 0 Controls execution of programs to prevent errors and improper use of the computer 4amp3 Operating System Concepts 8 Edition 17 SilherSCha Z GalVin and Gagne 2009 emf V13 Operating System Definition Cont l I No universally accepted definition I Everything a vendor ships when you order an operating systemquot is good approximation 0 But varies wildly The one program running at all times on the computer is the kernel Everything else is either a system program ships with the operating system or an application program an 4 Silberschatz Galvin and Gagne 2009 Operating System Concepts 8 Edition 4m Computer Startup i I bootstrap program is loaded at powerup or reboot 0 Typically stored in ROM or EPROM generally known as firmware 0 Initializes all aspects of system 0 Loads operating system kernel and starts execution Operating System Concepts 8 Edition 19 SilherSCha Z GalVin and Gagne 2009 its Lg Computer System Organization I Computersystem operation 0 One or more CPUs device controllers connect through common bus providing access to shared memory 0 Concurrent execution of CPUs and devices competing for memory cycles mouse keyboard printer monitor diSkS onine Cl I E3 disk ra hics CPU USB controller 9 p controller adapter memory a 4 Operating System Concepts 8 Edition 110 SilherSCha Z GalVin and Gagne 2009 is m ComputerSystem Operation l l l lO devices and the CPU can execute concurrently l Each device controller is in charge of a particular device type I Each device controller has a local buffer I CPU moves data fromto main memory tofrom local buffers I O is from the device to local buffer of controller I Device controller informs CPU that it has finished its operation by causing an interrupt t 42 v39 Operating System Concepts 8 Edition 111 SilherSCha Z GalVin and Gagne 2009 ilk n fvm h I V1 Common Functions of Interrupts I Interrupt transfers control to the interrupt service routine generally through the interrupt vector which contains the addresses of all the service routines I Interrupt architecture must save the address of the interrupted instruction I Incoming interrupts are disabled while another interrupt is being processed to prevent a lost interrupt I A trap is a softwaregenerated interrupt caused either by an error or a user request I An operating system is interrupt driven K u as as Operating System Concepts 8 Edition 112 SilherSCha Z GalVin and Gagne 2009 39 Interrupt Handling l The operating system preserves the state of the CPU by storing registers and the program counter I Determines which type of interrupt has occurred 0 polling o vectored interrupt system I Separate segments of code determine what action should be taken for each type of interrupt an 4 Operating System Concepts 8 Edition 113 SilherSCha Z GaIVin and Gagne 2009 Interrupt Timeline CPU user process executing IO interrupt processing IO idle device I l transferring lO transfer O transfer request done request done 394 Operating System Concepts 8th Edition 114 SilherSCha Zs 33an and Gagne 2009 IIO Structure I After O starts control returns to user program only upon O completion 0 Wait instruction idles the CPU until the next interrupt 0 Wait loop contention for memory access 0 At most one O request is outstanding at a time no simultaneous O processing I After O starts control returns to user program without waiting for O completion 0 System call request to the operating system to allow user to wait for lO completion 0 Devicestatus table contains entry for each O device indicating its type address and state 0 Operating system indexes into O device table to determine device status and to modify table entry to include interrupt at g gt Operating System Concepts 8 Edition 115 SilherSCha Z GalVin and Gagne 2009 IR n f mh h 3 Direct Memory Access Structure I Used for highspeed lO devices able to transmit information at close to memory speeds l Device controller transfers blocks of data from buffer storage directly to main memory without CPU intervention I Only one interrupt is generated per block rather than the one interrupt per byte k 43 Operating System Concepts 8 Edition 116 SilherSCha Z GalVin and Gagne 2009 ilk V Storage Structure l Main memory only large storage media that the CPU can access directly I Secondary storage extension of main memory that provides large nonvolatile storage capacity I Magnetic disks rigid metal or glass platters covered with magnetic recording material 0 Disk surface is logically divided into tracks which are subdivided into sectors 0 The disk controller determines the logical interaction between the device and the computer 8 43 Operating System Concepts 8 Edition 117 SilherSCha Z GaIVin and Gagne 2009 n Storage Hierarchy I Storage systems organized in hierarchy 0 Speed 0 Cost 0 Volatility I Caching copying information into faster storage system main memory can be viewed as a last cache for secondary storage I Operating System Concepts 8 Edition 44 Silberschatz Galvin and Gagne 2009 StorageDevice Hierarchy i I i l 39 ii v ii I magnetic disk gt optical disk i 7 ii H V magnetic tapes g 03 quotv2 Operating System Concepts 8 Edition 119 SilherSCha Z GalVin and Gagne 2009 Caching Important principle performed at many levels in a computer in hardware operating system software Information in use copied from slower to faster storage temporarily Faster storage cache checked first to determine if information is there 0 If it is information used directly from the cache fast 0 If not data copied to cache and used there I Cache smaller than storage being cached o Cache management important design problem a Cache size and replacement policy at u Operating System Concepts 8 Edition 120 SilherSCha Z GalVin and Gagne 2009 ComputerSystem Architecture l Most systems use a single generalpurpose processor PDAs through mainframes 0 Most systems have specialpurpose processors as well I Multiprocessors systems growing in use and importance 0 Also known as parallel systems tightlycoupled systems 0 Advantages include 1 Increased throughput 2 Economy of scale 3 Increased reliability graceful degradation or fault tolerance 0 Two types 1 Asymmetric Multiprocessing 2 Symmetric Multiprocessing Operating System Concepts 8 Edition 121 SilherSCha Z GaIVin and Gagne 2009 R A ql How a Modern Computer Works g lt instruction execution gt 0 ycle instructions thread of execution g and lt data movement gt data CPU N E o DMA 8 9 2 c S C 3 E memory device M 394 Operating System Concepts 8th Edition SilherSCha Zy 33an and Gagne 2009 Symmetric Multiprocessing Architecture CPU0 CPU1 CPU2 registers registers registers memory rm Operating System Concepts 8th Edition 123 SilherSCha Zy 33an and Gagne 2009 A DualCore Design CPU coreo CPU core1 registers registers rm Operating System Concepts 8th Edition 124 SilherSCha Zy 33an and Gagne 2009 l Clustered Systems I Like multiprocessor systems but multiple systems working together 0 Usually sharing storage via a storagearea network SAN 0 Provides a highavailability service which survives failures gt Asymmetric clustering has one machine in hotstandby mode gt Symmetric clustering has multiple nodes running applications monitoring each other 0 Some clusters are for highperformance computing HPC gt Applications must be written to use parallelization an 4 Operating System Concepts 8 Edition 125 SilherSCha Z GalVin and Gagne 2009 Operating System Structure l Multiprogramming needed for ef ciency Single user cannot keep CPU and HG devices busy at all times Multiprogramming organizes jobs code and data so CPU always has one to execute A subset oftotal jobs in system is kept in memory One job selected and run via job scheduling When it has to wait for lO for example 08 switches to anotherjob l Timesharing multitasking is logical extension in which CPU switchesjobs so frequently that users can interact with each job while it is running creating interactive computing 0 Response time should be lt 1 second Each user has at least one program executing in memory Egtprocess If several jobs ready to run at the same time gt CPU scheduling If processes don t t in memory swapping moves them in and out to run Virtual memory allows execution of processes not completely in memo s u Operating System Concepts 8 Edition 126 SilherSCha Z GalVin and Gagne 2009 w Memory Layout for Multiprogrammed System 512M Operating System Concepts 8th Edition operating system job 1 job 2 job 3 job 4 i0 Silberschatz Galvin and Gagne 2009 ilk stag operatingSystem Operations I Interrupt driven by hardware I Software error or request creates exception or trap 0 Division by zero request for operating system service I Other process problems include infinite loop processes modifying each other or the operating system I Dualmode operation allows OS to protect itself and other system components 0 User mode and kernel mode 0 Mode bit provided by hardware gt Provides ability to distinguish when system is running user code or kernel code gt Some instructions designated as privileged only executable in kernel mode gt System call changes mode to kernel return from call resets it to user we 43 Operating System Concepts 8 Edition 128 SilherSCha Z GalVin and Gagne 2009 A j t Transition from User to Kernel Mode I Timer to prevent infinite loop process hogging resources 0 Set interrupt after specific period 0 Operating system decrements counter 0 When counter zero generate an interrupt 0 Set up before scheduling process to regain control or terminate program that exceeds allotted time user process user mode user process executing H calls system call I i return from system call mode b 1 l 1 k I trap return eme mode bit 0 mode bit 1 kernel mcde execute system call mOde b O Operating System Concepts 8 Edition s in Silberschatz Galvin and Gagne 2009 Process Management A process is a program in execution It is a unit of work within the system Program is a passive entity process is an active entity Process needs resources to accomplish its task 0 CPU memory lO files 0 Initialization data Process termination requires reclaim of any reusable resources Singlethreaded process has one program counter specifying location of next instruction to execute 0 Process executes instructions sequentially one at a time until completion Multithreaded process has one program counter per thread Typically system has many processes some user some operating system running concurrently on one or more CPUs o Concurrency by multiplexing the CPUs among the processes threads Operating System Concepts 8 Edition 130 SilherSCha Z GalVin and Gagne 2009 ilk gammy if Process Management ActIVItIes The operating system is responsible for the following activities in connection with process management Creating and deleting both user and system processes Suspending and resuming processes Providing mechanisms for process synchronization Providing mechanisms for process communication Providing mechanisms for deadlock handling t 42 v39 Operating System Concepts 8 Edition 131 SilherSCha Z GalVin and Gagne 2009 he Memory Management I All data in memory before and after processing I All instructions in memory in order to execute l Memory management determines what is in memory when 0 Optimizing CPU utilization and computer response to users I Memory management activities Keeping track of which parts of memory are currently being used and by whom Deciding which processes or parts thereof and data to move into and out of memory Allocating and deallocating memory space as needed we 43 Operating System Concepts 8 Edition 132 SilherSCha Z GalVin and Gagne 2009 Storage Management I 08 provides uniform logical view of information storage 0 Abstracts physical properties to logical storage unit file 0 Each medium is controlled by device ie disk drive tape drive gt Varying properties include access speed capacity data transfer rate access method sequential or random I FileSystem management 0 Files usually organized into directories 0 Access control on most systems to determine who can access what 0 08 activities include gt Creating and deleting files and directories gt Primitives to manipulate files and dirs gt Mapping files onto secondary storage gt Backup files onto stable nonvolatile storage media at g Operating System Concepts 8 Edition SilherSCha Z GalVin and Gagne 2009 ilk barf MassStorage Management I Usually disks used to store data that does not fit in main memory or data that must be kept for a long period of time I Proper management is of central importance I Entire speed of computer operation hinges on disk subsystem and its algorithms I 08 activities a Freespace management 0 Storage allocation 0 Disk scheduling I Some storage need not be fast 0 Tertiary storage includes optical storage magnetic tape 0 Still must be managed o Varies between WORM writeonce read many times and RW readwrite we 43 Operating System Concepts 8 Edition 134 SilherSCha Z GalVin and Gagne 2009 Wei 39 Performance of Various Levels of Storage I Movement between levels of storage hierarchy can be explicit or im p icit Level 1 2 3 4 Name registers cache main memory disk storage Typical size lt1 KB gt16 MB gt 16 GB gt 100 GB Implementation custom memory with onchip or offchip CMOS DRAM magnetic disk technology multiple ports CMOS CMOS SRAM Access time ns 025 05 05 25 80 250 5000000 Bandwidth MBsec 20000 100000 5000 10000 1000 5000 20 150 Managed by compiler hardware operating system operating system Backed by cache main memory disk CD or tape it i Operating System Concepts 8 quot Edition 135 Silberschatz Galvin and Gagne 2009 PF x quotquot g H 7 Migration of Integer A from Disk to Register l Multitasking environments must be careful to use most recent value no matter where it is stored in the storage hierarchy magnetic main hardware disk 1 memory 1 cache E register I Multiprocessor environment must provide cache coherency in hardware such that all CPUs have the most recent value in their cache I Distributed environment situation even more complex 0 Several copies of a datum can exist 0 Various solutions covered in Chapter 17 3914 eLi Operating System Concepts 8th Edition 136 SilherSCha Zy 33an and Gagne 2009 ilk snare IO Subsystem I One purpose of OS is to hide peculiarities of hardware devices from the user I O subsystem responsible for 0 Memory management of HO including buffering storing data temporarily while it is being transferred caching storing parts of data in faster storage for performance spooling the overlapping of output of one job with input of otherjobs 0 General devicedriver interface 0 Drivers for specific hardware devices we 43 Operating System Concepts 8 Edition 137 SilherSCha Z GalVin and Gagne 2009 Protection and Security I Protection any mechanism for controlling access of processes or users to resources defined by the OS Security defense of the system against internal and external attacks 0 Huge range including denialofservice worms viruses identity theft theft of service Systems generally first distinguish among users to determine who can do what 0 User identities user IDs security IDs include name and associated number one per user 0 User ID then associated with all files processes of that user to determine access control 0 Group identifier group ID allows set of users to be defined and controls managed then also associated with each process file 0 Privilege escalation allows user to change to effective ID with more rights at g gt Operating System Concepts 8 Edition 138 SilherSCha Z GaIVin and Gagne 2009 as anti 39 39 lava Computing EnVIronmentS I Traditional computer 0 Blurring overtime 0 Office environment gt PCs connected to a network terminals attached to mainframe or minicomputers providing batch and timesharing gt Now portals allowing networked and remote systems access to same resources 0 Home networks gt Used to be single system then modems gt Now firewalled networked is Operating System Concepts 8 Edition 139 SilherSCha Z GalVin and Gagne 2009 Computing Environments Cont I ClientSewer Computing 0 Dumb terminals supplanted by smart PCs 0 Many systems now servers responding to requests generated by clients gt Computeserver provides an interface to client to request senices ie database gt Fileserver provides interface for clients to store and retrieve files I client I I client I I client I I I I network server 3911 at Operating System Concepts 8th Edition 140 SilherSCha Zy 33an and Gagne 2009 5k a PeertoPeer Computing I Another model of distributed system I P2P does not distinguish clients and servers 0 Instead all nodes are considered peers 0 May each act as client server or both 0 Node mustjoin P2P network gt Registers its service with central lookup service on network or gt Broadcast request for service and respond to requests for service via discovery protocol 0 Examples include Napster and Gnutela 4s 4 Operating System Concepts 8 Edition 141 SilherSCha Z GalVin and Gagne 2009 WebBased Computing I Web has become ubiquitous I PCs most prevalent devices I More devices becoming networked to allow web access I New category of devices to manage web traffic among similar servers load balancers I Use of operating systems like Windows 95 clientside have evolved into Linux and V ndows XP which can be clients and servers t 42 v39 Operating System Concepts 8 Edition 142 SilherSCha Z GalVin and Gagne 2009 OpenSource Operating Systems I Operating systems made available in sourcecode format rather than just binary closedsource Counter to the copy protection and Digital Rights Management DRM movement Started by Free Software Foundation FSF which has copyleft GNU Public License GPL I Examples include GNULinux BSD UNIX including core of Mac OS X and Sun Solaris Operating System Concepts 8 Edition 143 SilherSCha Z GalVin and Gagne 2009 End of Chapter 1 Operating System Concepts 8 Edit39un Silberschamz Galvin and Gagne 2009