@restcontroller 和@responsebody 在 Spring MVC + Thymeleaf 中不工作
@restcontroller and @responsebody not working in Spring MVC + Thymeleaf
在我的 spring MVC 4.1.5 应用程序中配置为使用 Thymeleaf 2.1.4(在它使用 JSP 并且工作正常之前),我无法 return JSON 响应。
它总是 return 一个完整的 HTML 页面天气我的请求映射在 @RestController 中或者如果它用 @responsebody
注释
这是控制器
在@controller class 中,我有以下映射
@RequestMapping(value = { "/", "/land", "/login" }, method = RequestMethod.GET)
public String getLogin(Model model, HttpSession session) {
session.setAttribute("login", "none");
System.out.println(programId);
model.addAttribute("signUpForm", new SignUpForm());
return "login";
}
在@RestController class 中,下面是相同 URL
的 post 方法
@RequestMapping(value = {"/login" }, method = RequestMethod.POST )
public @ResponseBody HashMap<String, Object> login2(@RequestBody SignUpForm signUpForm, HttpServletRequest request,
HttpServletResponse httpServletResponse, HashMap<String, Object> mo, HttpSession session ) {
User user = userDao.findUserByName(signUpForm.getUserName());
if (user != null && encoder.matches(signUpForm.getPassword(), user.getPassword())&& user.getProgram_id()==3) {/* && user.getProgram_id()==3*/
session.setMaxInactiveInterval(1200);
System.out.println(session.getMaxInactiveInterval()+":"+session.getLastAccessedTime()+":"+session.getCreationTime()+":"+session.getServletContext().getContextPath());
session.setAttribute("login", "success");
mo.put("redirect", "/home");
String ipAddress = request.getHeader("X-FORWARDED-FOR");
if (ipAddress == null) {
ipAddress = request.getRemoteAddr();
}
session.setAttribute("urip", ipAddress);
return mo;
} else {
mo.put("error", "Login failed. Please check your credentials");
return mo;
}
}
下面是我的xml配置
<context:component-scan base-package="com.company.cardholder" />
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="com.fasterxml.jackson.databind.ObjectMapper">
<property name="serializationInclusion">
<value type="com.fasterxml.jackson.annotation.JsonInclude.Include">NON_NULL</value>
</property>
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<mvc:default-servlet-handler />
<mvc:interceptors>
<bean class="com.company.cardholder.session.interceptors.URLInterceptor" />
</mvc:interceptors>
<mvc:resources mapping="/resources/**" location="/resources/" />
<bean id="templateResolver" class="org.thymeleaf.templateresolver.ServletContextTemplateResolver">
<property name="prefix" value="/WEB-INF/thymeleaf/" />
<property name="suffix" value=".html" />
<property name="templateMode" value="HTML5" />
<!-- Template cache is set to false (default is true). -->
<property name="cacheable" value="false" />
</bean>
<bean id="templateEngine" class="org.thymeleaf.spring4.SpringTemplateEngine">
<property name="templateResolver" ref="templateResolver" />
</bean>
<bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
<property name="templateEngine" ref="templateEngine" />
</bean>
这是我的JSON电话
$.ajax({
type: 'POST',
url: $form.attr('action'),
data: JSON.stringify({
userName: $form.find('#userName').val(),
password: $form.find('#password').val(),
}),
contentType: "application/json",
/*dataType: 'json',*/
complete: function(data) {
console.log(data);
if (data.redirect) {
// data.redirect contains the string URL to redirect to
window.location.href = data.redirect;
}else if(data.error){
$messageError.text(data.error);
$messageError.removeClass('hidden');
$messageSuccess.addClass('hidden');
}
}
});
好的。这是我想出的方法,但我仍然不确定原因。
public @ResponseBody HashMap<String, Object> login2(@RequestBody SignUpForm signUpForm, HttpServletRequest request,
HttpServletResponse httpServletResponse, HashMap<String, Object> mo, HttpSession session ){
////
}
在上面的方法签名中,我是"injecting"一个hashmap。 spring 框架默认值或一些未知配置决定注入 "Binding Result aware Hashmap." 我不确定它会产生什么不同。但要修复它,我必须做一个
HashMap<String, Object> mo=new HashMap<String, Object>;
在方法体内并删除注入的哈希图。
如果有人能够理解这种行为,请解释一下。我觉得我在 spring 框架的认识中错过了一些基本的东西。
在我的 spring MVC 4.1.5 应用程序中配置为使用 Thymeleaf 2.1.4(在它使用 JSP 并且工作正常之前),我无法 return JSON 响应。
它总是 return 一个完整的 HTML 页面天气我的请求映射在 @RestController 中或者如果它用 @responsebody
注释这是控制器 在@controller class 中,我有以下映射
@RequestMapping(value = { "/", "/land", "/login" }, method = RequestMethod.GET)
public String getLogin(Model model, HttpSession session) {
session.setAttribute("login", "none");
System.out.println(programId);
model.addAttribute("signUpForm", new SignUpForm());
return "login";
}
在@RestController class 中,下面是相同 URL
的 post 方法 @RequestMapping(value = {"/login" }, method = RequestMethod.POST )
public @ResponseBody HashMap<String, Object> login2(@RequestBody SignUpForm signUpForm, HttpServletRequest request,
HttpServletResponse httpServletResponse, HashMap<String, Object> mo, HttpSession session ) {
User user = userDao.findUserByName(signUpForm.getUserName());
if (user != null && encoder.matches(signUpForm.getPassword(), user.getPassword())&& user.getProgram_id()==3) {/* && user.getProgram_id()==3*/
session.setMaxInactiveInterval(1200);
System.out.println(session.getMaxInactiveInterval()+":"+session.getLastAccessedTime()+":"+session.getCreationTime()+":"+session.getServletContext().getContextPath());
session.setAttribute("login", "success");
mo.put("redirect", "/home");
String ipAddress = request.getHeader("X-FORWARDED-FOR");
if (ipAddress == null) {
ipAddress = request.getRemoteAddr();
}
session.setAttribute("urip", ipAddress);
return mo;
} else {
mo.put("error", "Login failed. Please check your credentials");
return mo;
}
}
下面是我的xml配置
<context:component-scan base-package="com.company.cardholder" />
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="com.fasterxml.jackson.databind.ObjectMapper">
<property name="serializationInclusion">
<value type="com.fasterxml.jackson.annotation.JsonInclude.Include">NON_NULL</value>
</property>
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<mvc:default-servlet-handler />
<mvc:interceptors>
<bean class="com.company.cardholder.session.interceptors.URLInterceptor" />
</mvc:interceptors>
<mvc:resources mapping="/resources/**" location="/resources/" />
<bean id="templateResolver" class="org.thymeleaf.templateresolver.ServletContextTemplateResolver">
<property name="prefix" value="/WEB-INF/thymeleaf/" />
<property name="suffix" value=".html" />
<property name="templateMode" value="HTML5" />
<!-- Template cache is set to false (default is true). -->
<property name="cacheable" value="false" />
</bean>
<bean id="templateEngine" class="org.thymeleaf.spring4.SpringTemplateEngine">
<property name="templateResolver" ref="templateResolver" />
</bean>
<bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
<property name="templateEngine" ref="templateEngine" />
</bean>
这是我的JSON电话
$.ajax({
type: 'POST',
url: $form.attr('action'),
data: JSON.stringify({
userName: $form.find('#userName').val(),
password: $form.find('#password').val(),
}),
contentType: "application/json",
/*dataType: 'json',*/
complete: function(data) {
console.log(data);
if (data.redirect) {
// data.redirect contains the string URL to redirect to
window.location.href = data.redirect;
}else if(data.error){
$messageError.text(data.error);
$messageError.removeClass('hidden');
$messageSuccess.addClass('hidden');
}
}
});
好的。这是我想出的方法,但我仍然不确定原因。
public @ResponseBody HashMap<String, Object> login2(@RequestBody SignUpForm signUpForm, HttpServletRequest request,
HttpServletResponse httpServletResponse, HashMap<String, Object> mo, HttpSession session ){
////
}
在上面的方法签名中,我是"injecting"一个hashmap。 spring 框架默认值或一些未知配置决定注入 "Binding Result aware Hashmap." 我不确定它会产生什么不同。但要修复它,我必须做一个
HashMap<String, Object> mo=new HashMap<String, Object>;
在方法体内并删除注入的哈希图。 如果有人能够理解这种行为,请解释一下。我觉得我在 spring 框架的认识中错过了一些基本的东西。