我最近有同樣的要求,下面是我的代碼。 validateTicket返回jsp名稱,sendForgotPassword郵件返回json。我的春天版本是4.0.0.RELEASE。當然,如果我需要返回複雜JSON話,我肯定會註冊傑克遜轉換器 - 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\"}";
}
}
見http://stackoverflow.com/questions/6568414/content-negotiation-in-spring-mvc – ebaxt
@ ebaxt我知道你可以使用'RequestMapping'來允許一個方法用JSON響應,另一個用JSP來響應。問題在於如何以同樣的方法處理JSON和JSP。 – vopilif
啊 - 對不起,沒有抓住:) – ebaxt