数据的使用主要还是以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-starterimooc-springboot-starter argetclasses started by ZHONGZHENHUA in D:imooc-springboot-starterimooc-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 FilesJavajre1.8.0_144in;C:WINDOWSSunJavain;C:WINDOWSsystem32;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 FilesNVIDIA GPU Computing ToolkitCUDAv8.0in;C:Program FilesNVIDIA GPU Computing ToolkitCUDAv8.0libnvvp;C:Program FilesNVIDIA GPU Computing ToolkitCUDAv9.0in;C:Program FilesNVIDIA GPU Computing ToolkitCUDAv9.0libnvvp;C:Program FilesNVIDIA GPU Computing ToolkitCUDAv9.2in;C:Program FilesNVIDIA GPU Computing ToolkitCUDAv9.2libnvvp;C:ProgramDataOracleJavajavapath;C:WINDOWSsystem32;C:WINDOWS;C:WINDOWSSystem32Wbem;C:WINDOWSSystem32WindowsPowerShellv1.0;D:BaiduNetdiskDownloadadt-bundle-windows-x86_64_20140101adt-bundle-windows-x86_64_20140101sdkplatform-tools;D:BaiduNetdiskDownloadadt-bundle-windows-x86_64_20140101adt-bundle-windows-x86_64_20140101sdkplatform-tools;C:Program FilesJavajdk1.8.0_144in;C:Program FilesJavajdk1.8.0_144jrein;I:数据库数据库3mysql-5.7.21-winx64mysql-5.7.21-winx64in;H:NDKandroid-ndk-r9d-windows-x86_64android-ndk-r9d;D:UsersHONGZHENHUAAnaconda3;C:Program FilesGitcmd;C:Program Files odejs;C:UsersHONGZHENHUAServermavenapache-maven-3.5.2in;C:Program FilesTortoiseGitin;C:WINDOWSSystem32OpenSSH;C:Program Files (x86)NVIDIA CorporationPhysXCommon;C:Program FilesNVIDIA GPU Computing Toolkitcudnnin;D:UsersHONGZHENHUAAnaconda3Scripts;C:Program FilesNVIDIA GPU Computing Toolkitcudnnin;C:ProgramDataNVIDIA GPU Computing Toolkitv9.0;C:UsersHONGZHENHUA.dnxin;C:Program FilesMicrosoft DNXDnvm;C:Program FilesMicrosoft SQL Server130ToolsBinn;C:ProgramDataNVIDIA GPU Computing Toolkitv8.0;C:UsersHONGZHENHUAAppDataLocalMicrosoftWindowsApps;C:UsersHONGZHENHUAAppDataRoaming pm;D:WindWind.NET.ClientWindNETin;G:eclipse-jee-2018-09-win32-x86_64eclipse;;.] 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-starterimooc-springboot-starter argetclasses started by ZHONGZHENHUA in D:imooc-springboot-starterimooc-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 FilesJavajre1.8.0_144in;C:WINDOWSSunJavain;C:WINDOWSsystem32;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 FilesNVIDIA GPU Computing ToolkitCUDAv8.0in;C:Program FilesNVIDIA GPU Computing ToolkitCUDAv8.0libnvvp;C:Program FilesNVIDIA GPU Computing ToolkitCUDAv9.0in;C:Program FilesNVIDIA GPU Computing ToolkitCUDAv9.0libnvvp;C:Program FilesNVIDIA GPU Computing ToolkitCUDAv9.2in;C:Program FilesNVIDIA GPU Computing ToolkitCUDAv9.2libnvvp;C:ProgramDataOracleJavajavapath;C:WINDOWSsystem32;C:WINDOWS;C:WINDOWSSystem32Wbem;C:WINDOWSSystem32WindowsPowerShellv1.0;D:BaiduNetdiskDownloadadt-bundle-windows-x86_64_20140101adt-bundle-windows-x86_64_20140101sdkplatform-tools;D:BaiduNetdiskDownloadadt-bundle-windows-x86_64_20140101adt-bundle-windows-x86_64_20140101sdkplatform-tools;C:Program FilesJavajdk1.8.0_144in;C:Program FilesJavajdk1.8.0_144jrein;I:数据库数据库3mysql-5.7.21-winx64mysql-5.7.21-winx64in;H:NDKandroid-ndk-r9d-windows-x86_64android-ndk-r9d;D:UsersHONGZHENHUAAnaconda3;C:Program FilesGitcmd;C:Program Files odejs;C:UsersHONGZHENHUAServermavenapache-maven-3.5.2in;C:Program FilesTortoiseGitin;C:WINDOWSSystem32OpenSSH;C:Program Files (x86)NVIDIA CorporationPhysXCommon;C:Program FilesNVIDIA GPU Computing Toolkitcudnnin;D:UsersHONGZHENHUAAnaconda3Scripts;C:Program FilesNVIDIA GPU Computing Toolkitcudnnin;C:ProgramDataNVIDIA GPU Computing Toolkitv9.0;C:UsersHONGZHENHUA.dnxin;C:Program FilesMicrosoft DNXDnvm;C:Program FilesMicrosoft SQL Server130ToolsBinn;C:ProgramDataNVIDIA GPU Computing Toolkitv8.0;C:UsersHONGZHENHUAAppDataLocalMicrosoftWindowsApps;C:UsersHONGZHENHUAAppDataRoaming pm;D:WindWind.NET.ClientWindNETin;G:eclipse-jee-2018-09-win32-x86_64eclipse;;.] 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); } }