ViewResolver(我的jsp位于前缀值指定的右侧文件夹中):
<!-- Resolves views selected for rendering by @Controllers -->
<!-- to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
Servlet映射:
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>*.fst</url-pattern>
</servlet-mapping>
控制器:
@Controller
public class HomeController {
private static final Logger logger =
LoggerFactory.getLogger(HomeController.class);
@RequestMapping("/home")
public ModelAndView home(String user, HttpServletRequest request) {
logger.info("Home controller has been executed");
ModelAndView mv = new ModelAndView();
mv.addObject("userName", user);
mv.addObject("controllerName", request.getRequestURI());
mv.setViewName("home");
return mv;
}
@RequestMapping(value = "/testAjax", method = RequestMethod.POST)
public String testAjax(@RequestParam("memberId") String id,
HttpServletRequest request, HttpServletResponse response,
Locale locale, Model model) {
logger.info("Text Ajax action has been executed. My Parameter is " + id);
return id;
}
}
在STS IDE上启用Tomcat 8服务器后,使用此URL http://localhost:8080/home.fst
访问此网站即可。
但是在页面上,像下面这样调用AJAX会引发404
错误:
$.ajax({
type: "POST",
url: "/testAjax.fst",
data: {"memberId" : "test"},
success: function (result) {
console.log(result)
}
});
这是控制台错误日志:
POST http://localhost:8080/testAjax.fst 404 (Not Found)
k.cors.a.crossDomain.send jquery-2.1.3.min.js:4
n.extend.ajaxhome.fst:11 (anonymous function) jquery-2.1.3.min.js:3
n.event.dispatch jquery-2.1.3.min.js:3
r.handle
奇怪的是它调用testAjax
控制器就好了,服务器上没有错误日志。
logger.info("Text Ajax action has been executed. My Parameter is " + id);
当我的AJAX调用textAjax
动作时,也会打印日志。我也用调试点检查了它(它坏了)。
似乎是什么问题??
答案 0 :(得分:8)
一切都很好只需在您的方法中添加@ResponseBody
注释,我建议您将请求方法POST
更改为GET
<强>弹簧强>
@RequestMapping(value = "/testAjax", method = RequestMethod.GET) //Made Change
@ResponseBody //added
public String testAjax(@RequestParam("memberId") String id, HttpServletRequest request, HttpServletResponse response, Locale locale, Model model) {
logger.info("Text Ajax action has been executed. My Parameter is " + id);
return id;
}
<强> JQuery的强>
$.ajax({
type: "GET", //Made Change
url:"/testAjax.fst",
data: {"memberId" : "test"},
success: function (result) {
console.log(result)
}
});