当大家学了很多spring的技术之后会发现它有一个框架叫做springboot这个框架让大家眼前一新 感觉之前的前端控制器框架都没这个简单 这个框架就是颠覆Java程序员的思维有一本书叫做springboot实战写的不错大家可以买来看看接下来我给大家展示一下入门springboot项目hello
首先我们创建一个maven项目,点开pom.xml在里面进行配置如下就可以实现一个简单的hello页面的展现;
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.4.0.RELEASE</version> </parent>
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <!-- 由于我们在上面指定了parent的版本 spring会选择最合适的版本添加 --> </dependency>
当我们添加了父节点依赖 并确定了版本号 之后的spring相关的引入都不需要配置版本号 都是它主动给我们匹配好 相当的简便,建议大家安装一个私服nexus这样你需要什么架包都可以在上面搜索,它会给你展现相关的配置文件 你只需要拷贝过去就可以了
下面展现前端控制器的代码
@RestController public class HelloController { @RequestMapping("/hello") public String hello(){ return "hello"; } /** * spring boot 默认使用的json解析框架是Jackson * @return */ @RequestMapping("getDemo") public User getDemo(){ User user = new User(); user.setId("123"); user.setUsername("张三"); user.setDateTime(new Date()); return user; } }
这里我们使用RestController而没有使用Controller原因是它相当于@Controller和@RequestBody
RequestBody的使用
@RequestBody需要把所有请求参数作为json解析,因此,不能包含key=value这样的写法在请求url中,所有的请求参数都是一个json
再写一个测试类 当我们以Java的方式运行此类的时候就可以直接访问了
@SpringBootApplication public class Test { /** * 在这里我们使用 @Bean注入 fastJsonHttpMessageConvert * @return */ @Bean public HttpMessageConverters fastJsonHttpMessageConverters(){ //先定义一个convert转换消息的对象 FastJsonHttpMessageConverter jsonHttpMessageConverter = new FastJsonHttpMessageConverter(); //添加配置信息 比如: 是否要格式化返回值 FastJsonConfig jsonConfig = new FastJsonConfig(); jsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat); //在convert中添加配置信息 jsonHttpMessageConverter.setFastJsonConfig(jsonConfig); HttpMessageConverter<?> converters = jsonHttpMessageConverter; return new HttpMessageConverters(converters); } public static void main(String[] args) { /** * 在main方法中启动我们的应用程序 */ SpringApplication.run(Test.class, args); } }其中的HttpMessageConverts是阿里的一个json框架 快速的转化json对象的一个框架可以自定义很多东西 你也可以使用jackson架包看个人喜好,运行之后直接访问localhost:8080//hello就可以出现hello了 不需要项目名称是什么也不需要你加入到Tomcat容器中 因为它已经自带了 它就是这么神奇让人很是喜欢。