0

Appreciate if someone could assist me on this. i have a servlet coded already (Its a http url). I would need to access the servlet in JSP to get the data using ajax. can someone tel me how to obtain this?

url link below is given for sample.

$.ajax({
                type: 'GET',
                data : {  },
                success: function(data) {
                    console.log(data);     
                     });
  • Please post your code here. – Jiahao Cai May 28 '17 at 02:36
  • Hi... I dont have much coding experience in ajax.... thats why requested for any assistance...I am not sure what goes in data :{} param and how to retrieve data from the http url ..... ur suggestion would be appreciated.. let me know if you need more details... – user7896515 May 28 '17 at 02:52
  • I'll work up an answer but you need to provide a few more parts so we can see what you are trying to do. Please add the following: 1) testconnection.jsp, 2) the class that test connection.jsp binds to ( markup), 3) web.xml, and 4) the error that you are getting. – Threadid May 28 '17 at 03:46
  • Thanks for that @Threadid... I have described the details in below link https://gist.github.com/theakathir/f6fb390d35b451a57958aa0d3cf05330 Please see if tat info helps or let me know if you need more details. – user7896515 May 29 '17 at 22:22
  • Hi... Any input/suggestion how to call this HTTP servlet in jsp using AJAX? your input would really helpThanks – user7896515 May 31 '17 at 04:01

2 Answers2

1

Here is little information about ajax and how to use it.

Here is sample ajax request code with json file ,

$.ajax({
            url : 'your_servlet_url',
            type : 'POST',
            dataType : 'json',// 
            data : {
                var yourVariable : jsonData // jsonData is jsonFormated data
            },
            contentType : 'application/json',
            complete : function(response) {
                 console.log(response);  
                }

            }
        });

In servlet , get json data like

JSONObject jObj = new JSONObject(request.getParameter("yourVariable"));
String myIndividualData = jObj.get("myIndividualDataFromJsp").toString().trim();

And you can retrieve the json data like this.

ObjectMapper mapper = new ObjectMapper();
String jsonString = mapper.writeValueAsString(dataYouWantToSend);
resp.getWriter().write(jsonString);

what goes in data :{} is the data you want to send to the servlet. This is how you can work ajax with json, there could be many different ways, since you don't specify which data time and don't forget to add the json jar, Here is the link.

parlad
  • 1,143
  • 4
  • 23
  • 42
  • My data is not Json format....Thanks.. I have described the details in below link gist.github.com/theakathir/f6fb390d35b451a57958aa0d3cf05330 ..can you please tel me how i can get the data from this URL which is already built.... Thanks – user7896515 May 30 '17 at 14:44
  • ok , i am also learner here , how do you suppose to collect the data to pass it in ajax request? – parlad May 30 '17 at 15:12
  • is this what you want? , https://madushankaperera.wordpress.com/2013/03/12/submitting-jsp-form-data-to-servlet-with-jquery-ajax/ – parlad May 30 '17 at 15:15
  • Yes exactly..but here ma input would be inbuilt servlet(http url) which i gave... I am not sure what i have to give in Ajax as data/urL to access the http url. – user7896515 May 30 '17 at 15:21
  • put your servlet url in form action or replcae the url of ajat with your servlet will do , i recomend you to leave the form action empty and put your servlet url in url of ajax. – parlad May 30 '17 at 15:25
0

Parlad highlights an important common practice in AJAX design is that XML has been replaced by JSON (therefore do we now implement AJAJ?).

But for your question you probably need to focus a little higher. If this is truly an AJAX request then you probably don't wan't to implement the service as a JSP. JSP is a templated frame work for dynamic web pages. Even though for a simple hello world connection test it is easy to write a scriptlet to return static content.

Rather your best implementation is true servlet.

Spend some time reading here:

Here is a sample servlet that is useful for understanding how to process the request.

package com.reallysimpleservice.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.Map;
import java.util.concurrent.*;

import javax.naming.Context;
import javax.naming.InitialContext; 
import javax.naming.NamingException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class servAjax
*/
//@WebServlet(name = "ServAjax", urlPatterns = { "/write/*", "/read/*" })
public class SimplyServed extends HttpServlet {
private ServletContext servContext;
private ServletConfig config;

/**
 * @see HttpServlet#HttpServlet()
 */
public SimplyServed() {
    super();
}

public void init()  throws ServletException
{
}

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

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

response.setContentType("text/html; charset=UTF-8");
response.setCharacterEncoding("UTF-8");
PrintWriter responseOut = response.getWriter();

System.out.println("SimplyServed");

this.servContext = this.getServletContext();

 System.out.println("<Begin>");

 System.out.println("request.getParameter(\"whom\") = "+request.getParameter("whom")+"<br>");        

 System.out.println("servContext.getInitParameter(\"jdbcURL\") = "+servContext.getInitParameter("jdbcURL")+"<br>");
 System.out.println("servContext.getInitParameter(\"dataService\") = "+servContext.getInitParameter("dataService")+"<br>");
 System.out.println("request.getAttributeNames().hasMoreElements() = "+request.getAttributeNames().hasMoreElements()+"<br>");
 if(request.getAttributeNames().hasMoreElements()) {
     System.out.println("request.getAttributeNames().nextElement() = "+request.getAttributeNames().nextElement()+"<br>");
 }
 System.out.println("request.getHeaderNames().hasMoreElements() = "+request.getHeaderNames().hasMoreElements()+"<br>");
 Enumeration<String> hnames = request.getHeaderNames();
 String hname = "";
 while(hnames.hasMoreElements()) {
        hname = (String) hnames.nextElement();
        System.out.println("request.getHeaderNames().nextElement() = "+hname+"<br>");
        System.out.println("request.getHeader("+hname+") = "+request.getHeader(hname)+"<br>");
 }   
 System.out.println("request.getAuthType() = "+request.getAuthType()+"<br>");
 System.out.println("request.getCharacterEncoding() = "+request.getCharacterEncoding()+"<br>");
 System.out.println("request.getContentLength() = "+request.getContentLength()+"<br>");
 System.out.println("request.getContentType() = "+request.getContentType()+"<br>");
 System.out.println("request.getContextPath() = "+request.getContextPath()+"<br>");
 System.out.println("request.getRequestedSessionId() = "+request.getRequestedSessionId()+"<br>");
 System.out.println("request.getRequestURI() = "+request.getRequestURI()+"<br>");
 System.out.println("request.getLocalAddr() = "+request.getLocalAddr()+"<br>");
 System.out.println("request.getLocalName() = "+request.getLocalName()+"<br>");
 System.out.println("request.getLocalPort() = "+request.getLocalPort()+"<br>");
 System.out.println("request.getMethod() = "+request.getMethod()+"<br>");
 try {
    System.out.println("request.getPart() = "+request.getPart("mime-type")+"<br>");
} catch (IllegalStateException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} catch (ServletException e) {
    e.printStackTrace();
}
 System.out.println("request.getPathTranslated() = "+request.getPathTranslated()+"<br>");
 System.out.println("request.getPathInfo() = "+request.getPathInfo() +"<br>");
 System.out.println("request.getProtocol() = "+request.getProtocol()+"<br>");
 System.out.println("request.getQueryString() = "+request.getQueryString()+"<br>");
 System.out.println("request.getRequestedSessionId() = "+request.getRequestedSessionId()+"<br>");
 System.out.println("request.getServletPath() = "+request.getServletPath()+"<br>");
 System.out.println("request.isRequestedSessionIdFromCookie() = "+request.isRequestedSessionIdFromCookie()+"<br>");
 System.out.println("request.isRequestedSessionIdFromURL() = "+request.isRequestedSessionIdFromURL()+"<br>");
 System.out.println("request.isRequestedSessionIdValid() = "+request.isRequestedSessionIdValid()+"<br>");
 System.out.println("request.isSecure() = "+request.isSecure()+"<br>");
 System.out.println("request.getSession() = "+request.getSession()+"<br>");
 System.out.println("request.getUserPrincipal() = "+request.getUserPrincipal()+"<br>");
 System.out.println("request.isAsyncStarted() = "+request.isAsyncStarted()+"<br>");
 System.out.println("request.isAsyncSupported() = "+request.isAsyncSupported()+"<br>");
 System.out.println("</End>");


String resourceServlet = "";
String resourcePath = "";
String whom="";

resourceServlet = request.getServletPath();
resourcePath = request.getPathInfo();
whom=request.getParameter("whom");

responseOut.print("Hello "+whom);

   }

}

And the Java Script to call it. Uses a global event handler - so alternative example for processing the response.

<script type="text/javascript" src="ScriptLibrary/jquery-1.10.2.js"></script>
<script type="text/javascript" src="ScriptLibrary/jquery.json-2.4.min.js"></script>

<script>
var objCounter;

function ajaxReq(ajaxQuery, mimeType, serv, path){
  // confirm("ajaxQuery"+ajaxQuery);
  // confirm("mimeType"+mimeType);
  // confirm("serv"+serv);
  //  confirm("path"+path);
var slash = "/";
if (typeof serv == "undefined"){serv="";path="";slash="";}
if (typeof path == "undefined"){path="";slash="";}
if (serv == ""){path="";slash="";}
if (path == ""){slash="";}
var ajaxHREF = serv+slash+path;

$.ajax({
    url: ajaxHREF,
    type: "post",
    data: ajaxQuery,         
    beforeSend: function ( xhr ) {
        xhr.overrideMimeType(mimeType);
        },
    success: function(response, textStatus, jqXHR){ 
        },         
    error: function(jqXHR, textStatus, errorThrown){             
        console.log("JSQL ajax error: " + textStatus + ", " + errorThrown);
        console.log(jqXHR.responseText);
        }, 
    complete: function(){
        }
    });     
}


function getGreeting() {
    //var mimeType = "application/xml";
      //var mimeType = "text/html";
    //var mimeType = "application/json";
    //var mimeType = "image/svg+xml";
      var ajaxQuery =  'whom='+$('#helloWhom').find('.whom').val();
  ajaxReq(ajaxQuery, mimeType, 'simply', 'served');
}

$(document).ajaxSuccess(function(event, xhr, settings) {
if (typeof settings.data == 'undefined') {return false;}
if (typeof settings.mimeType == 'undefined') {return false;}
    var query = settings.data;
    var mimeType = settings.mimeType;
    if (query.match(/whom/)){
        if(mimeType.match(/application\/xml/)){
        }
        if(mimeType.match(/text\/html/)){
            $('#divGreeting').text(xhr.responseText);
            }
        if(mimeType.match(/application\/json/)){
            }
        if(mimeType.match(/image\/svg\+xml/)){
            }
    }
});
</script>
Threadid
  • 730
  • 1
  • 7
  • 27