0% found this document useful (0 votes)
18 views76 pages

4 and 5

The document covers various aspects of web technology, including web development strategies, HTML, CSS, JavaScript, and server-side technologies like JavaServer Pages and Enterprise Java Beans. It provides an overview of Node.js, its environment setup, and key features such as asynchronous programming and event-driven architecture. Additionally, it discusses the types of session beans in EJB, their features, and the importance of callbacks in Node.js for handling asynchronous operations.

Uploaded by

u17270074
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)
18 views76 pages

4 and 5

The document covers various aspects of web technology, including web development strategies, HTML, CSS, JavaScript, and server-side technologies like JavaServer Pages and Enterprise Java Beans. It provides an overview of Node.js, its environment setup, and key features such as asynchronous programming and event-driven architecture. Additionally, it discusses the types of session beans in EJB, their features, and the importance of callbacks in Node.js for handling asynchronous operations.

Uploaded by

u17270074
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
You are on page 1/ 76
a WEB TECHNOLOGY (=, (BCS502) HANDWRITTEN TOPIC Cea teful Session bean, Stateless Session bean, Entity bean. ee ee te eed sengurcupmgteme LeASE BCS502 Introduction: Introduction and Web Development Strategies, History of Web and Internet Protocols Governing Web, Writing Web Projects, Connecting to Internet, Introduction Internet services and tools, Introduction to client-server computing, |Web Page Designing: HTML: List, Table, Images, Frames, forms, XML: Document typ. \definition (DTD), XML schemes, Object Models, presenting and using XML, Using XML [Processors: DOM and SAX. ICSS: Creating Style Sheet, CSS Properties, CSS Styling (Background, Text Format, TL |Controlling Fonts), Working with block elements and objects, Working with Lists and Tables, ICSS Id and Class, Box Model (Introduction, Border properties, Padding Properties, Margir [properties) CSS Advanced (Grouping, Dimension, Display, Positioning, Floating, Align, Pseudo class. |Navigation Bar, Image Sprites, Attribute sector), CSS Color, Creating page Layout and Site Designs. \Scripting: Java script: Introduction, documents, forms, statements, functions, objects, IIL introduction to AJAX. \Networking: Internet Addressing, InetAddress, Factory Methods, Instance Methods, TCP/IP| \Client Sockets, URL, URL Connection, TCP/IP Server Sockets, Datagram. [Enterprise Java Bean: Creating a JavaBeans, JavaBeans Properties, Types of beans, Statefull IV [Session bean, Stateless Session bean, Entity bean, \Node,js: Introduction, Environment Setup, REPL Terminal, NPM (Node Package Manager) ICallbacks Concept, Events, Packaging, Express Framework, Restful API |Node,js with MongoDB: MongoDB Create Database, Create Collection, Insert, delete, lupdate, join, sort, query. IServiets: Servlet Overview and Architecture, Interface Servlet and the Servlet Life Cycle| V Handling HTTP get Requests, Handling HTTP post Requests, Redirecting Requests to Othe: Resources, Session Tracking, Cookies, Session Tracking with Http Session \Java Server Pages (JSP): Introduction, Java Server Pages Overview, A First Java Server Page Example, Implicit Objects, Scripting, Standard Actions, Directives, Custom Tag Libraries Engineering Express © 4 Enterprise Java Bean (EJB) ee ee as ; f thi nterpri lition) platform. is ign simplify the creation of large-scale, distulayted, and secure busine: lication: smanagir =I ha ‘ransaction: security, and remote communication automatically. Key Features of EJB: Re Ci . EJB provides reusable modules of business |_logic, making_it_ easier to develop scalable applications. ___ |_ Simplifies Development: Developers.can focus on business logic __| |_without worrying about-system-level operations like database ____| |_management, network communication, or threading. Distrib C, ings EIB : Ls |_CRML), allowing-applications to work across different-systems __| |_seamlessly. 1 on a F f ; Security: Provides robust, built-in security mechanisms for enterprise- |_level applications. a a ; ssl trade wo ih i LEAL LL LIL lh , Ayre Why use EJB? T ild large, distril nd. ve enterprise lications. To simplify the development of applications by handling system services automatically. Engineering Express © & Creating a JavaBeans sa 2 a Ws ific conventions. Ii I lar and re I for application. mn in_graphical interfe L if Mak ication: —__i an yy perform business logic > || Steps ti (pegengelayabogpym, "GSE 1. || Create a Public Class: || The class must be declared public_so it can be accessed by other | |_parts of the application _____|| their state to_be saved and restored. ——2]| Use idtenProper IES VF PS Py EE ce BP |_encapsulation. ____|| To access and modify private properties, use get and set methods _____|| These methods should ; le Paconeeaneoe —_S.| i ic no- y I) easy instantiation. Engineering Express © | Example: Creating a Simple JavaBean import java.io.Serializable, : Gs : serializable £ private String name; // Private property private int id; are ni or public Employee) £ f LL Getter for ‘name: UN ie Sith (iN 16 on A _—\\ return name, i WLS > DLC i. ea de this.name = name; 2 1 Getter for ‘id. public int getldQ £ return id; 2 Setter for ‘id ee Cint i £ this.id = id; f 2 Engineering Express Qe & JavaBeans Properties getter an y hh folk hese naming conventions: For a property named property, the getter method is getProperty()_||__ andthe setter method.is setProperty(value), == « For a boolean property, the getter method is isProperty() ___> || Types of Properties in JavaBeans: ___1. || Simple Property: || single value_that can be read_or written. ___||A property name with getNameO_and_setNameQ methods. ____>|| Example: Simple Property ____||public class Product £ Getter public String getProductName() £ return _productName; $$ 2 Setter eae lic void setPre i re ni this.productName = productName; £ Engineering Express © | Boolean Property: instead of get. A_property isActive with isActive() and setActive() method: public class User £ private boolean isActive; // Boolean property // Getter _public boolean isActiveO_£ a ah return isActive; i JL Setter public void-setActiveCboolean isActive) £2 this.isActive = isActive; 2 Engineering Express © |public class Student £ private int[] scores; // Indexed property /L Getter for the whole amay = public intl] getScoresC_£ public void setScoresCint[] scores) £ this.scores = scores; Setter for a specitic index public void setScoresCint index, int value) £ this.scores[i = val 2 Engineering Express © + Types of beans : ifi ra a Ss Stateful Stateless Entity Session Session Bean Bean Bean. |Key Features: Maintains State: Retains information across method calls, useful for Client-Specific: Data is uni ‘ , |_others. Lt EL bE Destroyed After Session Ends; The bean is typically destroyed when the client's session ends (e.g, after logout). ion Lit Mai the container, tie ent’. session lifecycle. Engineering Express © | Example Use_Cases: | Game State: Stores progress or score during gameplay. 4 Stateless Session bean A z i i is he maintain_any client-specitic meth lis, Evert Key Features: | No. Client-Specific Data: Does. not_retain_any_information about ___| time_a method is invoked, the bean_is considered a new instance, and _||_ it doesn’t store data between calls, ~ |_previous method calls or-client: 2 ie EJB container but ‘a not ae a _ Le session | lifecycle, TATA oe re a | Database Operations: Methods that perform simple queries or updates. he an: handle individual, isolate lreguests such as generating report: Engineering Express © 4+ Entity bean - ee ( 5) ted j ; cee ae usually tied to a database tabl Key Features: is : The entit n_Ye record in Changes made to its properties are automatically stored in the database, tv |_Primary Key: Each entity bean typically has a primary key to uniquely identify it, similar to how records in a database table are |_wniquely identified mC |_Stateful: Unlike stateless beans, entity beans have their state ___| flecti , ; |_database. |_container automatically handles the mapping of the bean’s fields to _| interacting with databases to create, read, update, and delete records. Engineering Express © 4+ Node,js : Introduction ; a 2 JavaScri ine C scalability, especially for real-time application: |Key Features: |_Asynchronous & Event-Driven; Node,js is designed to be non-__| blocking and asynchronous, which makes it highly scalable, It uses i an event-driven archit Ta les many. ions simultaneously without waiting for tasks to finish. |_Single-Threaded: Node,js operates ona single thread, which means it_| |_handles requests sequentially. However, through asynchronous ___| a f Hick Ail . 5 . i ing Windows, macOS, and Linux. |_NPM (Node Package Manager): Node,/s comes with.NPM, a package | : f libraries for aiff |_tasks, making development easier and faster. Fi DO i ee a yal ‘ which makes it ideal for applications like APIs, real-time chats, or |_streaming services, TATA oe a a a a | Real-Tip Applications: Such as chat applications, online games, etc. Deen ee eae lode,js_is commonl to create RESTful APIs for Services, Microservices; Lightweight and scalable backend services. Engineering Express Qe 4 Environment Setup | Steps to Set Up Node,js: _ Download Node,js: Go to the official Node,js website, 2 Choose the version suitable for your system (LTS version is recommended for most users), » Download and instal) the installer. | Vert MSealntiG eee a | —"_—"_\ ~ 77, Va | After installation, open the command line CTerminal_or Command | | Prompt) and check the version of Nodes by running the following command: node -v. : Sie : Z NPM (Node Package Manage): NPM is installed automatically with Node,js, You can verify its npn =v |Setting Up a Project: o_Create a folder for your project. o Inside the folder, open the command line and initialize a Node,js roject ing: npn init Engineering Express © al rn is fil js). ri ir rip is fi 4 it_wit node app, + REPL Terminal |REPL stands for Read-Eval-Print Loop. It-is an interactive ______| | programming environment that allows-you to execute JavaScript code | directly in the terminal Features of REPL: pL LL | Read: The-REPL. takes the User's input ClavaScript-code), ___| cual ON , \_Print: It prints the result or output of the code, code, BE nar eee ee |_ Open your terminal (Command Prompt, Terminal, or PowerShell). Type node and press Enter. You'll enter the Nodes REPL environment, and you can start typing LLL vipt interactivel Engineering Express © | Example: console log Hello, Node,js!"); Hello, Node,js! # the REP. ey ee Use Cases: Testing small code snippets: You can quickly test expressions or functions without needing a full scrip Learning and experimenting; Great for beginners to learn JavaScript || interactively, 4 NPM (Node Package Manager) NPM js the default package manager for Node.js, and _it isan __| |essential tool for managing-packages (libraries or dependencies) in | manage the dependencies their projects require. [Key RegitressafaN PRES WF Fy Fy EE ce BP | NPI . a Wah ; Sea Fi : . fy F nga Example: project relies on in a package,json file. This file tracks all the libraries your project uses. a SY n_run predefined scripts lib ile Y custom tasks using NPM. Example: npm run start Engineering Express Qe is >: ini |npm update: Updates installed packages to their latest version: npm uninstall _: Removes a package from the project. «|| npm list: Lists all_install. hages i) (eMC | Example: | To install a package like express in your project: | npm-install express \dependency in_your package,json. 4 Callbacks Concept |A callback isa function that is passed as an argument to another A f EM pevior: Callbacks are commonly used in asynchronous programming to ensure in funct See o-task is fini ‘ lei on vngkive: oi EAT poe Points fi II PA cinchrondus: Benavides eee eee Node,js is non-blocking and asynchronous, meaning it doesn't wait for one operation to complete before starting another. Callbacks are used to handle asynchronous operations, ensuring Engineering Express © finish 2 A calll is tially a function that is in ther function, This is then i ft in_functic completes its task. Example: function fetchData(callback) £ _setTimeout(Q)_=> £ const data = "Data fetched’; callback(data); // The-callback function is called with | data 3, 2000); 3 fetchDataCfunction(data) fn console.log(data); // Output: Data fetched QD; 2_In this example, fetchData takes a callback function as an argument. The callback function is called with the fetched data _| immer seeps ier || Error-first_ Callback: 2 A common pattern in Node,js callbacks is the error-first callback. This means that the first argument passed to the callback is ically an error object Cif an error occurred), and the argument is the result of the operation. Engineering Express © Example: if Cerror) £. callbackC Error reading file’, null); 2 else f I ni < Ir, 2 2 readFile(function(error, data) £ fea MO |Z — an — console.logC'Error:", error); Zelse £ console log( File Data." data); z D: Nested Callbacks (Callback Hell): hard-to-read code, often referred to as "callback hell," | Example: doFirstTaskCfunctionCesultl)_£ doSecondTask(result!, functionCresult2) £ doThirdTask(result2, function(result3) £. Final callback Be 2; DR: Engineering Express © ee : ee hy hand Benefits of Callbacks: Non-blockin vations: ¢ nti nin her ik iting von ration complete. Improved performance; With callbacks, multiple operations can run i !, improving efficic a4 Events __ Lln Nodejs, events allow a program _to_listen for specific actions or | loccurrences and trigger_a_response when-they happen. These events | ' ; \respond to things like HTTP requests, file changes, or user action: Key Points About Events: The core of event-driven programming in Node,js is the [EventE mites | EventEmitter class. This class allows objects to emit events and | |___listen_for them. | Example: const EventEmitter = requireCevents'); const emitter = new EventEmitterO; emitter.onCeventName’, function _£ console,log( Event occurred’); DR: emitter.emitCeventName); // Output: Event occurred! Engineering Express © vent listeners are functic that_aré Ihe fie event is emitted, Y iple listeners for a single eve | Example: emitter, arg console,logCHello, ' + name); QD; emitter.emitCgreet,, ‘Alice); // Output: Hello, Alice + emitter.emitCeventOnce); Output: This will ran_only once! : HPenaneoneas No output Engineering Express © eae oo error event. | Example: emitter.onCerror, functionCer) £ -onsole.logCError occurred: err); i emitter,emitCerror, ‘Something went wrong!'); it Err a thin I [Eveht Dien Araniteciie, ——_—\ ~ 7 VE Node,js is built around_an_ event-driven architecture, where ____| |___ multiple processes or operations can be managed asynchronously. \ : ; callbacks when events occur, [Benefit Vee | the program, making Node,js highly efficient. Flexibility: You can listen for many different types of events and _| ae Engineering Express © a js isa ion of files tl Ne together. It typically includes: at The_main module JavaScript file) | Metadata like the package,json file, which defines the _| package's dependencies, version, and other ___| configuration: |Creatingig Backage T= WF Fy Fy EY Ec, ey ea ere) y iy This command prompts you to enter details about your package, such ; oth nstalling Extemal Packages: You can install external packages from the NPM registry. For example: nprn install expres This command will install the Express framework and add it to th node_modules directory. Engineering Express © P, ae : —e oh " + The package name, version, and description. +_A list of dependencies and their version: + Scripts for automating tasks (like starting the server, _ | testing, etc.) Example of a package,json file: t "version": "1.0.0" I "description": "A simple Nodejs app, "main": "indese je "scripts! £ Degeall, ty index. js" 3 “dependencies". £ mG 17 3 3. |Managing Dependencies T saceai ing NPM ae ison fi under the dependencies section. To install all dependencies listed in package,json, you can run: npm instal) Engineering Express © pi be Benefits of Packaging: = _Code Reusability: ORAZ io |__. Collaboration: Node,js allows developers to_share packages via | nd: np publish This wil i ip. _ Updating a Package: a 2 To update a package, Pa can change the version number i a json lish iin. [erates NPM, fostering a collaborative environment. Versi | . fersion Management: With package,json, you can manage and | |___ library. Engineering Express © 4 Express Framework managing routes, and serving static files, Express helps developer: le re sith fe lines of. nny ing re |Node,js alone Key Features of Express,js: .||_ Routing: Express offers an_casy way to handle different HTTP requests (GET, POST, PUT, DELETE) for specific routes. |_Middleware: It allows for easy inclusion of middleware functions to | |_handle requests and responses. Middleware can perform tasks like | Tk A. Enoines: : : | EIS, . : er \ I eA) el el el E—EeEE ing Static Files: 6 —_— he : ic POSEN Se FnGae |Request Handling: It simplifies the process of handling requests and _| sending responses by providing helpful methods like res.sendQ) | resisonQ), and res OVE middleware with custom error-handling function: Engineering Express © | Setting Up Express: reating a Basic Express Server: After installation, create and write the following code to set-up a basic server: const express = requireCexpress’); const app = express(); const port = 3000; A 1 ao |___// Middleware to parse JSON request body app.use(express.json()); UGE deateguesi ED We Wp) FE’ EY ce BNP app.get(l, (req, ves) => f Ce ees ‘| pe POST request to /submit. app. post( /su bynit' (req, res) => £ const data = req.body; Access POST data resjson(£ message: 'Data received, receivedData; data ?); 22; app.listen(port, () => £ consolelogCServer is running at_http://localhost:$fport?); DBs Engineering Express © Explanation: | vaguects at the coat VEY C/) and sands back a welcome | |___message, + The app.postQ) method handles POST requests sent to /submit. The_express,json() middleware is-used to parse the request body as ISON, whi + The server is listening on ind when a POST ré made to /submit, the server responds with the received data in ISON. format. i: Runn. : To start the server, run the following command: a ade apr jcey ~~ Tall eee. aan F exe om). ore As RESTful APIs: E . ild RESTful AP. oe ae ino HLIP methods like GET, POST, PUT, DELETE, | Web Servers: Create web servers to handle HTTP requests, manage | |_routes, and serve content. ingle-| icatic : ic fi icall update content for smooth user experiences. eee Real-Time Applications: Combine with WebSockets to create chat live notificatic r coll i Engineering Express © + Restful API | Update, Delete) operations on resource. Install Node,js and_Express_in_your project. Run the following commands: inp init gy npm install express |___const express = requireCexpress'); const app = express); const port = 3000; app.useCexpress,json()); — res.sendCHello, World!'); Bs app.postC/data, Creq, res) => £ resjson(£ message: ‘Data received, data; reg.body 2); BD» app.listen(port, () => £ console,logCServer running at_http://localhost:$éport 7); DBs Engineering Express Qe Lapp.get() handles GET request: Lapp,postO) handles POST requests and processes the data sent in the | Lrequest_body, Running the Server: Run the server using: node app, Access the server via http://localhost:3000. Comi GET: Used to fetch data. |POST: Used to send data to-the-sewer, ~~ |PUT: Used to update existing data. | DELETE: Used to delete data. Reglnet Handlifig in Express: +||req.body: To-access POST data. i WA is \req.query: To access query parameters in the URL. Error Handling: You can handle errors with a simple middleware like: ves.status(S00),sendC Something went wrong!'), 2; Engineering Express © 4+ Node,js with MongoDB riented form Inlike traditional relational Mon. nd 1 re in_flexibl. Form IN). It! icatic iri | high- rforman ndllip ial “he n't fit well into_a structured, relational_model. Environment Setup: Install MongoDB: |_Either install MongoDB locally-or use MongoDB Atlas (cloud). ___| |_Install Mongoose: const mongoose = requireCmongoose’); mongoose,connectCmongodb.//localhost:27017/mydb, £ | useNewUrlParser: true, useUnifiedTopology: true 2; Engineering Express @ them. 4 Create a Schema and Model a A schema defines the structure of your documents in a collection, specifying the fields and their datatypes. Mongoose uses schemas to_| Lenforce this structure and_allows creating models for interacting with | \the database. const mongoose = requireC mongoose’); const.Schema = mongoose.Schema, Define schema const _userSchema = new Schema name: £ type: String, required: true age: £ type: Number, required: true f ) Create a model based on the schema const User = mongoose.modelC User, userSchema); Engineering Express © 4 Inserting Data te ighth O. Lmethod for single documents or insertMany() for multiple documents. | Insert a single document: const user = new User(f "Toh : age: 2 Bs user,save() then(Q_ => consolelogC User Added )) catchCerr => console.errorCError’, err)); LinseraniEpleeaner nent s:\——-—____\ ——=— Se i CL E name: Alice, age: 30_}, £ name: Bob, age: 35 3 Dv. then(O => console.logCUsers Added)) catchCerr => console.errorC Error, err)); + Deleting Data | Data_can be deleted using deleteOneQ for single documents or __| |deleteMany() for multiple documents = Delete one document: User.deleteOneCf name: ‘John Doe’ 3) he => console y Del catchCerr => console.errorCError:, err)); Engineering Express © i User deleteMany(£ age: £ Sate: 30 } 2) then(O_ => console.logC Users Deleted )) catchCerr => console.errorC Error‘, err); + Updating Data User,updateOne(f name: ‘John Doe’ 7, £ $set: £ age: 26 ? 3) then(Q_ => console.logCUser Updated)) catchCerr => console.errorCError’, err)); I - AN ah serupdateMany(£ age: £ ote: 30-3 3, £ tet: £ age: 3/ } 2) |_____.then(() => console.logC Users Updated) catchCer => console.errorCError:', err)); PT obtih » 5 Seah at : pa EG const postSchema = new mongoose,Schema(f content: String, userld: £ type: mongoose,Schema,Types.Objectld, ref: ‘User 3 2; const Post = mongoose.model( Post’, postSchema); le: Fin Y ant late rel vr findByldCuserld, lateCposts') then(user => console.log(user)) catch(err => console.errorCEnror:, err); Sngineering. Express @ soscmns at cdeadhs the weit nce occsaning BB \descending (-1) order. Sort users by age in ascending order User.findO, sortC£_age:-1-3). then(users => console.logCusers)) hi => I iC Error: // Sort users by age in descending order anew User.findO.sort(£ age: -1 3) ~ then(users => consolelogCusers)) if catch(err => console.errorCError:, err); + Querying Data \MongoDB supports a wide range of query operators to filter data.___| + Find users with age greater than_or equal to.30: See eo SS => consoleerrorCError:, err); oe : Pe User.findCf age: £ $gte: 25, $lte: 30 ? 2) .then(users => console.logCusers)) catch(err => console.error' yr, err); a WEB TECHNOLOGY (=, (BCS502) HANDWRITTEN Other Resources, Sesion Tracking, Cookies, Session Tracking with Http Session epee ee oestrone any terete Tage ample mpl bcs Sepng Sunde acing Deas cxemteg [TINT T- 5 | bran il BCS502 Introduction: Introduction and Web Development Strategies, History of Web and Internet Protocols Governing Web, Writing Web Projects, Connecting to Internet, Introduction Internet services and tools, Introduction to client-server computing, |Web Page Designing: HTML: List, Table, Images, Frames, forms, XML: Document typ. \definition (DTD), XML schemes, Object Models, presenting and using XML, Using XML [Processors: DOM and SAX. ICSS: Creating Style Sheet, CSS Properties, CSS Styling (Background, Text Format, TL |Controlling Fonts), Working with block elements and objects, Working with Lists and Tables, ICSS Id and Class, Box Model (Introduction, Border properties, Padding Properties, Margir [properties) CSS Advanced (Grouping, Dimension, Display, Positioning, Floating, Align, Pseudo class. |Navigation Bar, Image Sprites, Attribute sector), CSS Color, Creating page Layout and Site Designs. \Scripting: Java script: Introduction, documents, forms, statements, functions, objects, IIL introduction to AJAX. \Networking: Internet Addressing, InetAddress, Factory Methods, Instance Methods, TCP/IP| \Client Sockets, URL, URL Connection, TCP/IP Server Sockets, Datagram. [Enterprise Java Bean: Creating a JavaBeans, JavaBeans Properties, Types of beans, Statefull IV [Session bean, Stateless Session bean, Entity bean, \Node,js: Introduction, Environment Setup, REPL Terminal, NPM (Node Package Manager) ICallbacks Concept, Events, Packaging, Express Framework, Restful API |Node,js with MongoDB: MongoDB Create Database, Create Collection, Insert, delete, lupdate, join, sort, query. IServiets: Servlet Overview and Architecture, Interface Servlet and the Servlet Life Cycle| V Handling HTTP get Requests, Handling HTTP post Requests, Redirecting Requests to Othe: Resources, Session Tracking, Cookies, Session Tracking with Http Session \Java Server Pages (JSP): Introduction, Java Server Pages Overview, A First Java Server Page Example, Implicit Objects, Scripting, Standard Actions, Directives, Custom Tag Libraries Engineering Express © 4 Servlets |handle client requests, process them, and generate responses marnicall vl re f thi ni inlk Yr f) nic ications, The i ) lie 1 rowser: y respon: > || Purpose: Servlets Ei (0_cre ications thai nic content (eg. retrieving data from a database). |_ Servlets are-capable of handling complex requests obtained from the _| |_web server. iow it ok ee —i The client sends an HTTP request to the server. Engineering Express © ___> || Advantages of Servlets: 1.|| Faster Than CG] + Servlets are fe H ) th n't cr new pr for every incomin request. 2, + Written in Java, servlets can run_on any platform that supports the Java Runtime Environment CIRE), 3,|| Efficient Resource Management _ Servlets run within the web server process, eliminating the __| overhead of process creation. ~A single servlet instance handles mul iple clien reque: ti 9 _ Ffocti of client_state. . = fit f aay ; |Java Platform Benet a Java Dan 2 «They can leverage other Java APis, such as JDBC, for tasks like _| database connectivity. RCostepireciive see « Many lightweight web servers that support servlets are free or inexpensive for personal or low-traffic usage. Engineering Express © nd _the server, It pr. i from the client and gener. \dynamic responses. Execution of Servlets basically involves Six basic steps: web browser or another HTTP client. || Web Server: The web server receives the HTTP request and forwards it to the servlet for processing. Engineering Express © s ers Sy, The se! of servlets. a_It loads servlets, manages their initialization, and handle: communication between the servlet and the server. | Servlet (Middle Layer: The servlet processes the client's request, performs business logic Clike accessing a database), and generates a a se, [ call ent like HT/ XML based on the client's request. |ResponseERackato, CENDS Fy Fy FE’ EY ce BI | The servlet generates a response and sends it back to the servlet container. The container forwards this response to the client, completing the request-response cycle. Engineering Express © ____ || Common Gateway Interface(CGI): 2 ++ re ing client re ind_generatin ynic_conteri In_CGl application, when _a_client i uni — he Nn lowin rations: ____||_-e Jt first locates the requested web page ie the required CGI application using URL. It then creates a new-process to service the client’s request, __| » Invokes the CGI application within the process and passes the | request information to_the |_ ot eno AO | —"_—"_—\ ~ 72, Va e Collects the response from the CG! application | to the client. CGI Processing a Client's Request 1° a el ia | rd a se Ele ae Engineering Express e |So, in CGI server has to create and destroy the process for every re incre \ Difference between Java Servlets and CGI: oie Servlet CGI (Common Gateway Interface) |_| Servlets are portable and |_| efficient. CG! is not portable |_| In Servlets, sharing data is |_| possible. In CGI, sharing data is not possible. | | Servlets can directly communicate with the webserver, CGI cannot directly communicate with the webserver. | | Servlets are less expensive than | | cal. CGI is more expensive than Servlets. Servlets can handle the cookies. CGI cannot handle the cookies. Engineering Express e Servlets APIs |Serviets are built from two packages: |_javax.servlet(Basic) javax.serviet.httpCAdvance) Vari I rH Component Type Package q |_| Servlet Interface Javax.serviet.* || | | ServietReguest Interface avax.serviet.* | L) ServietResponse Interface javax.serviet.” H i GenericServiet Class avax.serviet.* I [| HttpServiet Class Javax.serviet.http.” | | HttpServietRequest | Interface avax.serviet.http.” || HttpServletResponse | Interface javax.serviet.http.” 4 i Filter Interface avax.serviet.” | [| ServietContig Interface Javax.serviet.* | Engineering Express © 4 Interface Serviet ; : |Key Points: Definition: The Servlet interface belongs to the javax.servlet package and defines the lifecycle methods and_responsibilities of a servlet. .| Core Methods in the Servlet Interface; | nine servlene cbriagenntig): ——_—-~ ~ 77 WN | Called by the servlet container to initialize the servlet. This method _| ; : if f |_service(ServietRequest_req, ServietResponse res): |_Handles requests from clients and generates responses. This method _| : h : \_destroyO.: Invoked by the servlet container when the servlet is being taken out tServletConfig0: Returns the ServietConfig object containing configuration information for the serviet. getServietInfoQ): Provides metadata about the servlet, like its version or author. Engineering Express © _ Implementation: , a 3 init ___%|| The Servlet Container vie ntainer, al: ine, is an integré if hat_provic yun tip nvironment for Servie components, In simple words, it_is.a system that manages Java ervie ymponents on top.of the Web server to handle the Web i | client requests. Services provided by the Serviet container; = |_Network Services: 5 I . h fi Ai ides. The s, : |_provides the network services over which the request-and response _| | are sent, Provides the service of decoding and encoding MIME-based |_messages. | Manage Sewlet containers, Manages the lifecycle of a Servlet. Resource management; Manages the static and dynamic resources, such as HTML files, Servlets, and JSP pages. Engineering Express © 4+ The Servlet Life Cycle The Servlet life cycle refers to the stages a servlet goes through, from ||_ its creation to its destruction, The entire life cycle of a Servlet is 0, ervlet_contail ich uses the fe servlet Servlet interface to understand the Servlet object and manage it. Engineering Express The first stage involves loading and initializing the Servlet by th ____|| Servlet_container. _ yo ___2|| The container perfon i ring this I —__||_-- Loading CGR Cece :_Instantiation: Creates an_instance of the Servlet using the no- argument constructor o|| The container may load the servlet either: _ + During context initialization (configured with a zero or Weiive fie S »-Onademand when the_Web container Za Servlet _ ol init() service) Engineering Express © fe Eiseinea te ica eealaieoa The initO_method runs only once, immediately after instantiation. This_mé is initialize re h re hi let fail i le wntail hrowin, Servi ‘ion lable Exception, o|| After initialieation, the servlet _is ready to handle client requests. o|| The container performs the following steps for reque: ling: + Creates ServietRequest and ServletResponse objects Cor ____| HitpServietRequest and HttpServletResponse for HTTP requests). | |» Passes these objects to the service(SewletRequest, |___ServletResponse) method_to_process the request. |_. The service() method can throw ServletException, UnavailableException, or 1OException Destroys s | 5 é 3 5 ; invoking the destroy. method. | Before destruction, all threads handling the service) method are __| Bt a cee \Once destroyed, the servlet instance is released. Engineering Express © The Servlet interface provides three main methods to control its life Leycle: Life cycle methods of a Servlet service() handles multiple client Called only ‘once Called only once requests and send sends response Called by the container to initialize the servlet instance. 2 Runs only once during the senvlet’s lifetime. a_Typically used for tasks like setting up database connections connected architecture). | Prototype: public void initServletConfig con) throws ServietException £ Initialization code Engineering Express © la for initialization? ee \service() Method + Handles client requests and generates responses. - Uses Servi ie rvie n send _responses. Prototype: _ public void service(ServietRequest req, ServietResponse res) __| L throws ServietException, |OException |______// Request handling code 3 Engineering Express © fa Dak s, fe C destroy) method. Proper resource management and initialization ave tial sure HTTP Requests are the message sent by the client to request the data from /er_or form some action: LDifieyeriee il pareghest Dare _—"_\ ~. 77, VR |GET: GET request is used to read/retrieve data froma web server. | |GET retums an HTTP status code of 200 COK)if the data i successfully retrieved fram the server. | POST: POST request is used to send data (file, form-data, etc.) to | : ji rd». _ a replaces the entire content at a particular location with data that is \passed in the body payload. If there are no resources that match the _| ineicveits iwi) pererabe gma: PATCH: PATCH is similar to PUT request, but the only difference is, || it_modifies a part of the data. It will only replace the content that jou want to update, DELETE: A DELETE request is used to delete the data on the server || at_a specified location. Engineering Express © =& Handling HTTP get Requests re Tre it_return: IZ ong with an HTTP. status code (usually 200 OK). In rv hi fe ride_the Gi method. This method gets called when the client sends a GET request ||_ to the server, Inside this method, you can specity the logic to retrieve || neces: te Et the_clicnt. Example: i Moe ier import javax.servlet.http.*; public class GetExampleServlet extends HttpSeriet £ = | meer dire Aisle Seva te : HttpServietResponse response) throws ServletException, ____| 10Exception £ response,setContentTypeC text/html"); Printhriter out = responsegetWriterO; | String name = request.getParameterC'name'); // | |____Retrieving parameter from URL Cd out.printinC' "); out.printInC'Hello, " + name + "!"); out printInC' "); 3 2 Engineering Express © here is in the UR I vie lle Pe rr Pe This_me dhe i lieni ically invol sing the it yr ‘ing it_in database. | Example: |____ import java.io. JOException, import javax.serviet.”> PrintWriter out = response.getWriter); a ess Ci ”), String password = request.getParameterC password’); | "); out.printInC'Welcome, " + username + "!"); out.printInC'

Your password is: " + password + "

"), out printInC'"); 3 2 Engineering Express © 4 Redirecting R 0 R hieve this usin, ndRedire hod in the i This wary vedi) re he i re h ified I | Syntax response.s firect CURL" Example: é aA \\ |HTML (Index.html):

You might also like