代码如下
package shop.jitou.ssm.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import shop.jitou.ssm.domain.Account;
import shop.jitou.ssm.service.AccountService;
import java.io.UnsupportedEncodingException;
import java.util.List;
@RestController
public class AccountController {
/**
* 通过@Autowired自动装配方式,从SpringIoC容器中去查找到,并返回一个对象
*/
@Autowired
AccountService accountService;
@GetMapping(value = "/account/login", produces = "application/json;charset=utf-8")
public Account login() {
Account account = new Account();
account.setMoney(100.0);
account.setName("王燿");
account.setId(0);
return account; //在视图解析器中配置了前缀后缀
}
}
错误信息如下
网页中的网址
http://localhost:8080/ssm_war_exploded/account/login
网页报错内容
HTTP Status 406 – 不可接收
Type Status Report
描述 根据请求中接收到的主动协商头字段,目标资源没有用户代理可以接受的当前表示,而且服务器不愿意提供缺省表示。
Apache Tomcat/8.5.53
解决办法
pom.xml添加依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.58</version>
</dependency>
spring-mvc.xml配置更改
之前的配置
<mvc:annotation-driven></mvc:annotation-driven>
更改后的配置
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<!-- 配置Fastjson支持 -->
<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json</value>
<value>text/html;charset=UTF-8</value>
</list>
</property>
<!-- <property name="features">
<list>
<value>WriteMapNullValue</value>
<value>QuoteFieldNames</value>
</list>
</property>-->
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
再次测试接口,网页返回信息如下
{"id":0,"money":100.0,"name":"王燿"}
Account实体类如下
package shop.jitou.ssm.domain;
import java.io.Serializable;
public class Account implements Serializable {
private Integer id;
private String name;
private Double money;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getMoney() {
return money;
}
public void setMoney(Double money) {
this.money = money;
}
@Override
public String toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + money +
'}';
}
}
网友评论