1.新建项目(选择quikstart)
2.增加spring boot 依赖
org.springframework.boot spring-boot-autoconfigure 1.5.2.RELEASE org.springframework.boot spring-boot-starter-web 1.5.2.RELEASE
3.添加 springboot打包jar 插件依赖
参考 Spring Boot的Maven插件Spring Boot Maven plugin详解
maven-javadoc-plugin 2.9.1 UTF-8 UTF-8 UTF-8 true org.springframework.boot spring-boot-maven-plugin repackage org.apache.maven.plugins maven-compiler-plugin 1.8 UTF-8
4. 设置启动
application.properties 设置
server.port=9089
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.SpringApplication; /** * Hello world! * */ @SpringBootApplication public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } }
5. 添加 Contrller层
import com.g2.webtest.model.Person; import com.g2.webtest.model.PersonReq; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import java.util.HashMap; import java.util.Map; @RestController @RequestMapping("/h5") public class HomeController { private static MapdataSource; private static Person anonymous = new Person("未知", 0); @RequestMapping(value = "/{code}.jsonp") public Person testJsonp(@PathVariable("code") String code) { return dataSource.getOrDefault(code, anonymous); } @RequestMapping(value = "/person", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType .APPLICATION_JSON_VALUE) @ResponseBody public Person testJsonp2(@RequestBody PersonReq req) { return dataSource.getOrDefault(req.getCode(), anonymous); } static { dataSource = new HashMap<>(); dataSource.put("1001", new Person("张三", 15)); dataSource.put("1002", new Person("李四", 18)); } }
public class Person { private String name; private int age; public Person(){ this("",0); } public Person(String name,int age){ this.name=name; this.age=age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
6.设置jsonp的配置
import com.g2.webtest.controller.h5.HomeController; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.servlet.mvc.method.annotation.AbstractJsonpResponseBodyAdvice; @ControllerAdvice(basePackageClasses = {HomeController.class}) public class JSONPConfiguration extends AbstractJsonpResponseBodyAdvice { public JSONPConfiguration(){ super("callback","jsonp"); } }
7.测试
http://127.0.0.1:9089/h5/1001.jsonp?callback=myfun
myfun({"name":"张三","age":15});