我基於我的知識如何做到這一點on this Crunchify tutorial。如何爲AJAX查詢返回純文本?
我有一個單頁的應用程序。
它有兩個功能。它需要向HTTP servlet發送一個請求,該servlet將調用它自己的java,並從中接收包含任何錯誤的JSON字符串/建議servlet接下來要做什麼。
另一個功能是它提示servlet的保存文件對話框。
問題是 - 我如何構造我的servlet,使其返回一個純文本HTTP響應,以供AJAX查詢檢查。
我對此做了一個非常全面的討論,並且希望能夠以更簡單的方式達到同樣目的。
的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>
我的理解是這樣的工作原理是當發送/submitQuery
URI,它映射到的方式MyServlet
servlet。然後servlet返回ViewName = text, ModelName = model
的ModelAndView
。
然後調度程序重定向到/jsp/text.jsp(指定的視圖),在其上顯示模型。最終呈現的輸出返回到AJAX對象,然後可以訪問它的方式。
有沒有更直接的方法來做到這一點?
有關servlet名稱的確定好處,而應該稱爲「MyServletController」。 – dwjohnston 2015-04-08 03:46:27