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类
Springboot快速搭建Web API项目_第1张图片

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

你可能感兴趣的:(spring,boot,tomcat)