JAVA and AJAX

How to use Ajax with Java ? Bellow I show you how to do this.

Will create New Project on Eclipse Enterprise Edition. File-> New-> Dynamic Web Project.
Them add Java Servlet Class with specified code:


import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class Myservlet
 */
@WebServlet("/Myservlet")
public class Myservlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Myservlet() 
    {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		
		String automobile = request.getParameter("car").trim();
		if(automobile == null || "".equals(automobile)){
			automobile = "ZAPOROJEC";
		}
		
		String auto = "Mark: " + automobile;
		
		response.setContentType("text/plain");
		response.getWriter().write(auto);
	
	
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		
		
		String namer = request.getParameter("name").trim();
		
		if(namer == null || "".equals(namer))
		{
			namer = "Mr X";
		}
		
		String nameYour = "Post response from servlet  " + namer;		
		response.setContentType("text/plain");
		response.getWriter().write(nameYour);
		
	}

}

Next step will create JS folder in WebContent folder and create Javascript-file named ajaxer.js

 
   
   $(document).ready(function() {
		$('#name').blur(function() {
			$.ajax({
				url : 'Myservlet',
				type: 'POST',
				data : {
					name : $('#name').val()
				},
				success : function(responseText) {
					$('#ajaxPostNameServletResponse').text(responseText);
				}
			});
		});
	});
   
    
    $(document).ready(function () {
        $("#selector").change(function () {
            $.ajax({
                url: 'Myservlet',
                type: 'GET',
                data: {car: $("#selector").val()},
                success: function(responseText) {
    				$('#ajaxGetCarServletResponse').text(responseText);
    			                                   },
                error:function(){alert('error');}
            });
        });
    });
    

And Last Part of program is creating JSP (html) file – index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>

<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%20src%3D%22http%3A%2F%2Fcode.jquery.com%2Fjquery-1.7.2.js%22%3E%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="&lt;script&gt;" title="&lt;script&gt;" />
<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%20src%3D%22js%2Fajaxer.js%22%20type%3D%22text%2Fjavascript%22%3E%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="&lt;script&gt;" title="&lt;script&gt;" />
</head>
<body>

<label for="bar">A bar</label>
<input id="name" name="bar" type="text" value="" />
<input id="btnSend" type="button" value="Send" />


 <select id="selector">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select> 


 You choose car :   


<div id="ajaxGetCarServletResponse"></div>


 


 You type this :   


<div id="ajaxPostNameServletResponse"></div>




</body>
</html>

At this point your project is looking like on the picture:
Ajax Project

 

 

 

 

 

 

 

 

 

 

 

I hope, you installed Apache Tomcat Server. Try to start web-server –> RUN–>Run AS–>Run as Server