3

控制器中的相同方法能否同时用于 JSP 和其他 MIME 类型(如 XML 和 JSON)?

我知道以下在 Spring MVC 中解析视图的方法。

  1. 返回String带有视图名称的 a 并将属性添加到ModelorModelMap
  2. 返回ModelAndView带有视图名称和模型的 a
  3. 返回Object带有@ResponseBody注释的

我在处理 JSP 时使用 1 或 2,当我想返回 JSON 或 XML 时使用 3。

我知道我可以使用两种方法并使用@RequestMapping(headers="accept=application/xml")or@produces注释来定义它们处理的 MIME 类型,但是是否可以只用一种方法来做到这一点?

控制器逻辑非常简单,映射两个返回相同精确模型的不同方法似乎是不必要的重复,或者这只是它的完成方式?

4

2 回答 2

3

是的,这在 Spring MVC 3.x 中是直截了当的......

您基本上只为普通的 JSP 页面视图编写控制器方法,然后ContentNegotiatingViewResolver在 Dispatcher servlet 配置中配置一个 bean,它查看请求的 mime 类型(或文件扩展名)并返回适当的输出类型。

请按照此处的说明进行操作:Spring 3 MVC ContentNegotiatingViewResolver Example

于 2012-10-19T08:49:36.427 回答
1

我最近有同样的要求,下面是我的代码。validateTicket 返回 jsp 名称, sendForgotPassword 邮件返回 json。我的春季版本是 4.0.0.RELEASE。当然,如果我需要返回复杂的 json,那么我肯定会注册 Jackson 转换器 - http://docs.spring.io/spring/docs/4.0.x/javadoc-api/org/springframework/http/converter/json /MappingJackson2HttpMessageConverter.html

<?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: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="foo.bar" />
<bean id="viewResolver"
    class="org.springframework.web.servlet.view.UrlBasedViewResolver">
    <property name="viewClass"
        value="org.springframework.web.servlet.view.JstlView" />
    <property name="prefix" value="/WEB-INF/jsp/" />
    <property name="suffix" value=".jsp" />
</bean>
</beans>

@Controller
@RequestMapping("/forgot-password")
public class ForgotPasswordController {

@RequestMapping(value="/reset-password", method = RequestMethod.GET)
public String validateTicket(@RequestParam String ticket, @RequestParam String emailAddress) {
    return "resetPassword";
}

@RequestMapping(value="/send-mail", method = RequestMethod.POST, produces="application/json")
public @ResponseBody String sendForgotPasswordMail(@RequestParam String emailAddress) throws LoginException {
    return "{\"success\":\"true\"}";
}
}
于 2014-05-18T01:05:49.503 回答