SpringBoot入门——返回JSON数据
新手看看,大牛酱油~
1、Maven设置pom引入JAR包
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.aspirecn.exer</groupId>
<artifactId>webfw</artifactId>
<version>1.0.0</version>
<!-- springboot一般引用jar就行 -->
<packaging>jar</packaging>
<!-- 设置父引用 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.1.RELEASE</version>
</parent>
<!-- 配置需要的各个jar包版本、JAVA版本信息 -->
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<!-- 所需要的依赖包 -->
<dependencies>
<!-- web SpringMvc、AOP等依赖的包 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>
2、创建实体类Demo
package com.springboot.entity
public class Demo {
private int id; //创建id
private String name; //创建名字
//Springboot默认调用了jackson包,可以用此注解格式化日期格式
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
private Date createTime; //创建时间
private String remarks; //备注信息
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getRemarks() {
return remarks;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
}
3、创建Controller
package com.springboot.controller;
import java.util.Date;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
//@RestController = @ResponseBody + @Controller组合
@RestController
public class HelloController {
//如果发生乱码,可以改成
//@RequestMapping(path="/getDemo",produces = "application/json;charset=UTF-8" )
@RequestMapping("/getDemo")
public Demo getDemo(){
Demo demo=new Demo();
demo.setId(1);
demo.setName("李四");
demo.setCreateTime(new Date());
demo.setRemarks("这是备注信息");
return demo;
}
}
4、Springboot启动类
package com.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
//加此注解说明此为Springboot启动类
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Appication.class, args);
System.out.println("_____启动完成______");
}
}
直接启动Application运行
输入:
http://localhost:8080/getDemo
运行结果: