求教关于Spring MVC @ResponseBody 问题

hz890 2013-08-04 11:11:33
头一回使用Spring MVC的@ResponseBody注解,但是无法在前端得到响应。
不知是何原因。代码及配置如下:
前端VIEW: login.jsp
<%--
Created by IntelliJ IDEA.
User: BPM
Date: 2013/8/3
Time: 下午 2:10
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=utf-8" language="java" pageEncoding="utf-8" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript" src="${pageContext.request.contextPath}/scripts/jquery.js"></script>
<script type="text/javascript">
var jq = jQuery.noConflict();
jq(document).ready(function () {
jq("#btnLogin").click(function () {
jq.post("${pageContext.request.contextPath}/validateLogin.xhtml",
{
name: jq("#name").val(),
password: jq("#password").val()
},
function (data, status) {
if (data == "success") {
jq("#lblResult").text("Login Successfully!");
window.setTimeout("location.replace(\"${pageContext.request.contextPath}/index.xhtml\")", 3000);
}
else {
jq("#lblResult").text("Login Failed!");
}
}
);
return false;
}
);
}
);
</script>
<title>Login Page</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/validateLogin.xhtml" id="form1" name="form1" method="post">
Name:<input type="text" id="name" name="name"/><br/>
Password:<input type="password" id="password" name="password"/><br/>
<input type="submit" id="btnLogin" name="btnLogin" value="Login"/><span id="lblResult"></span>
</form>
</body>
</html>

后端控制器代码:
package springmvc.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
* Created with IntelliJ IDEA.
* User: BPM
* Date: 2013/6/27
* Time: 下午 8:16
* To change this template use File | Settings | File Templates.
*/

@Controller
public class WebAppController {

@RequestMapping(value = "/default.xhtml", method = RequestMethod.GET)
public ModelAndView redirectIndex() {
ModelAndView mv;
mv = new ModelAndView("login");
return mv;
}

@RequestMapping(value = "/validateLogin.xhtml", method = RequestMethod.POST)
@ResponseBody
public String validateLogin(@RequestParam String name, @RequestParam String password) {
String result = "";
if (name.equals("User") && password.equals("12345")) {
result = "success";
} else {
result = "failure";
}
return result;
}
}

web.xml配置:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<servlet>
<servlet-name>Dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Dispatcher</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>

<welcome-file-list>
<!--<welcome-file>jsp/index</welcome-file>-->
<welcome-file>default.xhtml</welcome-file>
</welcome-file-list>
</web-app>

Dispatcher-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"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

<context:component-scan base-package="springmvc.controller"/>
<context:annotation-config/>
<mvc:annotation-driven/>

<mvc:resources location="/" mapping="/resources/**"/>

<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>

<bean id="handlerAdapter" class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"
p:synchronizeOnSession="true"/>

<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource"
p:basename="i18n/messages"/>
</beans>
...全文
731 12 打赏 收藏 转发到动态 举报
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
hz890 2013-08-04
  • 打赏
  • 举报
回复
@ResponseBody注解对于方法的返回类型应该没有具体限制的 下面的网址给出的示例,是返回Boolean的 http://bbs.itqy8.com/topic/123
积木 2013-08-04
  • 打赏
  • 举报
回复
我不知道你是怎么理解这个 @ResponseBody 这个注解的使用时机的。 按照我的理解,@ResponseBody应该在 你打算将你的结果变换成 XML or JSON 的时候使用的。 因此 1. 你的前台 accept-content 应该设置成 XML 或者是JSON 2. 你的Controller的返回值应该是 对象Bean,而不是字符串。 字符串这种返回值方式用来做View名解析的时候最合适。
hz890 2013-08-04
  • 打赏
  • 举报
回复
请各位高手帮帮忙啦,多谢!
hz890 2013-08-04
  • 打赏
  • 举报
回复
不知是配置问题,还是缺少某些.jar文件?
hz890 2013-08-04
  • 打赏
  • 举报
回复
经过调试,控制器里的validateLogin方法可以响应执行,并返回结果。但是前端的js却未能获取,从而导致画面没有任何反应。 还有,如果采用下面的代码(print输出方式),则前端可以正常执行! ... @RequestMapping(value = "/validateLogin.xhtml", method = RequestMethod.POST) public void validateLogin(@RequestParam String name, @RequestParam String password, HttpServletResponse response) throws Exception { String result = ""; if (name.equals("User") && password.equals("12345")) { //result = "redirect:/index.xhtml"; //response.sendRedirect("index.xhtml"); result = "success"; } else { //result = "redirect:/jsp/login.jsp"; //result = "login"; result = "failure"; } PrintWriter out = response.getWriter(); out.print(result); } ...
积木 2013-08-04
  • 打赏
  • 举报
回复
不是 @ResponseBody 的问题。。。还是要说使用场景啊,人家就是要通过你浏览器前台指定的Content-Type来判定是要给你 XML ? JSON ? 还是其他的格式啊。这就是人家自动化的一个体现嘛。 呵呵。
hz890 2013-08-04
  • 打赏
  • 举报
回复
就因为前端脚本未指定"text"类型。 这个小问题足足折腾了快1天。 我想@ResponseBody注解不应该有那么多的“限制”。 还是要感谢一下goodboy1881!
hz890 2013-08-04
  • 打赏
  • 举报
回复
<script type="text/javascript"> var jq = jQuery.noConflict(); jq(document).ready(function () { jq("#btnLogin").click(function () { jq.post("${pageContext.request.contextPath}/validateLogin.xhtml", { name: jq("#name").val(), password: jq("#password").val() }, function (data, status) { if (data == "success") { jq("#lblResult").text("Login Successfully!"); window.setTimeout("location.replace(\"${pageContext.request.contextPath}/index.xhtml\")", 3000); } else { jq("#lblResult").text("Login Failed!"); } }, "text" ); return false; } ); } ); </script>
hz890 2013-08-04
  • 打赏
  • 举报
回复
终于了解了。 是前端jQuery脚本未指定dataType所致。
hz890 2013-08-04
  • 打赏
  • 举报
回复
http://bbs.itqy8.com/topic/123 这个示例里,没有在前台设置accept-content为XML或者JSON,其控制器方法返回的是boolean,也并非JavaBean。 另外,从网上的资料来看,也没有说@ResponseBody注解只能用作JSON或XML场景。 如你所言,若只是返回一个简单的字串给前端,是否就不能用这个注解呢? 如果不能用@ResponseBody,那要怎样实现?
积木 2013-08-04
  • 打赏
  • 举报
回复
不是对返回值有什么限制,而是你用的场景问题。

81,094

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧