【发布时间】:2015-06-05 09:12:54
【问题描述】:
我的知识基于如何做到这一点on this Crunchify tutorial。
我有一个单页应用程序。
它有两个功能。它需要向 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 返回 ModelAndView 或 ViewName = text, ModelName = model。
然后调度程序重定向到 /jsp/text.jsp(指定的视图),在其上显示模型。最终呈现的输出将返回给 AJAX 对象,然后该对象可以按需要访问它。
有没有更直接的方法来做到这一点?
【问题讨论】:
标签: ajax spring spring-mvc servlets single-page-application