Feedback Form

Fetch API & XMLHttpRequest: Client-Side Code to Call Servlets

Fetch API & XMLHttpRequest: Client-Side Code to Call Servlets

जब भी हम Java Servlet के साथ web development करते हैं, तो client और server के बीच communication बहुत ज़रूरी होता है। आज के modern web applications में ये communication asynchronous तरीके से होता है — यानी page reload किए बिना data भेजना और लाना। इसके लिए दो popular methods हैं — Fetch API और XMLHttpRequest (XHR)

इस blog में हम step-by-step समझेंगे कि कैसे client-side से servlet को call किया जाता है, data भेजा जाता है और response receive किया जाता है, दोनों methods — Fetch API और XMLHttpRequest — के साथ।

What is Client-Side to Servlet Call?

Client-side to servlet call का मतलब होता है कि browser (HTML, JS) से Java servlet को request भेजना। Servlet server पर run होती है और response वापस browser को भेजती है।

उदाहरण के लिए, अगर आप किसी form में user data भरते हो और उसे server को भेजना चाहते हो, तो आप Fetch API या XMLHttpRequest का use कर सकते हो ताकि servlet को वो data मिले और वो उसे process करे।

Why We Need Fetch API and XMLHttpRequest?

दोनों methods का main purpose है — client (browser) और server (servlet) के बीच asynchronous communication establish करना। यानी बिना page reload किए data भेजना या लाना।

  • Fetch API – Modern method है, जो promises पर based है।
  • XMLHttpRequest – पुराना लेकिन reliable method है, जिसे AJAX (Asynchronous JavaScript and XML) भी कहा जाता है।

इन दोनों के through आप form data भेज सकते हो, server से JSON data fetch कर सकते हो, या किसी database result को dynamically web page पर दिखा सकते हो।

Understanding the Servlet Endpoint

Servlet एक Java class होती है जो HTTP request handle करती है। जब आप client से request भेजते हैं, तो servlet उस request को process करके response देती है।

Servlet को generally web.xml file या @WebServlet annotation के ज़रिए map किया जाता है। उदाहरण:

@WebServlet("/fetchData") public class FetchDataServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { String name = request.getParameter("name"); response.setContentType("application/json"); response.getWriter().write("{\"message\": \"Hello, " + name + "\"}"); } }

अब चलिए देखते हैं कि इस servlet को client-side से कैसे call किया जा सकता है।

Method 1: Using Fetch API

Fetch API सबसे modern और readable तरीका है servlet को call करने का। यह promises पर based है और asynchronous operation को handle करने के लिए बहुत आसान है।

Basic Syntax of Fetch API

fetch('servletURL', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: 'key=value' }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error(error));

Example: Sending Data to Servlet using Fetch API

मान लीजिए हमारे पास एक simple form है जो user का name input लेता है और उसे servlet को भेजता है।

Send Data to Servlet using Fetch API

ऊपर दिए गए example में, data servlet तक POST method से भेजा जा रहा है और servlet JSON response वापस भेज रही है।

Advantages of Fetch API

  • Syntax simple और readable है।
  • Promises और async/await support करता है।
  • Modern browsers में fully supported है।

Method 2: Using XMLHttpRequest (AJAX)

XMLHttpRequest पुराना लेकिन बहुत ही popular तरीका है servlet को call करने का। इसे AJAX call भी कहा जाता है।

Basic Syntax of XMLHttpRequest

var xhr = new XMLHttpRequest(); xhr.open("POST", "servletURL", true); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.onload = function() { if (xhr.status === 200) { console.log(xhr.responseText); } }; xhr.send("key=value");

Example: Calling Servlet using XMLHttpRequest

Send Data to Servlet using XMLHttpRequest

Advantages of XMLHttpRequest

  • सभी पुराने browsers में भी supported है।
  • Request का control manually रखा जा सकता है।
  • Response handling flexible होती है।

Difference Between Fetch API and XMLHttpRequest

Feature Fetch API XMLHttpRequest
Syntax Simple and Promise-based Callback-based (complex)
Asynchronous Handling Supports async/await Manual state change handling
Browser Support Modern browsers All browsers including old ones
Streaming Supported Not supported
Response Type JSON, text, blob, etc. Manual parsing required

When to Use Which?

  • Fetch API का use तब करो जब modern browsers target करने हो और clean code चाहिए।
  • XMLHttpRequest तब use करो जब compatibility important हो या पुराने browsers को support करना पड़े।

Real-Life Use Case

मान लो आपको किसी student portal पर “Check Result” feature बनाना है — जहाँ student roll number डालता है और result दिखता है।

ऐसे case में आप Fetch API से servlet को roll number भेज सकते हो, servlet database से result fetch करके JSON में भेजेगा, और JS उस result को page पर दिखा देगा।

fetch("checkResult", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: "rollNo=" + encodeURIComponent(rollNo) }) .then(res => res.json()) .then(data => document.getElementById("result").innerText = data.grade);

Key Takeaways

  • Servlet को call करने के लिए client-side पर Fetch API या XMLHttpRequest दोनों use किए जा सकते हैं।
  • Fetch API modern, cleaner और readable है।
  • XMLHttpRequest पुराने browsers के लिए useful है।
  • POST method से data सुरक्षित तरीके से भेजा जाता है।
  • Always proper Content-Type header सेट करें।
  • Response को JSON में handle करना सबसे आसान तरीका है।

Notes for Exam

  • Fetch API → Promise-based modern JS method for server communication।
  • XMLHttpRequest → Classic method used in AJAX calls।
  • दोनों का use servlet से data भेजने और पाने में किया जाता है।
  • Servlet Mapping हमेशा सही होना चाहिए (जैसे: @WebServlet("/fetchData"))।
  • POST और GET दोनों methods को handle करने के लिए doPost() या doGet() methods का use करें।
  • Response को JSON format में भेजना modern practice है।
  • Exam में syntax और flow diagram दोनों पूछे जा सकते हैं।
  • Always include content-type header for clarity।
  • Fetch API modern JavaScript का हिस्सा है जबकि XHR older AJAX concept है।