Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I return plain text for an AJAX query?

I'm basing my knowledge on how to do this on this Crunchify tutorial.

I have a single page application.

It has two functions. It needs to either send a request to the HTTP servlet, which will go call its own java, and from which it will recieve a JSON string containing any errors/advising the servlet what to do next.

The other function is that it prompts a save file dialog from the servlet.

The question is - how can I structure my servlet such that it returns a plain text HTTP response for the AJAX query to examine.

I have a very round about way of doing this, and I'd like a suggestion for how to achieve the same thing in a simpler manner.

web.xml

   <servlet>
        <servlet-name>MyServlet</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>MyServlet</servlet-name>
        <url-pattern>/submitQuery</url-pattern>     
          <url-pattern>/saveFile
    </servlet-mapping>

MyServlet-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <context:component-scan base-package="world.hello.myservlets" />

    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

MyServlet.java

package world.hello.myservlets;

@Controller
public class MyServlet{


    @RequestMapping("/submitQuery")
    public ModelAndView submitQuery()
    {       

        return new ModelAndView("text", "model", "hello world");
    }

}

/WEB-INF/jsp/text.jsp

{model}

index.html

<html>
<head>
<script>
function myAjax()
{
         xmlhttp.onreadystatechange=function()
          {
          if (xmlhttp.readyState==4 && xmlhttp.status==200)
            {
                alert(xmlhttp.responseText)
                /*do something with the http response*/
            }     

          }


     xmlhttp=new XMLHttpRequest();
     xmlhttp.open("GET", "submitQuery", true);
     xml.send();
}
</script>
</head>
<body>
    <button onclick="myAjax()">Click me</button>
</body>
</html>

My understanding is the way this works is when the /submitQuery URI is sent, it's mapped to the MyServlet servlet. The servlet then returns a ModelAndView of ViewName = text, ModelName = model.

The dispatcher then redirects to /jsp/text.jsp (the specified view), displays the model on it. That final rendered output is returned to the AJAX object which can then access it how it wants.

Is there a more straight forward way of doing this?

like image 462
dwjohnston Avatar asked Dec 02 '22 17:12

dwjohnston


1 Answers

Yes there is more straight way for doing this.

As per crunchify tutorial you are returning the ModelAndView object. So that's the reason you are getting model object on text.jsp

ModelAndView: It returning both model and view information from a controller. Holder for both Model and View in the web MVC framework. Note that these are entirely distinct. This class merely holds both to make it possible for a controller to return both model and view in a single return value.

More about ModelAndView

Now come to the other way in which you need to return plain text.

Annotate your submitQuery() method in controller with @ResponseBody annotation:

@RequestMapping(value="/submitQuery")
@ResponseBody
public String submitQuery() {
    return "Response";
}

The @ResponseBody can be put on a method and indicates that the return type should be written straight to the HTTP response body (and not placed in a Model, or interpreted as a view name)

Access the parameter in javascript.

function myAjax()
{
    xmlhttp=new XMLHttpRequest();
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            alert(xmlhttp.responseText);
            console.log(xmlhttp.responseText);
        }
    }
    xmlhttp.open("GET", "submitQuery", true);
    xmlhttp.send();
}
like image 105
Harshal Patil Avatar answered Dec 10 '22 23:12

Harshal Patil