今天在Springboot新建Controller时,调试接口时发现自己犯了一个低级低级低级的错误.记录下以免以后犯同一个错误;
报错信息:
org.thymeleaf.exceptions.TemplateInputException: Error resolving template
Controller代码如下:
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* @author AxeLai
* @date 2019-04-18 14:59
*/
@Controller
@Api(value = "UserController",description = "用户端")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping(value = "/user", method = RequestMethod.POST)
@ApiOperation(value = "新增用户")
public boolean addUser( User user) {
System.out.println("开始新增...");
return userService.addUser(user);
}
}
原因分析:
我们都知道,在controller上加注解@Controller 和@RestController都可以在前端调通接口,但是二者的区别在于,当用前者的时候在方法上必须添加注解@ResponseBody,如果不添加@ResponseBody,就会报上面错误,因为当使用@Controller 注解时,spring默认方法返回的是view对象(页面)。而加上@ResponseBody,则方法返回的就是具体对象了。@RestController的作用就相当于@Controller+@ResponseBody的结合体,而我在controller层请求处理完了返回时,没有使用@RestController或@ResponseBody而返回了非json格式,只是用了@Controller;
解决方法:
1.类上注解@Controller改为@RestController;
2.方法添加注解@ResponseBody;