使用springboot开发接口:get接口、返回cookie的get接口、需要cookie的get接口
使用springboot开发接口
配置环境
<?xml version="1.0" encoding="UTF-8"?>
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.6.4
com.example.hello
demo
0.0.1-SNAPSHOT
demo
Demo project for Spring Boot
11
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-maven-plugin
配置端口
添加appclication.properties
server.port=${port:8888}
添加代理类
创建Application类:
@ComponentScan():这个指扫描哪个包来代理
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@ComponentScan("com.course.server")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
}
创建返回cookie的get请求
@RestController:来指明希望被代理
@RequestMapping:设置路径及请求方式
HttpServletResponse:封装响应信息,返回给外部使用
package com.course.server;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
@RestController
public class MyGetMethod {
@RequestMapping(value = "/getCookies",method = RequestMethod.GET)
public String getCookies(HttpServletResponse response){
//HttpServletRequest 装请求信息类
//HttpServletResponse 装响应信息类
//创建cookie
Cookie cookie = new Cookie("login","true");
//给返回值添加cookie
response.addCookie(cookie);
return "成功获取cookie";
}
}
创建需要cookie才能访问的get请求
HttpServletRequest: 封装请求信息,给内部使用
/*
* 要求客户端携带cookies访问
*
* */
@RequestMapping(value = "/get/with/cookies",method = RequestMethod.GET)
public String getWithCookies(HttpServletRequest request){
//创建一个cookie,从请求中获取
Cookie[] cookies = request.getCookies();
//判断是否携带cookie
if(Objects.isNull(cookies)){
return "你必须携带cookie来";
}
for (Cookie cookie:cookies){
//判断携带的cookie是否正确
if(cookie.getName().equals("login")&&cookie.getValue().equals("true")){
return "因为你携带了cookie,所以访问成功";
}
}
return "你必须携带正确的cookie来";
}