Springboot快速搭建Web API项目

内容概述

SpringBoot最常见得用途就是web api项目。

本文介绍使用自动配置功能,通过最简洁的pom依赖,快速搭建一个示例项目。

实现的功能为:接收http请求并返回json格式的数据。

一、配置pom.xml依赖

1.引入springweb依赖

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

2.引入数据库依赖(此处我们用的是SQL Server)

		<!-- SQL server-->
		<dependency>
			<groupId>com.microsoft.sqlserver</groupId>
			<artifactId>mssql-jdbc</artifactId>
			<version>7.4.1.jre8</version>
		</dependency>

二、配置服务端口和数据库

1.在application.properties中添加:

# 配置端口
server.port = 8088

# 配置SQLServer数据库连接
spring.datasource.url = jdbc:sqlserver://localhost;DatabaseName=数据库名称
spring.datasource.username = ***
spring.datasource.password = ***
spring.datasource.driver-class-name = com.microsoft.sqlserver.jdbc.SQLServerDriver

三、添加API接口

1.在JAVA目录下添加Controller、Service两个java类
在这里插入图片描述

2.UserController.java(通常在这里编写接口信息)

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;

/**
 * Created by *** on 2023/8/31.
 */
@RestController
public class UserController {

    @Autowired
    UserService userService;

    // 用户查询
    @CrossOrigin
    @PostMapping("/user/info")
    public Result infoUser(){
        return userService.InfoUser();
    }

    // 用户添加
    @CrossOrigin
    @PostMapping("/user/add")
    public Result addUser(@RequestBody Map<String,String> map){
        return userService.AddUser(map.get("pid"), map.get("name"), map.get("level"));
    }

    // 用户编辑
    @CrossOrigin
    @PostMapping("/user/edit")
    public Result editUser(@RequestBody Map<String,String> map){
        return userService.EditUser(map.get("id"), map.get("name"));
    }

    // 用户删除
    @CrossOrigin
    @PostMapping("/user/delete")
    public Result deleteUser(@RequestBody Map<String,String> map){
        return userService.DeleteUser(map.get("id"));
    }
}

3.UserService.java (通常在这里编写SQL查询方法)

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * Created by *** on 2023/8/31.
 */
@Service
public class UserService {
    @Autowired
    JdbcTemplate jdbcTemplate;

    /**
     * 用户查询
     * @return
     */
    @Transactional
    public Result InfoUser(){
        try {
            String SQL = "SELECT * FROM 表名称 ";
            List<Map<String, Object>> list = jdbcTemplate.queryForList(SQL);
            return Result.ok("查询成功",list);

        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询失败");
        }
    }

    /**
     * 用户添加
     * @param pid
     * @param name
     * @return
     */
    @Transactional
    public Result AddUser(String pid, String name, String level){
        try {
            Map<String, Object> count = jdbcTemplate.queryForMap("SELECT MAX(ID) FROM 用户信息数据表");
            int id =  Integer.parseInt(count.get("").toString()) + 1;
            String SQL = "INSERT INTO 用户信息数据表 VALUES (?, ?, ?, ?, NULL, NULL)";
            int res = jdbcTemplate.update(SQL, id, pid, name, level);
            System.out.println("添加id:" + id);
            return Result.ok("添加成功");

        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("添加失败");
        }
    }

    /**
     * 用户编辑
     * @param id
     * @param name
     * @return
     */
    @Transactional
    public Result EditUser(String id, String name){
        try {
            String SQL = "UPDATE 用户信息数据表 SET Name=? WHERE ID=?";
            int res = jdbcTemplate.update(SQL, name, id);
            System.out.println("编辑id:" + id);
            return Result.ok("编辑成功");

        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("编辑失败");
        }
    }

    /**
     * 用户删除
     * @param id
     * @return
     */
    @Transactional
    public Result DeleteUser(String id){
        try {
            String SQL = "DELETE FROM 用户信息数据表 WHERE ID=?";
            int res = jdbcTemplate.update(SQL, id);
            System.out.println("删除id:" + id);
            return Result.ok("删除成功");

        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除失败");
        }
    }
}

4.Result .java (信息返回通用类)


/**
 * Created by *** on 2023/8/31.
 */
public class Result {
    private Integer code;
    private String msg;
    private Object result;

    public static Result ok(String msg, Object result) {
        return new Result(200, msg, result);
    }


    public static Result ok(String msg) {
        return new Result(200, msg, null);
    }


    public static Result error(String msg, Object result) {
        return new Result(500, msg, result);
    }


    public static Result error(String msg) {
        return new Result(500, msg, null);
    }

    private Result() {
    }

    private Result(Integer code, String msg, Object result) {
        this.code = code;
        this.msg = msg;
        this.result = result;
    }

    public Integer getCode() {
        return code;
    }

    public Object getResult() {
        return result;
    }

    public String getMsg() {
        return msg;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public void setResult(Object result) {
        this.result = result;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王八八。

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值