Java创建接口实现前后端交互

极简

1、创建后端接口

创建 spring 项目,并引入依赖:

Lombok
Spring Web
MySQL Driver
MyBatis Framework

创建接口

文件结构:
在这里插入图片描述

package com.wuyh.demo01.entity;

import lombok.Data;

@Data // 自动生成 getter/setter/toString/equals/hashCode 方法
public class User {
    private Integer id;
    private String username;
    private String password;
    private String email;
}
package com.wuyh.demo01.controller;

import com.wuyh.demo01.mapper.UserMapper;
import com.wuyh.demo01.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@CrossOrigin(origins = "*") // 用于启用跨源资源共享 (CORS),允许来自不同域的客户端访问此服务
@RestController // 用来编写处理HTTP请求并返回响应的控制器
@RequestMapping("/test")    // 用于映射 HTTP 请求到特定的处理器方法
public class UserController {
    @Autowired  // 用于自动装配 Bean
    private UserMapper userMapper;
    @GetMapping("/user")    // 用于映射 HTTP GET 请求
    public List<User> index() {
        return userMapper.findAll();
    }
}
package com.wuyh.demo01.mapper;

import com.wuyh.demo01.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import java.util.List;

@Mapper // 用来标记为 MyBatis 的 Mapper 接口,以便初始化,并执行SQL语句
public interface UserMapper {
    @Select("select * from test.user")  // SQL查询语句
    List<User> findAll();
}

打开连接 MySQL 数据库,创建并添加对应数据:

CREATE DATABASE IF NOT EXISTS test;

USE test;

DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `username` varchar(20) DEFAULT NULL,
    `password` varchar(30) DEFAULT NULL,
    `email` varchar(30) DEFAULT NULL,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

INSERT INTO `user` VALUES (1, 'admin', '123456', 'admin@163.com');

创建 application.yml 配置文件:

server:
  port: 9090

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test
    username: root
    password: 123456

运行主程序 ×××Application.java,打开“http://localhost:9090/test/user”

在这里插入图片描述

2、创建前端 HTML 页面,实现前后端连接

创建 HTML 页面:

<body>
  <div> username: <input class="username" type="text"> </div>
  <div> password: <input class="password" type="password"> </div>
  <div> email: <input class="email" type="text"> </div>
  
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
 
  <script>
    var username = document.querySelector('.username');
    var password = document.querySelector('.password');
    var email = document.querySelector('.email');

    // 2. 使用axios函数,来发送一个 HTTP GET 请求,并处理返回的结果
    axios({
        url: 'http://localhost:9090/test/user'
    }).then((result) => {
        console.log(result);
        username.value = result.data[0].username
        password.value = result.data[0].password;
        email.value = result.data[0].email;
    })
  </script>
</body>

运行前端页面:

在这里插入图片描述

[REFRENCE]
第一个接口笔记
最简单的前后端连接(新手小白)

  • 15
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
当涉及到前后端交互Java 提供了多种方式来实现。以下是一个简单的示例,演示了如何使用 Java 进行前后端交互。 首先,你需要编写一个后端接口,用于处理前端请求并返回相应的数据。这里我们使用 Spring Boot 框架来实现。 1. 创建一个新的 Spring Boot 项目,并添加必要的依赖。 2. 创建一个控制器类,用于处理前端请求和响应数据。例如,创建一个名为 `ProductController` 的类。 ```java @RestController @RequestMapping("/api/products") public class ProductController { @GetMapping public List<Product> getHotProducts() { // 处理获取热点商品的逻辑 // 返回热点商品列表 List<Product> hotProducts = productService.getHotProducts(); return hotProducts; } @PostMapping public void addProduct(@RequestBody Product product) { // 处理添加商品的逻辑 productService.addProduct(product); } } ``` 3. 创建一个名为 `Product` 的类,用于表示商品对象。 ```java public class Product { private String id; private String name; // 其他商品属性 // 构造函数、getter 和 setter 方法 } ``` 4. 在主类 `Application` 中启动 Spring Boot 应用。 ```java @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 这样,后端接口就完成了。接下来,你需要在前端代码中调用这些接口实现前后端交互。 1. 前端可以使用 AJAX、Fetch API 或其他 HTTP 请求库发送 GET 请求来获取热点商品列表。 ```javascript fetch('/api/products') .then(response => response.json()) .then(data => { // 处理返回的热点商品列表数据 console.log(data); }); ``` 2. 前端可以使用 AJAX、Fetch API 或其他 HTTP 请求库发送 POST 请求来添加商品。 ```javascript const product = { id: '1', name: '热点商品' // 其他商品属性 }; fetch('/api/products', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(product) }) .then(() => { // 商品添加成功后的处理 }); ``` 通过以上步骤,你可以在前后端之间实现简单的数据交互。当然,具体的实现方式还取决于你使用的框架和技术栈。以上只是一个简单的示例,你可以根据实际需求进行适当调整和扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值