我正在使用Spring 2.5,并使用Ajax.updater(1.7)从Spring中的请求映射中获取响应。
在请求映射中,我返回一个ModelAndView,它引用带有一些文本的jsp。但问题是当ajax收到响应并更新容器时,整个页面被包装在容器中而不是jsp输出中,为什么会这样呢
答案 0 :(得分:0)
好的,这就是我在Spring 2.5中使用ajax的方法
首先,您需要控制器来响应ajax调用
public class AjaxController extends MultiActionController {
// injected services, daos here
public ModelAndView getAjaxData(HttpServletRequest request, HttpServletResponse response) throws Exception {
String data = // construct your ajax response here - string, json, xml etc
model.put("data", data);
return new ModelAndView("ajax_foo", model);
}
public ModelAndView anotherMethod(HttpServletRequest request, HttpServletResponse response) throws Exception {
String data = // construct your ajax response here - string, json, xml etc
model.put("data", data);
return new ModelAndView("ajax_foo", model);
}
}
然后你需要ajaxView将ajax数据写入响应
public class AjaxView extends AbstractView {
@Override
protected void renderMergedOutputModel(Map map, HttpServletRequest request, HttpServletResponse response) throws Exception {
String ajaxResponse = map.get("data");
response.setContentType("text/plain; charset=UTF-8");
response.getOutputStream().write(ajaxResponse.getBytes());
}
查看解析程序以解析ajax调用
public class AjaxViewResolver extends AbstractCachingViewResolver {
private String ajaxPrefix;
private View ajaxView;
@Override
protected View loadView(String viewName, Locale locale) throws Exception {
View view = null;
if (viewName.startsWith(this.ajaxPrefix)) {
view = ajaxView;
} else {
}
return view;
}
public void setAjaxPrefix(String ajaxPrefix) {
this.ajaxPrefix = ajaxPrefix;
}
public void setAjaxView(View ajaxView) {
this.ajaxView = ajaxView;
}
}
网址映射,将ajax网址映射到ajax控制器
<bean id="simpleUrlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/getAjaxData.htm">ajaxController</prop>
<prop key="/anotherMethod.htm">ajaxController</prop>
</props>
</property>
</bean>
Controller有bean ajaxResolver作为methodNameResolver,控制器有一些服务或daos例如
<bean name="ajaxController" class="my.test.web.ajax.AjaxController">
<property name="service" ref="service"/>
<property name="dao" ref="dao"/>
<property name="methodNameResolver" ref="ajaxResolver"/>
</bean>
方法名称解析器
<bean id="ajaxResolver"
class="org.springframework.web.servlet.mvc.multiaction.PropertiesMethodNameResolver">
<property name="mappings">
<props>
<prop key="/getAjaxData.htm">getAjaxData</prop>
<prop key="/anotherMethod.htm">anotherMethod</prop>
</props>
</property>
</bean>
Ajax View解析器在从AjaxController返回modelAndView时调用ajax视图
<bean id="ajaxViewResolver" class="my.test.web.ajax.AjaxViewResolver">
<property name="ajaxView">
<bean class="my.test.web.ajax.AjaxView"/>
</property>
<property name="ajaxPrefix" value="ajax_"/>
</bean>