使用springboot开发接口

使用springboot开发接口

配置环境

<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example.hello</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>11</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

配置端口

添加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来";
    }

创建需要参数才能访问的get请求

第一种方式:key=value&key=value

    /*
    * 开发一个需要参数才能访问的get请求
    * 第一种实现方式 url:key=value&key=value
    * 我们来模拟获取商品列表
    * */
    @RequestMapping(value = "/get/with/param",method = RequestMethod.GET)
    public Map<String,Integer> getList(@RequestParam Integer start,@RequestParam Integer end){

        Map<String,Integer> myList= new HashMap<>();
        myList.put("鞋",400);
        myList.put("面",1);
        myList.put("衣服",300);
        return  myList;

    }

第二种路径参数方式

    /* 第二种实现方式
    *   url://get/with/param/{start}/{end}
    * */
    @RequestMapping(value = "/get/with/param/{start}/{end}")
    public Map myGetList(@PathVariable Integer start,@PathVariable Integer end){
        Map<String,Integer> myList= new HashMap<>();
        myList.put("鞋",400);
        myList.put("面",1);
        myList.put("衣服",300);
        return  myList;
    }

创建post请求

package com.course.server;

import com.course.bean.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@Api(value = "/",description = "这是我全部的post请求")
@RequestMapping(value = "/v1")
public class MyPostMethod {
    private static Cookie cookie;//这个变量是用来装cookie的
    //用户登录成功获取到cookies,然后再访问其他接口获取列表
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    @ApiOperation(value = "登录接口,成功后获取cookie",httpMethod = "POST")
    public String login(HttpServletResponse response,
                        @RequestParam(value = "userName",required = true) String userName,
                        @RequestParam(value = "password",required = true) String password){
        if (userName.equals("zhangsan")&&password.equals("123456")){
            cookie = new Cookie("login","true");
            return "恭喜你登录成功,并获取到cookie";
        }
        return "用户名或者密码错误";
    }

    @RequestMapping(value = "/getUserList",method = RequestMethod.POST)
    @ApiOperation(value = "获取用户列表接口",httpMethod = "POST")
    public String getUserList(HttpServletRequest request,@RequestBody User u){
        User user;
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie:cookies){
             if (cookie.getName().equals("login")&&cookie.getValue().equals("true")&&u.getUserName().equals("zhangsan")&&u.getPassword().equals("123456")){
                 user = new User();
                 user.setName("lisi");
                 user.setAge("11");
                 user.setSex("man");
                 return user.toString();
             }
        }
        return "参数不合法";

    }
}

posted @   77的小白  阅读(641)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
点击右上角即可分享
微信分享提示