数据的使用主要还是以JSON为主,我们不会去使用XML。

这个时候我们先不使用@RestController,我们使用之前SpringMVC的那种方式,就是@Controller。

 @ResponseBody就表示返回出去的数据是以一个JSON字符串或者JSON对象为主。

 /imooc-springboot-starter/src/main/java/com/imooc/controller/UserController.java

package com.imooc.controller;

import java.util.Date;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody; import com.imooc.pojo.User; @Controller
public class UserController { @RequestMapping("/hello")
@ResponseBody
public User hello() { User u = new User();
u.setName("imooc");
u.setAge(18);
u.setBirthday(new Date());
u.setPassword("imooc");
//u.setDesc(null); return u; }
}

 运行并启动项目,控制台打印了错误

  .   ____          _            __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.0.6.RELEASE) 2018-10-27 10:41:22.306 INFO 10376 --- [ main] com.imooc.ImoocApplication : Starting ImoocApplication on DESKTOP-S07DGSI with PID 10376 (D:\imooc-springboot-starter\imooc-springboot-starter\target\classes started by ZHONGZHENHUA in D:\imooc-springboot-starter\imooc-springboot-starter)
2018-10-27 10:41:22.314 INFO 10376 --- [ main] com.imooc.ImoocApplication : No active profile set, falling back to default profiles: default
2018-10-27 10:41:22.488 INFO 10376 --- [ main] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@1e67a849: startup date [Sat Oct 27 10:41:22 CST 2018]; root of context hierarchy
2018-10-27 10:41:26.674 INFO 10376 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2018-10-27 10:41:26.799 INFO 10376 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2018-10-27 10:41:26.800 INFO 10376 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.34
2018-10-27 10:41:26.832 INFO 10376 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [C:\Program Files\Java\jre1.8.0_144\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:/Program Files/Java/jre1.8.0_144/bin/server;C:/Program Files/Java/jre1.8.0_144/bin;C:/Program Files/Java/jre1.8.0_144/lib/amd64;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v8.0\bin;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v8.0\libnvvp;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0\bin;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0\libnvvp;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.2\bin;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.2\libnvvp;C:\ProgramData\Oracle\Java\javapath;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;D:\BaiduNetdiskDownload\adt-bundle-windows-x86_64_20140101\adt-bundle-windows-x86_64_20140101\sdk\platform-tools;D:\BaiduNetdiskDownload\adt-bundle-windows-x86_64_20140101\adt-bundle-windows-x86_64_20140101\sdk\platform-tools;C:\Program Files\Java\jdk1.8.0_144\bin;C:\Program Files\Java\jdk1.8.0_144\jre\bin;I:\数据库\数据库3\mysql-5.7.21-winx64\mysql-5.7.21-winx64\bin;H:\NDK\android-ndk-r9d-windows-x86_64\android-ndk-r9d;D:\Users\ZHONGZHENHUA\Anaconda3\;C:\Program Files\Git\cmd;C:\Program Files\nodejs\;C:\Users\ZHONGZHENHUA\Server\maven\apache-maven-3.5.2\bin;C:\Program Files\TortoiseGit\bin;C:\WINDOWS\System32\OpenSSH\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files\NVIDIA GPU Computing Toolkit\cudnn\bin;D:\Users\ZHONGZHENHUA\Anaconda3\Scripts;C:\Program Files\NVIDIA GPU Computing Toolkit\cudnn\bin;C:\ProgramData\NVIDIA GPU Computing Toolkit\v9.0;C:\Users\ZHONGZHENHUA\.dnx\bin;C:\Program Files\Microsoft DNX\Dnvm\;C:\Program Files\Microsoft SQL Server\130\Tools\Binn\;C:\ProgramData\NVIDIA GPU Computing Toolkit\v8.0;C:\Users\ZHONGZHENHUA\AppData\Local\Microsoft\WindowsApps;C:\Users\ZHONGZHENHUA\AppData\Roaming\npm;D:\Wind\Wind.NET.Client\WindNET\bin\;G:\eclipse-jee-2018-09-win32-x86_64\eclipse;;.]
2018-10-27 10:41:27.162 INFO 10376 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2018-10-27 10:41:27.166 INFO 10376 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 4683 ms
2018-10-27 10:41:27.447 INFO 10376 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Servlet dispatcherServlet mapped to [/]
2018-10-27 10:41:27.457 INFO 10376 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-10-27 10:41:27.459 INFO 10376 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-10-27 10:41:27.460 INFO 10376 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-10-27 10:41:27.460 INFO 10376 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2018-10-27 10:41:27.770 INFO 10376 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-10-27 10:41:28.339 INFO 10376 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@1e67a849: startup date [Sat Oct 27 10:41:22 CST 2018]; root of context hierarchy
2018-10-27 10:41:28.629 INFO 10376 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/hello]}" onto public java.lang.Object com.imooc.controller.HelloController.hello()
2018-10-27 10:41:28.634 WARN 10376 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappingHandlerMapping' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping. Cannot map 'userController' method
public com.imooc.pojo.User com.imooc.controller.UserController.hello()
to {[/hello]}: There is already 'helloController' bean method
public java.lang.Object com.imooc.controller.HelloController.hello() mapped.
2018-10-27 10:41:28.650 INFO 10376 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2018-10-27 10:41:28.690 INFO 10376 --- [ main] ConditionEvaluationReportLoggingListener : Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2018-10-27 10:41:28.721 ERROR 10376 --- [ main] o.s.boot.SpringApplication : Application run failed org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappingHandlerMapping' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping. Cannot map 'userController' method
public com.imooc.pojo.User com.imooc.controller.UserController.hello()
to {[/hello]}: There is already 'helloController' bean method
public java.lang.Object com.imooc.controller.HelloController.hello() mapped.
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1694) ~[spring-beans-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:573) ~[spring-beans-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:495) ~[spring-beans-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317) ~[spring-beans-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315) ~[spring-beans-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:759) ~[spring-beans-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867) ~[spring-context-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:548) ~[spring-context-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140) ~[spring-boot-2.0.6.RELEASE.jar:2.0.6.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:754) [spring-boot-2.0.6.RELEASE.jar:2.0.6.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:386) [spring-boot-2.0.6.RELEASE.jar:2.0.6.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:307) [spring-boot-2.0.6.RELEASE.jar:2.0.6.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1242) [spring-boot-2.0.6.RELEASE.jar:2.0.6.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1230) [spring-boot-2.0.6.RELEASE.jar:2.0.6.RELEASE]
at com.imooc.ImoocApplication.main(ImoocApplication.java:10) [classes/:na]
Caused by: java.lang.IllegalStateException: Ambiguous mapping. Cannot map 'userController' method
public com.imooc.pojo.User com.imooc.controller.UserController.hello()
to {[/hello]}: There is already 'helloController' bean method
public java.lang.Object com.imooc.controller.HelloController.hello() mapped.
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry.assertUniqueMethodMapping(AbstractHandlerMethodMapping.java:581) ~[spring-webmvc-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry.register(AbstractHandlerMethodMapping.java:545) ~[spring-webmvc-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.registerHandlerMethod(AbstractHandlerMethodMapping.java:267) ~[spring-webmvc-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.lambda$detectHandlerMethods$1(AbstractHandlerMethodMapping.java:252) ~[spring-webmvc-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at java.util.LinkedHashMap.forEach(Unknown Source) ~[na:1.8.0_144]
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.detectHandlerMethods(AbstractHandlerMethodMapping.java:250) ~[spring-webmvc-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.initHandlerMethods(AbstractHandlerMethodMapping.java:219) ~[spring-webmvc-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.afterPropertiesSet(AbstractHandlerMethodMapping.java:189) ~[spring-webmvc-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping.afterPropertiesSet(RequestMappingHandlerMapping.java:136) ~[spring-webmvc-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1753) ~[spring-beans-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1690) ~[spring-beans-5.0.10.RELEASE.jar:5.0.10.RELEASE]
... 16 common frames omitted

修改UserController的@RequestMapping("/hello")为@RequestMapping("/user")

package com.imooc.controller;

import java.util.Date;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody; import com.imooc.pojo.User; @Controller
public class UserController { //@RequestMapping("/hello")
@RequestMapping("/user")
@ResponseBody
public User hello() { User u = new User();
u.setName("imooc");
u.setAge(18);
u.setBirthday(new Date());
u.setPassword("imooc");
//u.setDesc(null); return u; }
}

运行并启动项目,控制台没打印错误了

  .   ____          _            __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.0.6.RELEASE) 2018-10-27 11:05:06.338 INFO 5040 --- [ main] com.imooc.ImoocApplication : Starting ImoocApplication on DESKTOP-S07DGSI with PID 5040 (D:\imooc-springboot-starter\imooc-springboot-starter\target\classes started by ZHONGZHENHUA in D:\imooc-springboot-starter\imooc-springboot-starter)
2018-10-27 11:05:06.345 INFO 5040 --- [ main] com.imooc.ImoocApplication : No active profile set, falling back to default profiles: default
2018-10-27 11:05:06.611 INFO 5040 --- [ main] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@3bbc39f8: startup date [Sat Oct 27 11:05:06 CST 2018]; root of context hierarchy
2018-10-27 11:05:11.911 INFO 5040 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2018-10-27 11:05:12.001 INFO 5040 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2018-10-27 11:05:12.002 INFO 5040 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.34
2018-10-27 11:05:12.035 INFO 5040 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [C:\Program Files\Java\jre1.8.0_144\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:/Program Files/Java/jre1.8.0_144/bin/server;C:/Program Files/Java/jre1.8.0_144/bin;C:/Program Files/Java/jre1.8.0_144/lib/amd64;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v8.0\bin;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v8.0\libnvvp;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0\bin;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0\libnvvp;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.2\bin;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.2\libnvvp;C:\ProgramData\Oracle\Java\javapath;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;D:\BaiduNetdiskDownload\adt-bundle-windows-x86_64_20140101\adt-bundle-windows-x86_64_20140101\sdk\platform-tools;D:\BaiduNetdiskDownload\adt-bundle-windows-x86_64_20140101\adt-bundle-windows-x86_64_20140101\sdk\platform-tools;C:\Program Files\Java\jdk1.8.0_144\bin;C:\Program Files\Java\jdk1.8.0_144\jre\bin;I:\数据库\数据库3\mysql-5.7.21-winx64\mysql-5.7.21-winx64\bin;H:\NDK\android-ndk-r9d-windows-x86_64\android-ndk-r9d;D:\Users\ZHONGZHENHUA\Anaconda3\;C:\Program Files\Git\cmd;C:\Program Files\nodejs\;C:\Users\ZHONGZHENHUA\Server\maven\apache-maven-3.5.2\bin;C:\Program Files\TortoiseGit\bin;C:\WINDOWS\System32\OpenSSH\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files\NVIDIA GPU Computing Toolkit\cudnn\bin;D:\Users\ZHONGZHENHUA\Anaconda3\Scripts;C:\Program Files\NVIDIA GPU Computing Toolkit\cudnn\bin;C:\ProgramData\NVIDIA GPU Computing Toolkit\v9.0;C:\Users\ZHONGZHENHUA\.dnx\bin;C:\Program Files\Microsoft DNX\Dnvm\;C:\Program Files\Microsoft SQL Server\130\Tools\Binn\;C:\ProgramData\NVIDIA GPU Computing Toolkit\v8.0;C:\Users\ZHONGZHENHUA\AppData\Local\Microsoft\WindowsApps;C:\Users\ZHONGZHENHUA\AppData\Roaming\npm;D:\Wind\Wind.NET.Client\WindNET\bin\;G:\eclipse-jee-2018-09-win32-x86_64\eclipse;;.]
2018-10-27 11:05:12.592 INFO 5040 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2018-10-27 11:05:12.596 INFO 5040 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 5991 ms
2018-10-27 11:05:12.932 INFO 5040 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Servlet dispatcherServlet mapped to [/]
2018-10-27 11:05:12.942 INFO 5040 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-10-27 11:05:12.942 INFO 5040 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-10-27 11:05:12.943 INFO 5040 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-10-27 11:05:12.945 INFO 5040 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2018-10-27 11:05:13.306 INFO 5040 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-10-27 11:05:13.776 INFO 5040 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@3bbc39f8: startup date [Sat Oct 27 11:05:06 CST 2018]; root of context hierarchy
2018-10-27 11:05:14.229 INFO 5040 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/hello]}" onto public java.lang.Object com.imooc.controller.HelloController.hello()
2018-10-27 11:05:14.239 INFO 5040 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/user]}" onto public com.imooc.pojo.User com.imooc.controller.UserController.hello()
2018-10-27 11:05:14.251 INFO 5040 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2018-10-27 11:05:14.259 INFO 5040 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-10-27 11:05:14.354 INFO 5040 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-10-27 11:05:14.354 INFO 5040 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-10-27 11:05:14.926 INFO 5040 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2018-10-27 11:05:15.103 INFO 5040 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2018-10-27 11:05:15.112 INFO 5040 --- [ main] com.imooc.ImoocApplication : Started ImoocApplication in 9.782 seconds (JVM running for 10.974)

 再次修改UserController,重新运行并启动项目

package com.imooc.controller;

import java.util.Date;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody; import com.imooc.pojo.User; @Controller
@RequestMapping("/user")
public class UserController { //@RequestMapping("/hello")
@RequestMapping("/getUser")
@ResponseBody
public User hello() {
//public User getUser() {
User u = new User();
u.setName("imooc");
u.setAge(18);
u.setBirthday(new Date());
u.setPassword("imooc");
//u.setDesc(null); return u; }
}

 这个就是一个User对象。在真正的开发中,我们日常出去一个JSON的数据,我们不会很简单地把一个这样子的一个类型数据给抛出去,我们肯定是要对它做一个额外的封装。自己构建一个封装类/imooc-springboot-starter/src/main/java/com/imooc/pojo/LeeJSONResult.java

设置一下文件(Files)注释标签

/**  

 * Copyright © ${year}Nathan.Lee.Salvatore. All rights reserved.

 *

 * @Title: ${file_name}

 * @Prject: ${project_name}

 * @Package: ${package_name}

 * @Description: ${todo}

 * @author: ${user}  

 * @date: ${date} ${time}

 * @version: V1.0  

 */

/**

 * @Title:${enclosing_type}

 * @Description:${todo}

 * ${tags}

 * @author: ${user}

 * @date: ${date} ${time}

 */

/imooc-springboot-starter/src/main/java/com/imooc/pojo/LeeJSONResult.java

/**  

 * Copyright © 2018Nathan.Lee.Salvatore. All rights reserved.

 *

 * @Title: LeeJSONResult.java

 * @Prject: imooc-springboot-starter

 * @Package: com.imooc.pojo

 * @Description: 自定义响应数据结构
* 这个类是提供给门户,ios,安卓,微信商城用的
* 门户接受此类数据后需要使用本类的方法转换成对于的数据类型格式(类,或者list)
* 其他自行处理
* 200:表示成功
* 500:表示错误,错误信息在msg字段中
* 501:bean验证错误,不管多少个错误都以map形式返回
* 502:拦截器拦截到用户token出错
* 555:异常抛出信息 * @author: ZHONGZHENHUA * @date: 2018年10月27日 下午4:03:02 * @version: V1.0 */
package com.imooc.pojo; import java.util.List;
//import java.io.IOException; //import com.fasterxml.jackson.core.JsonParseException;
//import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper; /**
* @author ZHONGZHENHUA
*
*/
public class LeeJSONResult { // 定义jackson对象
private static final ObjectMapper MAPPER = new ObjectMapper(); // 响应业务状态
private Integer status; // 响应消息
private String msg; // 响应中的数据
private Object data; private String ok; // 不使用 public static LeeJSONResult build(Integer status, String msg, Object data) {
return new LeeJSONResult(status, msg ,data); } public static LeeJSONResult ok(Object data) {
return new LeeJSONResult(data);
} public static LeeJSONResult ok() {
return new LeeJSONResult(null);
} public static LeeJSONResult errorMsg(String msg) {
return new LeeJSONResult(500, msg , null);
} public static LeeJSONResult errorMap(Object data) {
return new LeeJSONResult(501, "error" , data);
} public static LeeJSONResult errorTokenMsg(String msg) {
return new LeeJSONResult(502, msg , null);
} public static LeeJSONResult errorException(String msg) {
return new LeeJSONResult(555, msg , null);
} public LeeJSONResult() { } //public static LeeJSONResult build(Integer status, String msg, Object data) {
//return new LeeJSONResult(status, msg ,data); //} public LeeJSONResult(Integer status , String msg , Object data) {
this.status = status;
this.msg = msg;
this.data = data;
} public LeeJSONResult(Object data) {
this.status = 200;
this.msg = "OK";
this.data = data;
} public Boolean isOK() {
return this.status == 200;
} public Integer getStatus() {
return status;
} public void setStatus(Integer status) {
this.status = status;
} public String getMsg() {
return msg;
} public void setMsg(String msg) {
this.msg = msg;
} public Object getData() {
return data;
} public void setData(Object data) {
this.data = data;
} public String getOk() {
return ok;
} public void setOk(String ok) {
this.ok = ok;
}
/**
* * @Title:LeeJSONResult * @Description: 将json结果集转化为LeeJSONResult对象
* 需要转换的对象是一个类 * @param jsonData
* @param clazz
* @return * @author: ZHONGZHENHUA * @date: 2018年10月28日 上午6:26:21
*/
public static LeeJSONResult formatToPojo(String jsonData, Class<?> clazz) {
try {
if(clazz == null) {
return MAPPER.readValue(jsonData, LeeJSONResult.class);
}
JsonNode jsonNode = MAPPER.readTree(jsonData);
JsonNode data = jsonNode.get("data");
Object obj = null;
if (clazz != null) {
if (data.isObject()) {
obj = MAPPER.readValue(data.traverse(), clazz);
} else if (data.isTextual()) {
obj = MAPPER.readValue(data.asText(), clazz);
}
}
return build(jsonNode.get("status").intValue(),jsonNode.get("msg").asText(),obj);
}catch (Exception e) {
// TODO Auto-generated catch block
return null;
} }
/**
* * @Title:LeeJSONResult * @Description: 没有object对象的转化 * @param json
* @return * @author: ZHONGZHENHUA * @date: 2018年10月28日 上午6:37:21
*/
public static LeeJSONResult format (String json) {
try {
return MAPPER.readValue(json, LeeJSONResult.class);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* * @Title:LeeJSONResult * @Description:Object是集合转化
* 需要转换的对象是一个list * @param jsonData
* @param clazz
* @return * @author: ZHONGZHENHUA * @date: 2018年10月28日 上午7:07:48
*/
public static LeeJSONResult formatToList(String jsonData, Class<?> clazz) {
try {
JsonNode jsonNode = MAPPER.readTree(jsonData);
JsonNode data = jsonNode.get("data");
Object obj = null;
if (data.isArray() && data.size() >0 ) {
obj = MAPPER.readValue(data.traverse(), MAPPER.getTypeFactory().constructCollectionType(List.class, clazz));
}
return build(jsonNode.get("status").intValue(),jsonNode.get("msg").asText(),obj);
} catch (Exception e) {
// TODO Auto-generated catch block
return null;
} }
}

/imooc-springboot-starter/src/main/java/com/imooc/controller/UserController.java

package com.imooc.controller;

import java.util.Date;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody; import com.imooc.pojo.LeeJSONResult;
import com.imooc.pojo.User; @Controller
@RequestMapping("/user")
public class UserController { //@RequestMapping("/hello")
@RequestMapping("/getUser")
@ResponseBody
public User hello() {
//public User getUser() {
User u = new User();
u.setName("imooc");
u.setAge(18);
u.setBirthday(new Date());
u.setPassword("imooc");
//u.setDesc(null); return u; }
@RequestMapping("/getUserJson")
@ResponseBody
public LeeJSONResult hello1() {
//public LeeJsonResult getUserJson() {
User u = new User();
u.setName("imooc");
u.setAge(18);
u.setBirthday(new Date());
u.setPassword("imooc");
//u.setDesc(null); return LeeJSONResult.ok(u); }
}

这是SpringMVC的一种方式。那SpringBoot又是怎么做的呢?@RestController=@Controller+@ResponseBody

package com.imooc.controller;

import java.util.Date;

//import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController; import com.imooc.pojo.LeeJSONResult;
import com.imooc.pojo.User; //@Controller
@RestController // @RestControler = @Controller + @ResponseBody
@RequestMapping("/user")
public class UserController { //@RequestMapping("/hello")
@RequestMapping("/getUser")
//@ResponseBody
public User hello() {
//public User getUser() {
User u = new User();
u.setName("imooc");
u.setAge(18);
u.setBirthday(new Date());
u.setPassword("imooc");
//u.setDesc(null); return u; }
@RequestMapping("/getUserJson")
//@ResponseBody
public LeeJSONResult hello1() {
//public LeeJsonResult getUserJson() {
User u = new User();
u.setName("imooc");
u.setAge(18);
u.setBirthday(new Date());
u.setPassword("imooc");
//u.setDesc(null); return LeeJSONResult.ok(u); }
}

第3章 springboot接口返回json 3-1 SpringBoot构造并返回一个json对象的更多相关文章

  1. 如何编写一个JSON解析器

    编写一个JSON解析器实际上就是一个函数,它的输入是一个表示JSON的字符串,输出是结构化的对应到语言本身的数据结构. 和XML相比,JSON本身结构非常简单,并且仅有几种数据类型,以Java为例,对 ...

  2. springboot 接口返回数据时 net.sf.json.JSONNull["empty"]) 异常

    @ResetController返回数据时出现异常 Could not write JSON: Object is null; nested exception is com.fasterxml.ja ...

  3. api接口写好了?想过(Accept,Content-Type)?返回类型json|xml?

    api接口写好了?想过(Accept,Content-Type)?返回类型json|xml? 起因: - A,B. A调用B提供的api接口. - A:为毛你的接口返回的是xml格式的(浏览器访问)? ...

  4. SpringBoot接口 - 如何优雅的对接口返回内容统一封装?

    在以SpringBoot开发Restful接口时,统一返回方便前端进行开发和封装,以及出现时给出响应编码和信息.@pdai SpringBoot接口 - 如何优雅的对接口返回内容统一封装? RESTf ...

  5. springboot接口返回封装与异常控制

    首先,返回有两个状态,status和code status标识response的状态,有2个值:0成功,-1服务错误. code跟业务有关,可以有各种数值,99999服务未知异常,10000参数异常, ...

  6. springboot 接口参数校验

    前言 在开发接口的时候,参数校验是必不可少的.参数的类型,长度等规则,在开发初期都应该由产品经理或者技术负责人等来约定.如果不对入参做校验,很有可能会因为一些不合法的参数而导致系统出现异常. 上一篇文 ...

  7. SpringBoot接口服务处理Whitelabel Error Page(转)

    To switch it off you can set server.error.whitelabel.enabled=false http://stackoverflow.com/question ...

  8. 2、SpringBoot接口Http协议开发实战8节课(1-6)

    1.SpringBoot2.xHTTP请求配置讲解 简介:SpringBoot2.xHTTP请求注解讲解和简化注解配置技巧 1.@RestController and @RequestMapping是 ...

  9. SpringBoot接口服务处理Whitelabel Error Page

    转载请注明来源:http://blog.csdn.net/loongshawn/article/details/50915979 <SpringBoot接口服务处理Whitelabel Erro ...

随机推荐

  1. UrlRewrite重写url

    UrlRewrite就是我们通常说的地址重写,用户得到的全部都是经过处理后的URL地址. 优点 (1)提高安全性 可以有效的避免一些参数名.ID等完全暴露在用户面前,如果用户随便乱输的话,不符合规则的 ...

  2. NSObject头文件解析 / 消息机制 / Runtime解读 (二)

    本章接着NSObject头文件解析 / 消息机制 / Runtime解读(一)写 给类添加属性: BOOL class_addProperty(Class cls, const char *name, ...

  3. 21 Python 异常处理

    异常和错误                                                      AttributeError 试图访问一个对象没有的树形,比如foo.x,但是fo ...

  4. spring学习-2

    Spring_属性配置细节 1.若字面值包含特殊字符,可以使用<[CDATA[]]>把字面值包裹起来 例:<value><![CDATA[<3333>^]]& ...

  5. linux内嵌汇编语言

    http://blog.chinaunix.net/uid-21254310-id-1828921.html http://www.cnblogs.com/lxgeek/archive/2011/01 ...

  6. [Unity3D]EZGUI 操作简单介绍

    官方的GUI根本无法跟EZGUI比,无论是资源还是易用性还是速度.EZGUI基于Mesh不占DrawCall.EZGUI是自动合并Mesh成为一个物体,并且贴图自动制作Atlas.所以效率高,CPU消 ...

  7. mysql前缀索引的应用

    在mysql中有时需要索引的列很长,如果直接应用索引会造成索引过大的问题.因此我们可以取其中一部分字段来做索引,例: 添加索引:alter table * add key (field(3));   ...

  8. Xcode9 修改工程名(含cocopods)

    由于需要现在要更改包名,但是在网上找了N多资料都比较老,16年的资料却是残缺不全,尤其 ios10 出了 .entitlement  的机制 ,很多琐碎的小细节 很容易忘记.所以我自己总结了一篇, 环 ...

  9. 深入理解Spring IOC

    转载自 http://www.cnblogs.com/xdp-gacl/p/4249939.html 学习过Spring框架的人一定都会听过Spring的IoC(控制反转) .DI(依赖注入)这两个概 ...

  10. linux环境下搭建redis

    1. 官网下载安装包,然后解压,或者直接从github上pull下来. git clone https://github.com/antirez/redis.git 2. 确保linux环境上已安装g ...