i Web Development Toolkit for Java Developers Build dynamic, secure, and scalable web applications with Java Dr. Nirali Dabhi Dr. Dharmendra Patel Dr. Atul Patel www.bpbonline.com
ii Copyright © 2023 BPB Online All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor BPB Online or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book. BPB Online has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, BPB Online cannot guarantee the accuracy of this information. First published: 2023 Published by BPB Online WeWork 119 Marylebone Road London NW1 5PU UK | UAE | INDIA | SINGAPORE ISBN 978-93-55510-341 www.bpbonline.com
iii Dedicated to My beloved Parents: Late Nikhilkumar Johnbhai Honest Nilaxi Nikhilkumar Honest & My Husband Bhavinkumar Williambhai Dabhi and all my family members
iv About the Authors l Dr. Nirali Dabhi has worked as Senior Java Developer, Dakshya Freondtech, from March 2022 to June 2022. From January 2021 to February 2022, she was working as Associate Professor at Smt. Chandaben Mohanbhai Patel Institute of Computer Applications (CMPICA), CHARUSAT, Changa. January 2010 to December 2020, she has also worked as Assistant Professor at Smt. Chandaben Mohanbhai Patel Institute of Computer Applications (CMPICA), CHARUSAT, Changa. August 2005 to December 2009, she worked as a Lecturer at Smt. Chandaben Mohanbhai Patel Institute of Computer Applications (CMPICA) formerly known as Charotar Institute of Computer Application (CICA), CHARUSAT, Changa. l Dr. Dharmendra Patel is currently working as Professor in Smt. Chandaben Mohanbhai Patel Institute of Computer Applications, Charusat, Changa. He possesses 19 years of progressive experience in Academics, Research and implementing academic policies. His area of research is Web Mining. He has published 49 research papers in various domains of computer science in reputed journals. He also acted reviewers and editors in various journals of repute. He has published 6 book chapters and 16 technical articles in reputed books and magazine respectively. He has received five research paper awards as contribution in research. He also acted resource person of various committees of conferences, STTPs, Workshops etc. He has organized more than 10 events as a coordinator. He also has professional body membership of various reputed organizations. l Dr. Atul Patel is currently working as in charge Registrar of Charotar University of Science and Technology, Changa. He is Dean and Principal of Smt. Chandaben Mohanbhai Patel institute of Computer Applications since inception the university. Under his leadership, institution has achieved various milestones. The institution has received 5 stars ranking in GSIRF two consecutive years. He possesses 28 years of progressive experience in Industry, Academics, Research and implementing academic policies. He is also servicing as a controller of examination in Charotar University of Science and Technology. He also served as an E-Governance Coordinator, CHARUSAT for integration and smooth functioning of different digital services of entire University. He
v provided several ICT services like Website and Web Application Development, Mobile Application Development to the various departments and institutions of entire University as and when required. His area of research is Wireless Communications. He has published more than 100 research papers in various domains of computer science. 6 students completed Ph.D. under his guide ship and 8 students are working under him. He is also an active member of NAAC committee. He possesses various roles in NAAC committee including chairman of NAAC peer team. He is awarded with various owners/ awards from reputed institutions and organizations. He is awarded with Rashtriya Vidya Gaurav Gold Medal Award, IIEM (ISC), New Delhi in 2020. He received Bharat Vidya Shiromani Award, Indian Solidarity Council, New Delhi in 2020. He is also senior member of ACM, USA and life member of CSI India. He has delivered more than 30 expert talks in various workshops, conferences, and seminars of repute. He is associated with several other universities/ Institutions as a member of Doctoral Advisory Committee, Boards of Studies, and Faculty Board. He is serving as an expert in Ph.D. evaluation and viva for many Universities. He is also serving as an expert in faculty recruitment for many institutions.
vi About the Reviewer Dr. Pranav Vyas is a highly skilled and experienced Product Specialist at Caliber Technologies Pvt Ltd, a leading company that specializes in developing cutting- edge products for the pharmaceutical and chemical sector. His expertise is widely recognized by leading Indian and multinational companies in this domain. Prior to joining Caliber Technologies Pvt Ltd, Dr. Vyas held an academic position for over a decade at a renowned university in Gujarat. As an academician, he authored numerous research papers which were published in top-tier journals and presented at both national and international conferences. Additionally, he has made notable contributions to several books in the form of book chapters, focusing on topics of his interest. Dr. Vyas' diverse areas of expertise include IoT, Network Security, Software Engineering, Product Management and Blockchain. He is a frequent guest speaker and lecturer in leading universities and educational institutions, where he passionately shares his knowledge on these subjects.
vii Acknowledgement There are a few people I want to thank for the continued and ongoing support they have given me during the writing of this book. First and foremost, I would like to thank my parents for continuously encouraging me for writing the book, my husband and my family motivated me to complete the work with all the support they can give me, I could have never complete this book without their support. I am grateful to Dr. Atul Patel for providing me all the resources needed to complete the book, I would thank Dr. Dharmendra Patel for writing and guiding throughout the chapters, I gratefully acknowledge Mr. Rakesh Dobariya, Dr. Pranav Vyas for accepting and performing technical review for this book. My gratitude also goes to the team at BPB Publications for being supportive enough to provide me quite a long time to finish the book and providing guidance and valuable inputs throughout the publication process.
viii Preface Web development is one of the most demanding skills required in the field of computer application. Java supports the development of web application using simple model view controller as well as with support of advance frameworks based on java language. This book takes a practical approach for web application development using java, it covers the tokens of concepts required to develop a web application. It covers the practical aspects of programming using simple examples. This book is divided into 14 chapters. Database connectivity from java, JSP and servlets, JSF, web services, Spring boot and aspect-oriented concepts. Chapter 1: Database Connectivity From Java- The chapter covers the use of JDBC API, explain the major components of JDBC API, list and explain the types of driver available to communicate with the database. Chapter 2: Performing Insert, Update, Delete and Select Operations- The chapter covers the steps used to access a database from a java application. JDBC API components with its methods are described briefly to understand the purpose and syntax before using them to build a program. The basic database operations like insert records, update records, selecting records, traversing on the ResultSet, deleting records, etc. are covered with suitable examples. Chapter 3: Creating Properties File and Performing Batch Operations- The chapter covers the steps to create a properties file and access it in a java code. The use of properties file can be for different purposes here we use it to hold the database specific key and value pairs. The other part of chapter covers the concept of batch processing with the transactions and shows the concept of how to manually rollback and commit using the SavePoint. It also shows that instead of executing a program for one query, one can add the queries to batch and execute the batch single time, so it save time and effort, for example if you want to enter five records then have five insert queries added to a single batch and execute this batch once. Chapter 4: Web Components and Web Application Directory Structure- This chapter covers the fundamentals knowledge required to understand client server communication, it includes the understanding of web client, server and protocols
ix used in the communication. The chapter covers a brief overview of TCP/IP and HTTP protocols with their role in web client server communication. The role of container is explained in brief and the details of how a web directory structure is organized is explained with the goal of making a web archive file. In the end of the chapter MVC design pattern is briefly described. Chapter 5: Servlet Programming- This chapter covers servlet introduction, role and taks of servlet, working of servlet, servlet life cycle, generate plain text and html responses. Understand the generation of implicit and explicit data by understanding request and response headers, and its methods Chapter 6: Managing Advance Features in Servlet- This chapter covers advance features that can be managed using servlets, the major features include managing cookies and sessions. Chapter 7: Basics of Java Server Pages (JSP)- In this chapter we cover the basic syntax of JSP. JSP is used to write java in html, but how we write, where we write, and how much we write matters a lot. So understanding the basic scripting elements like scriptlets, expressions and declarations are very important. Then we understand the usage of directives like page, include and taglib directive. Apart from these we covered the include action, param element, forward action, and the XML syntax of using all the JSP tokens. Chapter 8: Handling Beans and Using Expression Language- In this chapter we cover the concept of bean class, how to create and use it in a simple java application as well as in a web application, then we cover the usage of jsp:useBean, jsp:getProperty and jsp:getSetproperty. We cover the sharing of beans in different locations like request, session and application. In the second half part of chapter we cover the usage of expression language which is a short and easy way to invoke java code without writing core java syntax in html. Chapter 9: Understand Model, View and Controller Pattern- In this chapter we cover the concept of model, view and controller in the development of the application. The MVC pattern suggest the separation of code based on the different role and purpose, so the error solving and managing of code become easier as the application size and complexity increases. Servlet is good at processing, JSP is good at presentation, and bean class and database can be used to represent the entity class. Technologies can be optimized in using it for right purpose, so Servlet is used as a Controller, JSP is used as a View layer and, Java Beans are used as Model layer.
x Chapter 10: Overview of JSP Standard Tag Library (JSTL)- In this chapter we cover the concept of using an external library that support various functions required during programming. The use of this functions shows how easy it is with lesser programing we can continue to work without compromising functionalities. Chapter 11: Outline of JSF for Building Component-Based, Event-Oriented Web Interfaces- In this chapter we cover the concept of using JSF, we compare its benefit over JSP, and explore the syntax and application of it. Chapter 12: Working with Web Services (SOAP and RESTful)- In this chapter we cover the concept of web services both SOAP based and RESTful services. Chapter 13: Aspect-Oriented Approach with Spring Framework- In this chapter we cover the aspect-oriented approach and explore the Spring Framework. Chapter 14: Introduction to Spring Boot- In this chapter we cover the syntax and application of Spring Boot.
xi Code Bundle and Coloured Images Please follow the link to download the Code Bundle and the Coloured Images of the book: https://rebrand.ly/v5hub5c The code bundle for the book is also hosted on GitHub at https://github.com/bpbpublications/Web-Development-Toolkit-for-Java- Developers. In case there's an update to the code, it will be updated on the existing GitHub repository. We have code bundles from our rich catalogue of books and videos available at https://github.com/bpbpublications. Check them out! Errata We take immense pride in our work at BPB Publications and follow best practices to ensure the accuracy of our content to provide with an indulging reading experience to our subscribers. Our readers are our mirrors, and we use their inputs to reflect and improve upon human errors, if any, that may have occurred during the publishing processes involved. To let us maintain the quality and help us reach out to any readers who might be having difficulties due to any unforeseen errors, please write to us at : errata@bpbonline.com Your support, suggestions and feedbacks are highly appreciated by the BPB Publications’ Family. Did you know that BPB offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.bpbonline.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at : business@bpbonline.com for more details. At www.bpbonline.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on BPB books and eBooks.
xii Piracy If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at business@bpbonline.com with a link to the material. If you are interested in becoming an author If there is a topic that you have expertise in, and you are interested in either writing or contributing to a book, please visit www.bpbonline.com. We have worked with thousands of developers and tech professionals, just like you, to help them share their insights with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea. Reviews Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions. We at BPB can understand what you think about our products, and our authors can see your feedback on their book. Thank you! For more information about BPB, please visit www.bpbonline.com. Join our book's Discord space Join the book's Discord Workspace for Latest updates, Offers, Tech happenings around the world, New Release and Sessions with the Authors: https://discord.bpbonline.com
xiii Table of Contents 1. Database Connectivity From Java ............................................................................ 1 Introduction ............................................................................................................ 1 Structure .................................................................................................................. 1 Objectives ................................................................................................................ 2 Introduction to JDBC ............................................................................................. 2 Core components of JDBC API ............................................................................ 3 JDBC drivers ........................................................................................................... 4 Types of JDBC drivers ........................................................................................... 4 Type 1: JDBC-ODBC Bridge ............................................................................. 4 Type 2: Native-API driver ................................................................................. 5 Type 3: Network-Protocol .................................................................................. 6 Type 4: DatabaseProtocol driver ........................................................................ 7 Type 5 JDBC Drivers ......................................................................................... 8 Conclusion .............................................................................................................. 9 Points to remember ............................................................................................... 9 Multiple choice questions ..................................................................................... 9 Answers ............................................................................................................. 9 Questions .............................................................................................................. 10 Key terms .............................................................................................................. 10 2. Performing Insert, Update, Delete and Select Operations ............................... 11 Introduction .......................................................................................................... 11 Structure ................................................................................................................ 11 Objectives .............................................................................................................. 12 Steps to access the database from Java application ........................................ 12 Import the packages ......................................................................................... 12 Register the JDBC driver ................................................................................. 12 Open a connection ........................................................................................... 14 Creating a Statement ....................................................................................... 15
xiv Creating a Statement object .................................................................................. 15 Creating the PreparedStatement objects ............................................................... 15 Creating the CallableStatement objects ................................................................. 16 Executing a query ............................................................................................ 17 Extracting data from result set ........................................................................ 18 Clean up the environment ............................................................................... 21 MetaData ............................................................................................................... 21 ResultSetMetaData ......................................................................................... 21 DatabaseMetaData .......................................................................................... 22 Creating application to access the database using IDE .................................. 22 Creating a table in Oracle from Java ............................................................... 23 Alter table in Oracle from Java ........................................................................ 32 Insert records in table from Java ...................................................................... 32 Update records in table from Java .................................................................... 34 Delete records in table from Java ..................................................................... 36 Conclusion ............................................................................................................ 38 Points to remember ............................................................................................. 38 Multiple choice questions ................................................................................... 38 Answers ........................................................................................................... 40 Questions .............................................................................................................. 40 Key terms .............................................................................................................. 41 3. Creating Properties File and Performing Batch Operations ............................. 43 Introduction .......................................................................................................... 43 Structure ................................................................................................................ 43 Objectives .............................................................................................................. 44 Introduction to properties file ............................................................................ 44 Constructors and methods of properties class ................................................ 44 Properties file example ........................................................................................ 45 JDBC transactions ................................................................................................ 50 Commit and rollback ........................................................................................ 51 Savepoints ........................................................................................................ 51
xv Batch processing in JDBC ............................................................................... 51 Advantages of batch processing ....................................................................... 52 Application of methods .................................................................................... 52 Conclusion ............................................................................................................ 56 Multiple choice questions ................................................................................... 56 Answers ........................................................................................................... 57 Questions .............................................................................................................. 57 Key terms .............................................................................................................. 57 4. Web Components and Web Application Directory Structure ............................ 59 Introduction .......................................................................................................... 59 Structure ................................................................................................................ 59 Objectives .............................................................................................................. 60 Understanding web applications ...................................................................... 60 Web server and client .......................................................................................... 60 TCP/IP - Transmission Control Protocol (TCP) and Internet Protocol (IP) .......61 HTML and HTTP ................................................................................................. 62 Understanding the HTTP ................................................................................... 62 Examples of HTTP parameters ........................................................................ 63 HTTP headers .................................................................................................. 65 Message start-line ................................................................................................ 65 Header fields ........................................................................................................ 65 Message body ....................................................................................................... 66 HTTP - requests .................................................................................................... 66 Understanding URL ............................................................................................ 70 Need servlet and JSPs ......................................................................................... 71 Role of container in handling the request ........................................................ 73 Web application directory structure.................................................................. 75 WAR file ................................................................................................................ 77 Deployment descriptor ....................................................................................... 77 Model View Controller (MVC) Overview ........................................................ 77 Conclusion ............................................................................................................ 78
xvi Points to remember ............................................................................................. 78 Multiple choice questions ................................................................................... 78 Answers ........................................................................................................... 79 Questions .............................................................................................................. 80 Key terms .............................................................................................................. 80 5. Servlet Programming ................................................................................................ 81 Introduction .......................................................................................................... 81 Structure ................................................................................................................ 81 Objectives .............................................................................................................. 82 Basics of the servlet ............................................................................................. 82 Role of servlets ................................................................................................. 82 Common Gateway Interface (CGI) .................................................................. 83 Servlet Life cycle .................................................................................................. 84 The init() method ............................................................................................. 84 The service() method ........................................................................................ 85 The doGet() method ......................................................................................... 85 The doPost() method ........................................................................................ 85 The destroy() method ....................................................................................... 85 Servlet life cycle scenario ................................................................................. 86 Servlet programming .......................................................................................... 86 Servlet to generate plaintext .................................................................................. 88 Servlet to generate HTML..................................................................................... 88 Handling the client-side form data ................................................................... 89 Methods to read the data .................................................................................... 89 Reading single values: getParameter ............................................................... 89 Reading multiple values: getParameterValues ................................................ 90 Accessing parameter names: getParameterNames and getParameterMap ..... 90 Accessing the form fata : getReader or getInputStream .................................. 90 Reading input in multiple character sets: setCharacterEncoding ................... 91 Reading form data ............................................................................................ 91 Handling the request headers ............................................................................ 93
xvii Methods to read the request headers ................................................................ 93 HTTP request headers ..................................................................................... 94 Generate the server response ............................................................................. 96 Setting random status codes: setStatus ........................................................... 97 Setting 302 and 404 status codes: sendRedirect and sendError...................... 97 HTTP 1.1 status codes ..................................................................................... 97 Handling the response headers ......................................................................... 99 Setting response headers from servlets .......................................................... 100 HTTP response headers ................................................................................. 100 Expires ................................................................................................................. 102 Last-modified ....................................................................................................... 103 Location ............................................................................................................... 103 Pragma ................................................................................................................ 103 Refresh ................................................................................................................. 103 Retry-after ........................................................................................................... 104 Set-Cookie ............................................................................................................ 104 WWW-Authenticate ........................................................................................... 104 Conclusion .......................................................................................................... 104 Points to remember ........................................................................................... 104 Multiple choice questions ................................................................................. 105 Answers ......................................................................................................... 105 Questions ............................................................................................................ 106 Key terms ............................................................................................................ 106 6. Managing Advance Features in Servlet .............................................................. 107 Introduction ........................................................................................................ 107 Structure .............................................................................................................. 107 Objectives ............................................................................................................ 107 Managing cookies .............................................................................................. 108 Sending and receiving cookies ....................................................................... 108 Sending cookies to the client................................................................................ 109 Setting the maximum age .................................................................................... 109
xviii Placing the Cookie in the Response Headers ....................................................... 109 Reading cookies from the client ........................................................................... 110 Cookie attributes ............................................................................................ 110 Session and cookies .........................................................................................111 Cookie utilities ..................................................................................................... 113 Utilities.java ........................................................................................................ 113 LongLivedCookie.java .......................................................................................... 114 Cookie utilities ..................................................................................................... 114 RepeatVisitor.java ................................................................................................ 115 Using cookies to handle user accounts and preferences ................................. 115 AccessCounts.java ............................................................................................... 116 RegistrationForm.java ......................................................................................... 117 RegistrationServlet.java ...................................................................................... 118 Managing session .............................................................................................. 118 Overview of session tracking ......................................................................... 119 Cookies ................................................................................................................. 119 URL rewriting ............................................................................................... 120 Hidden form fields ............................................................................................... 120 Session tracking in servlets ........................................................................... 121 Accessing the session object associated with the current request .................. 121 Looking up information associated with a session .............................................. 122 Associating information with a session ......................................................... 122 Discarding session data ................................................................................. 123 API for session tracking ................................................................................. 124 Types of sessions ............................................................................................ 126 URL encoding ................................................................................................ 127 Conclusion .......................................................................................................... 128 Points to remember ........................................................................................... 128 Multiple choice questions ................................................................................. 128 Answers ......................................................................................................... 129 Questions ............................................................................................................ 129 Key terms ............................................................................................................ 129
xix 7. Basics of Java Server Pages (JSP) .......................................................................... 131 Introduction ........................................................................................................ 131 Structure .............................................................................................................. 131 Objectives ............................................................................................................ 132 Java Server Pages ............................................................................................... 132 JSP life cycle ........................................................................................................ 132 The JSP page interface ................................................................................... 134 The HttpJspPage interface ............................................................................. 134 Overview of JSP ................................................................................................. 134 Basic tokens of JSP ......................................................................................... 135 Writing first JSP program ............................................................................. 136 Basic scripting elements .................................................................................... 136 JSP expressions .............................................................................................. 137 JSP scriptlets .................................................................................................. 141 JSP declarations ............................................................................................. 142 Comparing JSP expressions, Scriptlets, and declarations ............................. 144 JSP directives ...................................................................................................... 146 Page directive ................................................................................................. 146 The import attributes .......................................................................................... 147 The contentType and pageEncoding attributes ................................................... 148 The session attributes .......................................................................................... 158 The isELIgnored attribute ................................................................................... 159 The buffer and autoFlush attributes .................................................................... 159 The info attributes ............................................................................................... 159 The errorPage and isErrorPage attributes ..................................................... 159 The extends attribute ........................................................................................... 167 The language attributes ....................................................................................... 167 Include files .................................................................................................... 167 The jsp:include action .......................................................................................... 167 The page attributes .............................................................................................. 168 The flush attribute ............................................................................................... 168 XML syntax and jsp:include ............................................................................... 169
xx The include directive ........................................................................................... 175 The file attributes ................................................................................................. 176 XML syntax for the include directive ................................................................. 176 Forwarding requests with jsp:forward ........................................................... 183 taglib directive .................................................................................................... 186 Conclusion .......................................................................................................... 186 Points to remember ........................................................................................... 186 Multiple choice questions ................................................................................. 187 Answers ......................................................................................................... 188 Questions ............................................................................................................ 188 Key terms ............................................................................................................ 188 8. Handling Beans and Using Expression Language ............................................ 189 Introduction ........................................................................................................ 189 Structure .............................................................................................................. 189 Objectives ............................................................................................................ 190 Introduction to JavaBean .................................................................................. 190 Advantages of using Java bean ...................................................................... 192 Using Java beans in a web application .......................................................... 193 JSP syntax for creating and accessing beans ................................................. 197 Creating beans ............................................................................................... 197 Retrieving values from beans ......................................................................... 198 Assigning values to beans ............................................................................. 199 Assigning properties of bean with input parameter values ........................... 205 Assigning all properties of bean with input parameter values ...................... 212 Sharing Beans in different scopes .................................................................... 212 Unshared bean in Page scope ......................................................................... 219 Sharing bean in Request scope ....................................................................... 222 Sharing bean in Session scope ....................................................................... 225 Sharing bean in application scope ................................................................... 230 Introduction to expression language .............................................................. 232 Retrieving scoped variables ............................................................................. 233
Comments 0
Loading comments...
Reply to Comment
Edit Comment