How do I use Servlet and Ajax?

Posted by kof20012 on Wed, 11 Mar 2020 11:15:17 +0100

I'm new to Web applications and servlets, and I have the following questions:

Whenever I print something in the Servlet and the web browser calls it, it returns a new page containing that text. Is there a way to print text on the current page using Ajax?

#1 building

I'll show you the entire example of a servlet and the way ajax calls are made.

Here, we will create a simple example to create a login form using a servlet.


   Name:<input type="text" name="username"/><br/><br/>  
   Password:<input type="password" name="userpass"/><br/><br/>  
   <input type="button" value="login"/>  

This is an ajax example

            type: "POST",           
            data: 'LoginServlet='+name+'&name='+type+'&pass='+password,
            url: url,

LoginServlet Servlet Code:-

    package abc.servlet;


public class AuthenticationServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
        doPost(request, response);

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {

        HttpSession session = request.getSession();
        String username = request.getParameter("name");
        String password = request.getParameter("pass");

                /// Your Code
out.println("sucess / failer")
        } catch (Exception ex) {
            // System.err.println("Initial SessionFactory creation failed.");

#2 building

type: "POST",
url: "url to hit on servelet",
data:   JSON.stringify(json),
dataType: "json",
success: function(response){
    // we have the response
    if(response.status == "SUCCESS"){
        $('#info').html("Info  has been added to the list successfully.<br>"+
        "The  Details are as follws : <br> Name : ");

        $('#info').html("Sorry, there is some thing wrong with the data provided.");
 error: function(e){
   alert('Error: ' + e);

#3 building

Ajax (also Ajax, the acronym for asynchronous JavaScript and XML) is a set of interrelated Web development technologies used by clients to create asynchronous Web applications. With Ajax, Web applications can send data to and retrieve data from the server asynchronously. Here is the sample code:

The Jsp page Java script function uses two variables firstName and lastName to submit the data to the servlet:

function onChangeSubmitCallWebServiceAJAX()
      var firstName=document.getElementById("firstName").value;
      var lastName=document.getElementById("lastName").value;"GET","/AJAXServletCallSample/AjaxServlet?firstName="


The Servlet reads the data sent back to the jsp in xml format (you can also use text. Just change the response content to text and render the data on the javascript function.)

 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    String firstName = request.getParameter("firstName");
    String lastName = request.getParameter("lastName");

    response.setHeader("Cache-Control", "no-cache");

#4 building

Use guide multiple selection


function() { $.ajax({
    type : "get",
    url : "OperatorController",
    data : "input=" + $('#province').val(),
    success : function(msg) {
    var arrayOfObjects = eval(msg); 
    // $('#output').append(obj);
    dataType : 'text'

In Servlet


#5 building

In general, you cannot update pages from servlet s. The client (browser) must request an update. The Eiter client loads the entire new page, or requests to update part of the existing page. This technology is called Ajax.

Topics: JSON xml Java Javascript