Ajax implementation in Struts 2 without jQuery plugin
AJAX is a technique for creating better, faster, and more interactive web applications. With AJAX, your JavaScript can communicate directly with the server, using the JavaScript XMLHttpRequest object. With this object, your JavaScript can transfer data with a web server, without reloading the page.
This post elaborates on how to implement Ajax in Struts 2 application.
** UPDATE: Struts 2 Complete tutorial now available here.
Action class
package com.simplecode.action; import java.io.ByteArrayInputStream; import java.io.InputStream; import com.opensymphony.xwork2.Action; public class AjaxAction implements Action { private String userName; private InputStream inputStream; public String ajaxMethod() { System.out.println("ajaxMethod() is called"); byte[] bArray; if(!userName.isEmpty()) { bArray = ("Welcome " + userName).getBytes(); inputStream = new ByteArrayInputStream(bArray); } else { bArray = ("User name cant be blank").getBytes(); inputStream = new ByteArrayInputStream(bArray); } return SUCCESS; } public String execute() { return SUCCESS; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public InputStream getInputStream() { return inputStream; } }
Recommended reading:
Jsp Pages
<%@taglib prefix="s" uri="/struts-tags"%>Ajax implementation in Struts 2 Ajax implementation in Struts2
Please Enter your Name :
Also read:
- Integrating jQuery DataTable with Struts2 using Ajax to implement Gridview
- CRUD Operations in Struts 2 using jTable jQuery plugin via Ajax
- Autocomplete in Struts 2 using Jquery and JSON
Struts.xml
/ajax.jsp text/html inputStream
Demo
On running the application
Now giving the input as Jamil, the following output is obtained
Here the struts 2 action is called onBlur() event automatically , and hence the above response is obtained in the webpage without refreshing the page.
Hi Mohaideen Jamil,
Please help me to Configure Struts2 Application,I am new to this framework,I tried lot of times,it showing resource not available error Please Help me ASAP
This page rocks. thanks