SpringBoot Web(中)

REST理论基础

REST用不同状态来进行rpc传输,比较轻量级的web服务

架构属性:

  1. 性能
  2. 可伸缩性
  3. 统一接口简化性
  4. 组件可修改性
  5. 组件通讯可见性
  6. 组件可移植性
  7. 可靠性

SpringBoot REST

核心接口:

定义相关:定义是一个Rest接口

  • @Controller
  • @RestController:是Controller+RestBody的组合
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {

   /**
    * The value may indicate a suggestion for a logical component name,
    * to be turned into a Spring bean in case of an autodetected component.
    * @return the suggested component name, if any (or empty String otherwise)
    * @since 4.0.1
    */
   @AliasFor(annotation = Controller.class)
   String value() default "";

}

映射相关:和URL映射有关

  • @RequestMapping
  • @GetMapping 4.3版本RequestMapping的替代物
  • @PostMapping
  • @PathVariable:路径的变量(动态的)
 http://localhost:8080/html/demo3
  http://localhost:8080/html/demo/messageString
@RestController
public class RestDemoController {

    //HTML
    //@RequestMapping(value = {"/html/demo","/html/demo2"},method = {RequestMethod.GET,RequestMethod.POST})
    //@GetMapping(path = "/html/demo3")
    @PostMapping(path = "/html/demo4")
    @ResponseBody
    public String htmlCode(){
        return "<html><body>hello,world</body></html>";
    }

    @GetMapping(path = "/html/demo/{message}")
    public String htmlPathVariable(@PathVariable String message){
        return "<html><body>hello,"+message+"</body></html>";
    }

请求相关:

  • @RequestParam:看着使用此注解和使用HttpServletRequest去获取参数都一样的效果,实际不然,用注解的方式会自动帮你强制转换成你想要的类型
http://localhost:8080/html/demo/param?p=123

@RestController
public class RestDemoController {

     @GetMapping(path = "/html/demo/param")
   public String htmlParam(@RequestParam(value = "p",required = false,defaultValue = "1") String param,
                           HttpServletRequest request){
       String param2 = request.getParameter("param2");
       return "<html><body>RequestParam value :"+param+",param2 value:"+param2+"</body></html>";
   }
}
  • @RequestHeader
@RestController
public class RestDemoController {

	@GetMapping(path = "/html/demo/header")
    public String htmlHeader(@RequestHeader(value = "Accept") String acceptHeader){
        return "<html><body>Request Accept value :"+acceptHeader+"</body></html>";
    }
}
  • @CookieValue
  • RequestEntity

响应相关:

  • @ResponseBody:响应体 在application.properties配置如下,当只有Controller的时候他会当做一个模板的路径而不是响应体进行返回,
spring.mvc.view.prefix=/WEB-INF/
spring.mvc.view.suffix=.jsp
  • ResponseEntity:他跟ResponseBody不同在于他可以存入相应头和响应体

    @GetMapping(path = "/html/demo/response/entity")
    public ResponseEntity<String> htmlResponseEntity() {

        HttpHeaders httpHeaders = new HttpHeaders();

        httpHeaders.put("MyHeader", Arrays.asList("MyHeaderValue"));

        ResponseEntity responseEntity = new ResponseEntity("<html><body>HTML ResponseEntity </body></html>", httpHeaders, HttpStatus.OK);
        return responseEntity;


    }

对于映射相关的 不可以同时存在不会同时生效只会生效最上面的那一个

  @RequestMapping(value = {"/html/demo","/html/demo2"},method = {RequestMethod.GET,RequestMethod.POST})
  @GetMapping(path = "/html/demo3")
  @PostMapping(path = "/html/demo4")

HATEOAS

HATEOAS(Hypermedia As The Engine Of Application State)在Json的基础上增加了,服务发现的机制,希望入口可以把相应的RESTUrl展示出来
在这里插入图片描述
pom.xml 在springboot 1.5.4当中写法如下

		<!-- hateoas-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-hateoas</artifactId>
		</dependency>

User对象


import org.springframework.hateoas.ResourceSupport;

public class User extends ResourceSupport {

    private String name;

    private int 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;
    }

}

JSONRestController

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;

@RestController
public class JSONRestController {

    @Bean
    public User currentUser() {
        User user = new User();

        user.setName("JSON");
        user.setAge(20);

        return user;
    }

    @Autowired
    @Qualifier("currentUser")
    private User user;

    @GetMapping(path = "/json/user",
            produces = MediaType.APPLICATION_JSON_VALUE)
    public User user() {

        user.add(linkTo(methodOn(JSONRestController.class).setUserName(user.getName())).withSelfRel());
        user.add(linkTo(methodOn(JSONRestController.class).setUserAge(user.getAge())).withSelfRel());

        return user;
    }

    //setName
    @PostMapping(path = "/json/user/set/name",
            produces = MediaType.APPLICATION_JSON_VALUE)

    public User setUserName(@RequestParam String name) {

        user.setName(name);

        return user;

    }


    //setAge
    @GetMapping(path = "/json/user/set/age",
            produces = MediaType.APPLICATION_JSON_VALUE)
    public User setUserAge(@RequestParam int age) {

        user.setAge(age);

        return user;

    }
}

REST文档生成

Spring Boot / mappings endpoin t可以看到所有的mapping相关信息

在springboot 1.5.4当中修改application.properties
endpoints.enabled = true
endpoints.sensitive = false

访问url
http://localhost:8080/mappings

Spring RestDocs:测试化用例在编译的时候

Swagger

REST客户端实践

导入pom.xml

		<!-- httpclient-->
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
		</dependency>

Web浏览器

Apache HttpClient

SpringRestTemplate

 public static void main(String[] args) {
        RestTemplate restTemplate = new RestTemplate();
        //String conent = restTemplate.getForObject("http://localhost:8080/json/user",String.class);
        //User conent = restTemplate.getForObject("http://localhost:8080/json/user",User.class);
        User conent = restTemplate.getForObject("http://localhost:8080/xml/user",User.class);
        System.out.println(conent);

    }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章