How to Integrate Struts and Ajax Tutorial |Video upload date:  · Duration: PT13M34S  · Language: EN

Learn how to integrate Struts and Ajax to add asynchronous calls in Java web apps for faster partial updates and clean JSON responses.

If you want your Struts based web app to stop feeling like a slow motion slideshow welcome to the world of Ajax. This guide shows how to wire up Struts actions to asynchronous calls from a JSP so only the bits of the page that matter get updated. No full page reloads no drama and yes you will still love logs when things break.

Quick overview of the flow

Here is the basic pipeline so you do not get lost in the weeds

  • Client sends an async request from a JSP using fetch or a library like jQuery
  • Struts action receives parameters and delegates work to a service layer
  • Action returns JSON or a stream response so the client can parse it
  • Client updates the DOM fragment that actually cares about new data

Step 1 Setup project and dependencies

Use Struts 2 rather than ancient versions unless you enjoy hand crafting XML for fun. Add the Struts core libraries and the json plugin via Maven or by dropping jars. Make sure your web.xml has the Struts filter configured so requests will reach the framework.

What to include

  • struts2 core and interceptor libraries
  • struts2 json plugin for automatic JSON results when you want them
  • Either jQuery for convenience or rely on the browser fetch API for minimal baggage

Step 2 Choose your client side approach

If you want something tiny and modern use fetch. If you want shortcuts and less typing use jQuery. Both work fine. Use a helper function if you have many forms or repeating logic. Keep payloads focused so you do not send the kitchen sink every time.

// example using fetch with JSON response
fetch('/app/ajaxAction' , {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ id: 42 })
})
.then(response => response.json())
.then(data => {
  document.querySelector('#result').textContent = data.message
})
.catch(err => console.error('Ajax error' , err))

Step 3 Create Struts action and service layer

Make an Action class that reads params from the request or uses setters that Struts will populate. Delegate business logic to a service class rather than stuffing everything into the action. For JSON results the action can expose getters for fields that should be serialized by the json plugin.

Two ways to return data

  • Use the Struts json plugin and a result type of json so the framework serializes your action properties automatically
  • Or write directly to the HttpServletResponse stream when you need full control over the payload format

Step 4 Configure action mapping in struts.xml

Map a friendly name to your action class and set the result type to json when you want automatic serialization. That keeps your controller clean and your client happy.

<action name="ajaxAction" class="com.example.action.AjaxAction">
  <result type="json" />
</action>

Step 5 Build the JSP and update the DOM

Wire a button or form to trigger the Ajax call. Only replace the DOM fragment that changed. The browser will thank you with fewer repaints and your users will thank you with less rage clicks.

<button id="loadBtn">Load item</button>
<div id="result">Waiting for data</div>

<script>
document.getElementById('loadBtn').addEventListener('click' , function() {
  fetch('/app/ajaxAction' , { method: 'GET' })
    .then(r => r.json())
    .then(data => {
      document.getElementById('result').innerHTML = data.html || data.message
    })
    .catch(e => console.error('Fetch failed' , e))
})
</script>

Step 6 Test and debug the flow

Open the browser network panel and the console. Watch the request and the response payload. If you see a 404 check your action mapping. If you see a stack trace check server logs. If the client rejects JSON check the content type header and the actual payload shape.

Tips and pitfalls that will save you time

  • Keep payloads small and focused so parsing is fast
  • Validate inputs on the server because client side validation is just a polite suggestion
  • Use consistent content type values so the client knows what to expect
  • When debugging dump the response body to logs before more clever handling

There you go. You now have a maintenance friendly way to add async interactions to your Struts app. It will still break sometimes but at least it will do it faster.

I know how you can get Azure Certified, Google Cloud Certified and AWS Certified. It's a cool certification exam simulator site called certificationexams.pro. Check it out, and tell them Cameron sent ya!

This is a dedicated watch page for a single video.