[Go to site: main page, start]

0% found this document useful (0 votes)
7 views82 pages

Advanced Java Notes

The document provides an overview of Java Database Connectivity (JDBC) and Java Servlets, detailing how JDBC allows Java applications to interact with databases through a standard API and various driver types. It also covers the servlet lifecycle, HTTP request handling, session tracking techniques, and the differences between servlet filters and listeners. Key concepts include CRUD operations, exception handling, and the architecture of web applications using Java technologies.

Uploaded by

neloyhstu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
7 views82 pages

Advanced Java Notes

The document provides an overview of Java Database Connectivity (JDBC) and Java Servlets, detailing how JDBC allows Java applications to interact with databases through a standard API and various driver types. It also covers the servlet lifecycle, HTTP request handling, session tracking techniques, and the differences between servlet filters and listeners. Key concepts include CRUD operations, exception handling, and the architecture of web applications using Java technologies.

Uploaded by

neloyhstu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
— THE COMPLETE — JEANIE @ curious_.programmer a Inhentance & public class MyClass { ny = public static void main(StringLI Gael — Pt args) ¢ S a [Link]("Hello,Java!"); | SubClass1 SubClass2 Et : peers) Interface Exception Handling role ss ae 7 aE [hreoat} [Thread] ’ a | Database |—< ~/ } JDBC ~tisaly> | Database SELECT INSERT | + getName() | UPDATE DELETE GET, Ae ~ name. String = age int OBIJET: me’ SELECT INSERT UPDATE DELETE Chapter 1: Java Database Connectivity (JDBC) @ curious— programmer Introduction to JDBC 4 JDBC or Java Database Connectivity, is a Java API that enables Java applications +o interact with databases. It provides a standard set of interfaces that allow Java programs to execute SQL queries, update records, retrieve results, and interact with various relational database management systems in a database-independent manner JDBC Architecture The JDBC architecture consists of several key components that work together to enable database connectivity for Java applications. DriverManager r JDBC Architecture — Java JDBC-ODBC | Bridge Driver ~ Gee, |Da va JDBC Drivers (Type 1-4) @ curious_programmer vIDEC Drivers (Type 1-4) JDBC drivers are used to connect Java applications to databases. There are four types of JDBC drivers, each with its own architecture. 3c sridge Driver — = Comverts JDBC cals ilo ODBC cae BELeaE) HEBES A a - Converts JDBC calls into native database APT calls. eres SDBC calls into a = S- ea independent nelwork protocol : | Thin Driver (Pure Java Driver) Ke > = Directly converts JDBC calls to et ES jependent specific protocol using pure Jova, fastest x platform-ind SDBC API & Packages JDBC API provides a set of classes minterfaces allowing Java, applications to connect and interact with databases. + Manages a list of database drivers Extensions for - Defines SQL classes for enterprise-level | | aot connecting and oe eee interacting with | | and connection databases. | pooling. : @ curious_programmer Steps to Connect Java Application with Database: DriverManager and DataSource @ curious_programmer "| | DataSource ds= | Be aegergctcorechont |= [Link]; (url, user, password); | Se || Preparec : v Precompiled SQL queries V Uses placeholders (2) for | parameters v Represents:a connection to the database. Connection conn = ..; } ae Statement stmt = com createStatemertQ; | | Statement stmt = conn. | [Link] ("SELECT * FROM users’) Srsverietere terete ~ i ape aE ) | jl CallableStatement jy — v Precompiled SQL queries | t |v Used to call stored procedures ' v Uses placeholders (7) for | | v Uses placeholders (?) for parameters 1 parameters. | Prepared Statement. psmt = | ! CallableStatement cstmt = | | conn. prepareStatement('setect |!—+ | conn. prepareCall(" | * FROM users WHERE id= ?); ~~ [Link], 123)): | [Link](1, 123); [Link]; [_Patint.executeQueryO; } (> @ curious_programmer Executing SQL Queries @ curious_programmer CRUD Operations using JDBC — FLConnection ke Connection conn = DrivaManager getConnection(.. | v¥ Insert new records into the database. V Update existing records. Read \y | v Retrieve records from the ¥ Insert new records into the database database. [ PreparedStatement psmt = [Statement stmt = conn 24 INTO users (name, email) | ResultSet rs = [Link], VALUES (?, 2°); | C/SELECT * FROM users’); while (rs. ee) & [Link]. printin([Link] "+ [Link]")); [Link] (a, “John")s ‘ ‘ ' ' [Link] | | createStatement(); ' ' ' ' psmt-setString (2, "n@[Link]’);| | ' v Update existing records V Delete records from the SS = database. | PreparedStatement psmt = | conn .prepareStatement UPDATE PreparedStatement psmt = users SET email = 7) ” conn. prepareStatement DELETE [Link](1, “newemail | eee eas __ @[Link]”) | [Link](1, 123); | | [Link] mt-exeaute Updated; af | SpsmrtexeatelipclateO; e) @ curious_programmer ResultSet Th and Concurrency @ curious_programmer Levels jj Vv Read-only access ‘Statement stmt = [Link]; “stmt addBatchCINSERT INTO users ...”); [Link] UPDATE users SET ..."); ~>~ \ [Link] FROM users WHERE v [Link]; ¥ Adds multiple SQL statements to a batch. {| Deveve= ¥ Executes the batch with a single call v Improves performance by reducing the number of database calls @ curious_programmer Stored Procedures @ curious_programmer ‘CallableStatement cstmt = conn. prepareCalll(” (Feat getUserinfo(7))"); v Stored in the database V Reusable database logic v Encapsulates SQL statements vy Atomic, Consistent, Isolated, Durable email = ? WHERE id = 7"); [Link](1, "newemail @[Link]"); BACK conn create Statement ,executeUpdateC UPDATE users SET | [Link](2, 123); | JLBEGIN Transaction |y~-~- ¥ conn createStatementO, vy Commit saves the changes (Peek aan O. C) X Rollback undoes the changes. 1 UPDATE users SET email WHERE id = ?”); stmt. setString (1, “newemail@excmple cont); ?; | [[Link]; | @ curious—programmer Savepoints & Exception Handling in JDBC @ curious_programmer [Gennection conn =... fe [Link]); [Sevepoint spi stmt executeUpdateCUPDATE users SET _ status = “inactive” WHERE id = 1); ( “Savepoint sp2 = [Link](); v CommiT |= ROLLBACK ¥ [Link](sp1); LLBACK, wv [Link]’'UPDATE users SET status = “inactive” WHERE id=2') ¥ [Link]; vy Handling SQL exceptions v Handling database-specific SQL errors. vv Ensures proper resource cleanup ry < Connection conn = [Link](..)3 Statement stmt = [Link]; ResultSet rs = stmt. executeQueryC’SELECT * FROM users) catch (SQLException e) ‘[Link]'Error! "+ [Link]"); Finally ¢ if Ceonn == null) [Link]; // Close cornecton tone @ curious—programmer Chapter 2: Java Servlets @ curious_programmer v Introduction to Web Applications Web applications are dynamic websites that interact with users, often requiring data processing. Java Serviets help make web applications faster and more efficient by replacing CGT for handling requests sah CGI vs Servlet |Z CcGL Servlets } (Common Gateway Interface) (Java Servlets) | - Scripts are executed for = Code runs within the server each request. => (managed by JVM). ~ Slower and resource-heay - Faster and more efficient aj eae | - Scripts are executed | - Code runs within the server for each request. | (managed by JVM). - Slower and resource-heavy ~ Faster and more efficient ~g | EA (web Server) [al Web Clients Servlet Architecture @ curious_programmer v Servlet API ([Link], [Link]: http) The Servlet API provides classes and interfaces for building web applications using Java The main packages are javaxserviet and [Link], which offer functionality for handling requests and responses in a server-side Java environment =f Servlet API }~~~__ - GenericServiet pss) — ServletRequest — HttpServletRequest | v Defines the core interfaces and classes. | w Extends functionality for v Handles basic serviet functionality HITTP-specific requests. wv Provides HttpServiet, HttpServietRequest, HttpServietResponse classes ~© Core Components we en ae — Servlet — ServietRequest : Servlet APL mA — ServietResponse Vv. 7 ne @ curious_programmer Servlet Life Cycle @ curious_programmer v Servlet Life Cycle A Servlet is a Java class that runs on a server to handle client requests and generate dynamic web content. The life cycle of a servlet is managed by the servlet container, which consists of four main stages: sLteaaing eS Instantiotion |-z = + Servlet a ee ie SF service es This stage is called feces meted riches | Fe — v Diasec | -{ Request Handling |-~~__ ae ee v The servlet handles client requests using the service method a 4/2 | vThis stage is called for each request Iw The serviet is initialized using the initO method. { Request Handling | - v The serviet handles client requests using the service method. @ curious_programmer GenericServlet vs HttpServlet @ curious_programmer v GenericServlet vs HttpServlet w Extends GenericServiet & part of [Link] Http pce wv Part of [Link] package. vy Designed specifically for handling HTTP requests. ¥ Protocol-independent Vv Provides HTTP-specific base class. eee methods like: request (not limited to | -——~~ ---p| °GET, + doGetO, Nese PosT, + doPost(). HTTP). | v Superclass: HttpServiet Eeeener > [] HttpServiet vv Defines a protocol-independent wv Extends GenericServiet base class for creating servlets. to specialize in handling HTTP. requests, v Request Handling: v Handles any type of request —-- (protocol-agnostic) + (SS) o[ServictRequest }>[ HitpServiet | ¥ Designed specifically for HTTP via <> methods like doGet(), doPostO, etc. TTP => a @ curious_programmer Handling HTTP Requests & Responses @ curious_programmer v Handling HTTP Requests & Responses Servlets handle HTTP requests and generate dynamic responses. This involves several steps HTTP a = —S | : Requests )_$ ea _ _ Responses ae Client Sends Request |--—— v The client (browser) sends an HTTP request to the server. @) Serviet Generates Response -- v The serviet processes the request, generates a dyramic HTML response (A) Servlet Sends Response } v The servlet sends the HTTP response back to the client (browser). -G) Client Receives Response |-~~-- Eee v The client displays the response (web page) in the browser: v The server passes the request to the serviet for processing. : | GET vs POST & Form Data Processing v GET vs POST? GET and POST are two common HTTP methods used to send form data to a server. Both methods have different characteristics and uses. v Sends data appended to URL vy Sends dota in the request | as query parameters. body (hidden from URL) ¥ Visible in browser's address bar. v Not visible in browser's ¥ Limited amount of data address bar. v No size limitations for data v Not secure for sensitive data Arar ors v Secure for sending sensitive data (passwords, etc). v [Link]/form?name=John ey ponnbate &erail=john@[Link] rame=John ‘email= john@[Link] | Server Receives Data ~> See Receives | Servlet Confi uration @ curious_ programmer © ler ) Configuration ae SSS ¥ [Link] ; Te [Link] 1 | @WebSeret VexampleServiet?) ¥ Configuration file located SSRIS Niels Vv Uses @WebServiet annotation Vv Uses XML to define servlets, to define servlets and URL URL mappings, init parameters, | mappings. etc. ‘i |! | public class MyServlet 1 extends HtpServiet {...} ae : Saat we ‘Used directly in Java source code = | Simpler and less verbose than [Link]| ¥ Helps maintain configuration | outside the code. v¥ Supports basic configurations, URL mappings, and init parameters. v Eccase to update and moaittaim. Vv Supports advanced configurations like filters, listeners, etc. Vv More verbose and requires maneatl treartteranee. V Used directly in Java source code in WEB-INF folder. vv Uses XML to define servlets, URL mappings, init parameters, v Uses @WebServiet annotation to define servlets and URL. mappings 1 1 1 t 1 br ass 1 i 1 t 1 1 @ curious_prograrmer ae Servlet Session Tracking @ curious_programmer ee ar Tracking v Session tracking is a way to maintain state (data) about a client's interactions with a web application across multiple requests Vv As HTTP is stateless, session tracking helps in remembering user-specific data | v Uses session IDs to manage | user-specific dataleg. login | | status, shopping cart, etc.) | wv Improves user experience by maintaining continuity of interactions (* + HTTP is stateless, it does not retain information between | reques +e Tracks user activities like logins, shopping cart contents, and preferences. 4e Personalizes user experience by storing user-specific data 4 Improves application security by managing sessions and preventing unauthorized access \ tae, Servlet Server | @ curious_programmer Session Tracking Techniques: @ curious_programmer S —_ Session » Tracking “URL Rewriting ¥ Appends the session ID to the URL as a parameter ¥ Small text Files stored on the user's browser. ¥ Contains a session ID for identifying users v Used when cookies are disabled or not prefered ¥ Sent back to the server ¥ Session ID appears in the with each request URL like /page:jsessionid=12345 | ¥ Can store user preferences | | and tracking information ¥ Can be less secure as session ID is visible. 4 a pe, sees ime ¥ Requires careful management for validity ae oo) igssamy A | [atte | Ppagesjsesionid=12545 | SS Servlet Servlet Server @ curious_programmer Session Tracking Techniques: @ curious_programmer a € Seon Tracking V Hidden input fields are. embedded in forms to store session IDs. wW Session ID is sent back to the server with each form submission V Used in multi-page forme and basic session management ¥ Session ID stored in HTML Form as Y, Error !
onerror - e=rro” alert ("Upload failed!"),
console. log ("Error occured: "e) @ curious_programmer File Upload & Download @ curious—_programmer 2 = => | =) S| V Allows users to upload files via forms. = { mee —~ aa D> wv Enables downloading of content like images, PDFs, and more. v Uses element with type="file” for uploads. wae = _- | | — , . =, \2 = Ss = Gated @ curious_programmer Security in Servlets @ curious_programmer v Secure User Authentication — Uses login pages and sessions to authenticate users, — Ensures only authorized users can access resources. VY Validate & Sanitize Inputs — Checks user-provided input for harmful content = Sanitizes input to prevent Cross-Site Scripting (XSS) and SQL Injection attacks. w Prevent Data Leaks —Enforces HTTPS +o encrypt data sent over the network. — Protects sensitive information from being intercepted during transmission Vv Protects against attacks — Defends against Cross-Site Scripting (SS) attacks. — Prevents SQL Injection by sanitizing inputs. = Guards against other vulnerabilities like CSRF (Cross-Site Request Forgery). @ curious_programmer Chapter 3: JavaServer Pages (JSP) @ curious programmer v Introduction to JSP JSP stands for JavaServer Pages. It is a server-side technology used to create dynamic, interactive web pages by embedding Java code info HTML. JSP allows for the creation of custom Java-based content that can be processed on the server and. displayed in a web browser. JSP Architecture )S=2 Se oe a) JSP Container —<—<<> |g | tS ISP Page Web Browser Se, Soxis | ap es Servlet t Gave) 4 ISP Request i | | he cone per J | Web Server | CA™L eon HTML Response ) 1 \ ee eee es \ 1 Response -—— a Se v — (Gerviet Gava) )—p> (Compiled Servict ) JSP Architecture Explanation @ curious_programmer [Link] Browser Sends Request: v The user makes a request by accessing a [sos JSP page through their web browser. Request > | [= © = = ell == 2. Web Server Processes Request: ___ Web Browser |v The web server receives the JSP request b ' and forwards it te the JSP container $600 for processing Je? Container |i 3. ISP Container Processes JSP Page: SS. = HLS v JSP Page: Contains HTML with embedded Java code (<% %> to generate dynamic Sort, Eas) a Gava) | || vy Servlet (Java): Converts the JSP into a servlet, which is Java code that can be & executed on the server. 4, HTML Response Sent Back to Browser: i | wv The server executes the serviet to generate the “HTML dynamic content, which is sent back to the Bb (Re. browser as an HTML response. —> The web browser then displays the generated web page to the user. Web Browser ~ Overall, ISP allows the creation of dynamic, Java-based content ‘on the server-side that is embedded into HTML, which is then displayed as a web page to the user. i (Senet Gava) ) i { | 1 i 1 i i 1 1 1 1 JSP Life Cycle @ curious_programmer { oe Ser { {7 Java Code} ‘ es ara Compile Servlet Ga) __|[ Execute Servlet ——— a= Servlet (Java) Dp GS ¥ Compilation: The JSP page is converted into a Java Servlet ¥ Loading and Initialization: The servlet is loaded into the server memory and initialized, V Execution: The servlet is executed to process client requests and generate a response. ¥ Destruction: When the server shuts down, the servlet is removed From memory x. Overall, the TSP life cycle involves converting a JSP page into a Java servlet, executing the servlet to handle client requests, and eventually removing the servlet from memory when no longer needed. _ ISP @ Servlet @ curious_programmer Difference Between JSP and Servlet: | ee erence Bete LSaniab &% %>) asp | JsP | Servlet Used fr uch Mebaet e | Osed er ha | page development | handling HTTP | HTTP requests | foembed Java | requests and | and responses | in HTML. | responses via | via pure Jova code! | pure Java code. | | Hegeoe — v Mix of HTML |v Pure Java code | © Pure Jova code | and Java code | for logic; | for logic; usually | with ISP tags usually no HTML! no HTML. | | | t ' \ ' vEasier to write |w More complex, | © More complex, | and maintain due | requires detailed | requires detailed | to embedded knowledge of Java knowledge oF Jou Java in HTML. to write and manage to write. + w Harder 40 debug | © Easier to debug | © Faster as it due to indirect directly in Jova | directly handles translation to code as itis | requests without servlet code pure Java | translation slower due to | directly handles directly handles translation into requests without! requests without servlet first. | translation. translation. I } cit lv Can be slightly |v Faster as it | ¢ Faster as it ! \ ' \ I @ curious_ programmer a JSP. Syntax = @ curious_programmer What is ISP Syntax? _|——--————---- omc JSP syntax allows embedding Java code into HTML | pages. By using special JSP tags, you can insert | Java code to handle dynamic content, making it <%! dataType method() | {code} %> | \ zi al <%\ dataType method) | | esi \ “ ' { ' | I \ I \ t | ' \ I | I EY v Evaluates and outputs Java expressions v Executes code each time the page is requested vw Initialized once, retained between requests. |v Dicploys values in| | the HTML page. i | i + xpression |, / aaa { ss eee A \ | | <% Java code here %>! | <%= expression %> | datatype methodO) | | {code} %> \ \ i | v Contains Java code. |! v Evaluates and outputs i wv Initialized once, | I i | | Je sions | w Executes code each eee = time the page is 1 \ Hi \ \\ y Displays values in retained between the HTML page @ curious_programmer ISP Directives (page, include, taglib) | @ curious_programmer | Page Directive |X ¥ Defines page-specific attributes and settings for the JSP file = Can set content type, language, error page, etc. = Example: <<% page contentType="text/html” language="java” error Fage="[Link]” %> | we) Include Directive |% VY Includes a file during the translation phase. = Used to include static content like headers, footers, etc. = Example ( <4% include file="header jsp” %> | yS | mains (Ne FIP Taglib Directive |Z V Dedlares a tag library for use in the JSP file. = Allows using custom tags by referencing a tag library 22% taglib prefix" ur ae (= & wttp:// [Link]/jsp/jsti/core” %> => | > | | [nena Eanes] @ curious_programmer ISP Directives (page, include, taglib) | @ curious_programmer | Page Directive |X ¥ Defines page-specific attributes and settings for the JSP file = Can set content type, language, error page, etc. = Example: <<% page contentType="text/html” language="java” error Fage="[Link]” %> | we) Include Directive |% VY Includes a file during the translation phase. = Used to include static content like headers, footers, etc. = Example ( <4% include file="header jsp” %> | yS | mains (Ne FIP Taglib Directive |Z V Dedlares a tag library for use in the JSP file. = Allows using custom tags by referencing a tag library 22% taglib prefix" ur ae (= & wttp:// [Link]/jsp/jsti/core” %> => | > | | [nena Eanes] @ curious_programmer JSP Actions (jsp:useBean, jsp:setProperty, etc.) @ curious_programmer i jsp: useBean | v Creates or locates a JavaBean in the page scope = Specifies a JavaBean class and an identifier (id) = Can create a new bean if it doesnt exist yet: <<} useBean id="myBean” dlass="comexample. MyBean” scope="page"/> 13 jspsetProperty |x ¥ Sets a property of a JavaBean = Can set a property value with a static value or request parameter = Example: <| | < | y[ By Other JSP Actions |x ‘Blas —_ ¥ Provide functionalities to the page ~ Examples: | | = Adds a parameter to a request. ee | @ curious_programmer | Lzagermenasnp 25 Q What are Implicit Objects? : @ eunious=programmer 2 5|_ Implicit Objects _ [7 = Predefined objects in JSP that provide access to various aspects of the web environment. They are created automatically and can be used directly in ISP without explicit declaration. ={_Common Implicit Objects y al “request | k 3i_response es\_session _ i 4 =|\— = Provides information about the request: — Provides controls for Used te get parameters, headers the response = Example | Hello, <%= [Link]”) %> | > welcome jsp | s|_ response ws|__session |Z S| application |Z Tracks user sessions.< Tracks user session. = Provides information — Used to store — Used to store about the web application, session data. session data, = Used fo shore dota behwoon sors | <9 response sendRedirect (welcome jap"); | > <% application ‘setAttribute CcompanyN SABC Corp" | — ws EE pplication | | <2 application setattribute CcompanyName’, "ABC Corp") %6> | @ curious_programmer More Implicit Objects @ curious_ programmer In addition to the common implicit objects, ISP provides more implicit objects to facilitate advanced Functionality yl Additional Implicit Objects |x OZ config = Provides the Servlet configuration information, = Used to get initialization parameters. { <<%-[Link]”) %> |-> [eevee —— © | be msl ecathest/ab | 12 pagecontext |Z = Provides access to various page attrbutes. = Used to access to request, session, application scopes. {<% pageContext forward(‘onctherPage j9p"),76> | >| | = Represents the current JSP page. = Rarely used, as it points to current page itself. (isting tote 5 pose t0StrINGO: >| [ mapee pp aaa a = For handling errors in JSP with error pages = Used as an instance of JspWwriter | <26 exception. printStack Trace! out Zz = Used for sending output to the client = Facilitates printing output to the response. 2 => [ups Helle, ISP! | <% out. printinC Hello, ISP!D; > | => [outpu: Hello, 35P! | @ curious_programmer 2 Q ISP Standard Tag Library (ISTL) @curious_programmer 1S SSTL K A powerful set of tags provided by Jova Standard Pag Library to simplify ISP development by encapsulating commen tacks. = Provides tags for control Flow, data manipulation, intemationalization, ete = Helps write cleaner and more maintainable code. < SELECT + FROM users | <“set select:/root/item’> FEM Tags x IL) Functions Tags jz = Used for parsing, transforming XML. re = Provides tags for working = Provides tags for performing with XML documents. common functions like string = Used for parsing, transforming manipulation. [ $€in:toUppercaseC hello") | =p |_$(fntoUppercaseC hello) i EE = EeSenHelt @ curious_programmer @Q Expression Language (CEL) @ curious—programmer GB What is EL? | (A simple language for accessing data in oe JavaServer Pages. w Allows easy access to data stored in JavaBeans, request, session, application, etc. ~ Simplifies JSP page development by embedding expressions directly into the JSP pages SL Why Use EL? |x 5|@ Simplifies the code |y pe (I . f HTML Page =A = Simplifies the code in ISP pages c = by reducing the need for Java ——> L {[Link]} ——— Ex code inside HTML. wv Impraes readability and maintainability of TSP pages v Makes accessing data like request, session, and beans easier BL EL Suntax [x i fol ject. property} | z i) Using EL Objects — ~ e st = secsion aoe [ $€usernamey Jai ee ee © Access request parameters: ${[Link]} © Access session attributes: ${[Link]} © Access JavaBeans properties: ${bean. property} [ #lobject property? —\=>[ Stesernamey = @ curious_programmer y MVC Architecture with JSP & Servlet @ curious_programmer MVC (Model-View-Controller) is a design pattern used to separate an application into three interconnected components. weak s[ Controller x fiMiew ig — fe) 5 | ¥ Handles user requests, |_| v Displays data | vy Manages data | and business logic. processes them, and | | 40 the user i | v Interacts with interacts with Model || ISPs | | the databose. |_| to get data | Lv Renders the UL ' | v Processes data. | | ¥ Servlets ~ |v Handles logic, flow | ~---—— aaa chs Oops! An error occurred,

Sorry an error hos occurred. Please try agin later: |

| YES Page Directive a © In the main JSP file, use the “errorPage” attribute to direct to the error page. <% page errorPage="errorPage jsp’ , Steps in Error Handling z| |v Create an error page with isErrorPage="true” to handle errors. ¥ Use the ‘errorPage’ directive in the main JSP page to specify the error page. WV When an error occurs, the user is redirected to the specified error @ curious_programmer Chapter 4: Introduction to JavaBeans @ curious_programmer v¥ What is JavaBeans? JavaBeans are reusable software components for Java applications. They follow a set of conventions and can be e-sily integrated and manipulated in visual development tools JavaBeans encapsulate data into reusable and customizable Java components known as beans | | Methods Events | l ae aa — ————— | b={ JavaBeans follow a set of conventions: |=) | wv {G0} Properties: Private fields with public getters/selters | ¥ &} Methods: Public methods to perform actions | wv & Events: Listeners to handle events JavaBean Conventions @ curious_programmer @) Properties Y Use private fields with public getters and setters to encapsulate data 2 a ee = v Keeps data hidden from public class UserBean ( other classes. private String name, // Privote Feld | y Getter methods retum the public String getName © { nO aces return name; | v Setter methods allow setting the ty vol Public Void setName(Shrng named | 9 bob SE [Link] = name; 3 } } @ Methods ¥ Provide public methods to perform actions. [ public class UserBean { Vv Public methods provide public void updateProfile © { ERSRTANG ech Sess ‘[Link]-printinC Updating a Berton actions ike! user profile y calculations, database access, ; } | etc. See ¥ Usually, method names © tent start with a verb Vv Use event listeners to handle events and notify other components. User updates profile —> Component reacts to ae Properties (Read-only, Write-only, Read-Write ) @ curious_programmer ey) JavaBean properties control access to data encapsulated in beans. Properties can be Read-only) (Write-only) ((Read-Write | (Read-only Properties | Getter method only for read access: public class Product: { private double price; //Private field Read © > ~ public double getPrice() { return price; jj Sy | $23.00 Setter method only for write access: [ public class User: { private: String: password; //Prsate fied] Write [awa | public void set Password(String passwieray” > ei this password = password; ( Read-Write Properties ) Both getter and setter methods for read and write access | public class Person: { Read & Write Private: int age; //Private field -—-----—----------—-- public int getAge'() { return age: Public void setAgelint age) { this. age = age; Getter & Setter Methods @cu © What are Getter and Setter Methods? us __programmer v Getter and setter methods are used to access and modify the value of private fields in JavaBeans. Getter Method Provides read access to a private field GO public class UserBean{ private String name; // Private field public String getName() { return name; Provides write access to a private field i => = = public class UserBean { private String name; // Private field Write ce -> [serter public void setName(String name) |- this. name = name; Getter and setter methods ensure data encapsulation, allowing control ove access and modification of private fields. v Getter methods start with ‘get’ and return the field value. v Setter methods start with ‘set’ and update the field value. Using Beans in JSP S&S Advantages of JavaBeans SO} Why use JovaBeans in ISP? ¥ JavaBeans in ISP (JavaServer Pages) encapsulate business logic and properties into reusable components called beans, providing several advantages v Beans are reusable components that can be instantiated multiple times. | “user” class="[Link]’ /> S&S WEB-INF : Configuration files (eg, web xml), Java classes, JAR libraries static : Static resources like images, CSS, JavaScript files [Link] Deployment Descriptor @ curious_programmer “Deployment Descriptor @ A deployment descriptor is an XML file used to describe how a web application should be deployed and configured in a server. _ v Defines configuration settings for the application [Link] v Specifies servlets, URL pattems, initialization parameters, and security settings | Api ication Servers vs Web Servers ) | Application | Servers =| @E © Runs web applications and © Runs web applications enterprise-level applications that generate dynamic content © Supports Servlets, ISP © Handles HTTP requests and GovaServer Pages), EJBs, JNDI,; responses and transactions, © Supports Servlets and JSP, © Provides services like database but not EJBs or advanced features connectivity. session management, and messaging, eg Overlapping 1g Feature: )————= See @ Both can run Servlets and JSP to generate dynamic web content. @ curious_programmer Introduction to Apache Tomcat @ curious_programmer @ Apache Tomcat is an open source web server and servlet container developed by the Apache Software Foundation. v Tt is used to deploy and run Java-based web applications in a lightweight, fast, and efficient environment v Supports Java Servlets, ISP GavaServer Aoneaes Tomcat Pages), and WebSocket v Cross-platform, runs on Windows, macOS, Linux, etc. SSiep loying Web Applications | To deploy a web application in Apache Torncat, follow these steps: ¥ Package the web application into a WAR. file (Web Application Archive) tomcat Avebapps/ [a}_ [Link] v Copy the WAR file to the “webapps” directory in the Tomcat installation directory v Torncat automatically deploys. the WAR file and makes the web application accessible <> hip: /Accatort srr) “Done! The web ‘application is now accessible via | ___[Link] @ curious_programmer Context & Configuration Files @ curious_programmer _{ Context Files a © Context files are XML files that define settings specific to a web application's context context xm|_ | —_—_—»> v Define the context path © [zZesreteree | vy Configure data sources (eq, database connection pools) v a Set up security constraints and session settings configuration Files Configuration files are XML files that define server-wide settings, including how web applications are deployed and managed. ¥ Most cornmon configuration files are the most common : [Link] | Deployment Descriptor — Defines servlets, serviet-mapping, welcome files, error pages, ete [Link] | [Link] Main server configuration file Configures server level components, ports, thread pools, etc Users and roles — Defines user accounts, roles, and admin permissions. @ curious_programmer Chapter 7: Session Management & Security LB Authentication & Authorization Iz Bie Anthentication Authentication is the process of verifying who a user is. Tt ensures only legitimate users can access an account or system. ** ‘OGIN | Gomis: | —> Gorn) (GSEs > Passwords > Two-Factor Authentication Authorization Authorization is the process of verifying what a user is allowed to do. It controls access levels and permissions after authentication. Examples Roles ------>|@ Roles | + > Access Control Lists (ACLS) Form-based Authentication & Programmatic Security @ curious_programmer Form-based Authentication is the process of verifying a user's identity using an HTML form. & Username Gaexxx | Locin User123, yw Programmatic Security a Programmatic Security involves handling authentication and authorization through code ina secure, programmable way ~ Developers use server-side code to check a user's credentials and enforce access controls based on roles or permissions. v Example: : if Cauthenticate(username, password) {iF (user hasRoletadmin’)) { // gpark adrein access } else / grant regular access + --- + Qe @ curious_programmer Session Timeout & Preventing Session Hijacking @ curious_programmer Session Timeout is a security feature that automatically logs out a user after a period of inactivity ® Prevents unauthorized access if a user leaves their session unattended. > Reduces the risk of sessions being exploited through idle time = eee Your Session Will Expire In 0:30 0120 v Example: Session Hijacking is an attack where an attacker takes over a user's session, v Use Secure Cookies > Implement HTTPS v Regenerate. Session IDs Cae { <(sessionid> 123ABC4S6DEF @ curious_programmer acm kon Cees energy | \ & HTTPS Basics &f CSRF 2 XSS Overview @ curious_programmer ~ HTTPS stands for Hypertext Transfer Protocol Secure, Tt encrypts data transmitted between a user's browser ~ HTTPS is important: ~ Encrypts data to keep it secure from eavesdr: rs. ~ Secure communication between a user's browser and server Caen ILESRE (Cross-Site Request Forgery) Jz =CSRF tricks a user into performing actions they didn't intend to by exploiting their authenticated session. : -XSS (Cross-Site Scripting) }z—=—=> 4 XSS involves injecting malicious scripts: into web pages viewed by other users. @ curious_programmer Chapter 8: Filters & Listeners @ curious_programmer y Filters _ —— Filters are used to process and modify incoming requests | or outgoing responses before they reach the target resource. | ¥ Filter Life Cycle Incoming Request === Outgoing Response. —A filter has three key stages: 1. Initialized: initQ called once at startup 2. Filtering: doFilterO called for every request or response. = Destroyed: destroy() called once when filter is removed. (¥ Authentication Filters ) Authentication filters are used to verify and authenticate users before allowing them access oo-- => Check Credentials }------ == ae . Incoming aie Bequeey ls Authentication E= ABs : Se cy Denied eee > Access Granted =—d) Logging Filters & Compression Filters @ curious_programmer v Logging Filters = Capture and lag information about requests and responses ¥ Logs details of each request, including URL, parameters, headers, timestamp, etc ¥ Logs details of each response, including status codes, content type, size, etc v Helps in monitoring, debugging, and auditing web applications. ¥ Logging Filters } Tncoming Request (Logs requests & |— Compression Filters = Compression Filters reduce the size of web content before sending it to the client. v Tt uses GZIP compression to make responses smaller in size Benefits include: v Compresses responses, such. HTML, CSS, 35, JSON, reducing their size v Faster lood times by reducing the amount of data sent over the network. v Saves bandwidth, especially beneficial for users with slow connections, GET /page?user=1234 | POST /form- 200 OK 123-2an2018 20.21 -3236 3..Jan 2018 1936 -059 Listeners @ curious_ programmer v_Listeners * Listeners are classes that listen for specific events in a web application and respond when those events occur. thee Eo) v. Eeonontaaes + Listens for changes in the servlet context Capplication-scope) v¥ Context Initialized: Called when the web application starts. v Context Destroyed: Called when the web application shuts down, eee v HttpSessionListener + Listens for events related to user sessions. v Session Created: Called when a new user session is created, ¥ Session Destroyed: Called when a user session is invalidated or times out — (Track user login/logout activity ) a @ curious_programmer Listeners @ curious_programmer v Listeners * Listeners are classes that listen for specific events in a web application and respond when those events occur (Execute custom code when specific events happen } v Request Listeners + Request listeners respond to events in the request life cycle. VY Request Initializea: Called when a new request is received. v Request Destroyed: Called when a request is completed ———— {REQUEST LIFE CYCLE | Z- el Process Request Request Destroyed | Request = — a “Monitor & respond to request events | v_ Use Cases Vlog requests and responses for monitoring and auditing v Check authentication before processing a request V Track performance metrics like request processing time wv Implement custom logic like setting attributes in requests. @ curious_programmer Chapter 9: Enterprise JavaBeans (EJB - Overview) = @ curious_programmer v Introduction to EJB vv What is EJB? EJB stands for Enterprise JavaBeans. Tk is a server-side component architecture used for building scalable, robust, and transactional business applications in Java. Entity Beans <— |! i Other Systems VY Client: The extemal application that interacts with the EJBs. ¥ EJB Container: The runtime environment within the app server that manages EJBs. V Session Beans: Handle business logic. v Entity Beans: Represent persistent data Stored in a database. V Message-Driven Beans: Process asynchronous messages, [@ Client: The external application that interacts with the EJBs. (ESB Container: The runtime environment within the app server that manages EJBs. Session Beans: Handle business logic. [@ Entity Beans: Represent persistent data stored in a database. [Z Message-Driven Beans: Process asynchronous messages. Types of EJB: @ curious__programmer ( Session beans are EJB components that implement business logic in an application. They run within the EJB container in an application server wv Asingle, shared instance used by | all clients | (. Does not maintain ¥ Maintains state any state between between client calls client calls. for a spocific user. | Vv Each call is cE Remembers user | | y Maintains glebal state i : interactions. Seas independent interactions. | | ecross users. J Scapa —> —> \- | E &22a2 <4 . Clients Client State! Sa V¥ Maintains state between client calls for a specific user. Vv Remembers user interactions. @ curious_ programmer Message-Driven Beans & EJB Life Cycle @ curious_programmer \ Message-driven beans are EJB components that process asynchronous. | messages sent to the application from a message-criented middleware | (MOM) or message queue. Does Not Exist ~~ Anew EJB instance is cre. by the EJB container ENB container initializes EJB container initializes and “e the bean. and ae bean. Does Not Exist Bean ic removed from The bean is — to the pool and cleaned up. process incoming messages v Does Not Exist: Bean is removed from the pool and cleaned up. v New Instance: A new EJB instance is created by the EJB container ¥ Initialization: EB container initializes and sets up the bean. Y Ready: The bean is ready to process incoming messages. ¥ Message Processing: The bean processes incoming messages from _| the message queue. @ curious_ programmer | Transactions in EJB |v Enterprise JavaBeans (EJB) use transactions to ensure data integrity and consistency across business operations Database | Y ESB transactions are automatically managed by the EJB container, ensuring ACID properties A\) operations are treated as a single unit Transactions | | Intermediate states | | Once committed, leave data in are not visible to a. consistent || other transactions | | permanent. state. \ {ESB vs Spring (Overview) } : = = @B Spring Framework |v Java EE server- Y Lightweight, modular |_| Type side framework Roeore |_| Fransactional| W Built-in container- Y Flexible trarsaction Management | managed transaction management with support @ Transactional annotation eae XML-based configuration within application server Deployment | 7 Requires deployment in | Java EE application server | Learning Curve] 7 Moderate to steep v Annetation-based configuration and XML support Y Can nun in any Java environment, standalone or with a server V Friendlier learning curve ©) \ @ curious_programmer Chapter 10: Java Persistence API (JPA) / Hibernate (Basics) @ curious_programmer yv_ORM Concepts ORM stands for ObjectRelational Mapping, It is a technique used to map Java objects to database tables t—' ORM _|g—> ORM allows developers to interact with a database using Java objects instead of SQL queries. v_ JPA Architecture Entity Mapping, @ curious_programmer v Annotations Annotations are used to define mappings between Java objects and database tables in JPA = @Entity: marks a class as a JPA entity — @ld: marks the primary key of the entity — @Table: specifies the table in the database v Relationship Mappings: v@OneToOne: defines a one-to-one relationship between two entities. (Oto) (Gretoore) (Chet Ore) Sera AS | Entity & lod entiye Fae | Y@OneTeMany defines a one-to-many relationship where an | entity is related to many other entities. v@OneToMany defines a many-to-many relationship | between two entities Stenenany | [Entity e | Entity 2¢| GOneToMang — ee Y@ManyTeMany defines a many-to-many relationship between tuo entities

You might also like