前端发送请求,后端没有接收到的可能原因

练手的项目,没有学Spring,所以踩坑了。前端用Java Swing图形界面窗口来写的,后端用的Springboot。

  • 出现的问题:写代码的时候发送的请求,后端总是返回请求失败。查了很久,没想到是请求方法不匹配造成的。
  • 代码片段如下,主要功能就是:前端给删除按钮添加一个鼠标点击时间,发送请求后,后端把数据库的对应id的数据给删掉。
    这里使用了自己写的(抄的)GetUtils工具类创建http请求,但注意这里使用的是Get方法。而导致上述问题的原因就是在后端的Controller层注解用的@DeleteMapping(“/deleteStudentById”),实际上应该用@GetMapping(“/deleteStudentById”),因为我的项目中还是要返回一个操作成功的信息给前端的。
deleteBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //获取选中的条目
                int selectedRow = table.getSelectedRow();//如果有选中的条目,则返回条目的行号,如果没有选中,那么返回-1

                if (selectedRow==-1){
                    JOptionPane.showMessageDialog(jf,"请选择要删除的条目!");
                    return;
                }

                //防止误操作
                int result = JOptionPane.showConfirmDialog(jf, "确认要删除选中的条目吗?", "确认删除", JOptionPane.YES_NO_OPTION);
                if (result != JOptionPane.YES_OPTION){
                    return;
                }

                String id = tableModel.getValueAt(selectedRow, 0).toString();

     	//这里用的Get方法
     	GetUtils.get("http://localhost:8080/test/deleteStudentById?id=" + id, new SuccessListener() {

                    @Override
                    public void success(String result) {
                        ResultInfo info = JsonUtils.parseResult(result);
                        if (info.isFlag()){
                            //删除成功
                            JOptionPane.showMessageDialog(jf,"删除成功");
                            requestData();
                        }else{
                            //删除失败
                            JOptionPane.showMessageDialog(jf,info.getMessage());
                        }

                    }
                }, new FailListener() {
                    @Override
                    public void fail() {
                        JOptionPane.showMessageDialog(jf,"网络异常,请稍后重试");
                    }
                });

            }
        });

下面是我的Controller层的一些接口,这里@GetMapping(“/deleteStudentById”)的注解原本写成了@DeleteMapping(“/deleteStudentById”),所以前后端没有匹配上。

package com.guo.getscreen.controller;

import com.guo.getscreen.dao.ResultInfo;
import com.guo.getscreen.dao.Test;
import com.guo.getscreen.dto.TestDTO;
import com.guo.getscreen.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/test")
public class TestController {
    @Autowired
    private TestService testService;

    @GetMapping("/findStudentById")
    public ResultInfo getStudentById(@RequestParam long id){

//        return Response.newSuccess(testService.getStudentById(id));
        return new ResultInfo(true,testService.getStudentById(id),"查询成功");
    }



    @GetMapping("/deleteStudentById")
    public ResultInfo deleteStudentById(@RequestParam long id){
        System.out.println("Request received to delete student with ID: " + id);
        testService.deleteStudentById(id);
       return  new ResultInfo(true, null, "删除成功");
    }


    @PutMapping("/updateStudent/{id}")
    public Response<TestDTO> updateStudent(@PathVariable long id,
                                           @RequestParam(required = false) String name,
                                           @RequestParam(required = false) String email,
                                           @RequestParam(required = false) String password){
        return Response.newSuccess(testService.updateStudentById(id, name, email,password));

    }

    @GetMapping("/findAllStudents")
    public ResultInfo findAllStudents(){
        return new ResultInfo(true,testService.findAll(),"查询成功");
    }

    @PostMapping("/addNewStudent")
    public ResultInfo addNewStudent( Test test){
        testService.addNewStudent(test);
        return new ResultInfo(true,null,"添加成功");
    }



}

其他注意事项:
前后端接口不匹配还有一些可能的原因,这里也作为搜集整理如下:
1.URL不匹配。前端URL上请求的接口写错了字母导致与后端不匹配,或者使用的注解不匹配
2. 后端没有启动,没有监听成功。

上面使用的GetUtils类的代码也附在下面:

package com.guo.getscreenui.net;

import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class GetUtils {
    //无参方式
    public static void get(String url,SuccessListener sListener,FailListener fListener) {
        getWithParams(url, new HashMap<>(),sListener,fListener);
    }

    //有参方式
    public static void getWithParams(String url, Map<String, Object> params,SuccessListener sListener,FailListener fListener) {
        CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultCookieStore(CookiesHolder.getCookieStore()).build();
        CloseableHttpResponse response = null;
        try {
            // 创建Get请求
            url = joinParam(url, params);
            HttpGet httpGet = new HttpGet(url);
            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(3000) //服务器响应超时时间
                    .setConnectTimeout(3000) //连接服务器超时时间
                    .build();
            httpGet.setConfig(requestConfig);
            // 由客户端执行(发送)Get请求
            response = httpClient.execute(httpGet);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                sListener.success(EntityUtils.toString(responseEntity));
            }

        } catch (Exception e) {
            e.printStackTrace();
            fListener.fail();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static String joinParam(String url, Map<String, Object> params) {
        if (params == null || params.size() == 0) {
            return url;
        }

        StringBuilder urlBuilder = new StringBuilder(url);
        urlBuilder.append("?");

        int counter = 0;
        for (Map.Entry<String,Object> entry : params.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            if (key == null) {
                continue;
            }

            if (counter == 0) {
                urlBuilder.append(key).append("=").append(value);
            } else {
                urlBuilder.append("&").append(key).append("=").append(value);
            }
            counter++;
        }

        return urlBuilder.toString();
    }
}

  • 5
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要让前端发送请求后,后端能够接收并查询相关数据库,你可以按照以下步骤进行操作: 1. 在前端,使用 JavaScript 或其他适合的语言编写代码,通过 AJAX 或 Fetch API 发送 HTTP 请求后端。你可以使用 `XMLHttpRequest` 对象或现代浏览器中更常用的 `fetch` 函数来发送请求。 ```javascript fetch('/api/json_api.jsp', { method: 'POST', body: JSON.stringify(data), // 可选,如果需要发送数据到后端 headers: { 'Content-Type': 'application/json' // 根据实际情况设置请求头 } }) .then(response => response.json()) .then(data => { // 处理从后端返回的数据 }) .catch(error => { // 处理请求错误 }); ``` 2. 在后端,根据你的后端技术选择合适的框架或库,例如 Go 的标准库 `net/http`、Gin、Echo 等。在你的路由处理函数中,根据请求路径和方法,编写相应的处理逻辑来接收请求。 ```go func ApiHandle(w http.ResponseWriter, r *http.Request) { // 处理请求逻辑 // 查询数据库 // ... // 将结果返回给前端 // ... } ``` 3. 在后端处理函数中,根据你的需求连接数据库,并执行相应的查询操作。具体的数据库查询操作和语法将取决于你使用的数据库类型和相关库。 ```go func ApiHandle(w http.ResponseWriter, r *http.Request) { // 连接数据库 db, err := sql.Open("mysql", "user:password@tcp(localhost:3306)/database") if err != nil { // 处理数据库连接错误 } defer db.Close() // 执行查询操作 rows, err := db.Query("SELECT * FROM table") if err != nil { // 处理查询错误 } defer rows.Close() // 处理查询结果 // ... } ``` 4. 在后端处理函数中,将查询结果转换为适当的数据格式(例如 JSON),并通过 HTTP 响应将数据发送前端。 ```go func ApiHandle(w http.ResponseWriter, r *http.Request) { // ... // 将查询结果转换为适当的数据格式,例如 JSON result := []string{"data1", "data2"} // 设置响应头 w.Header().Set("Content-Type", "application/json") // 将数据写入响应体 json.NewEncoder(w).Encode(result) } ``` 这些是实现前端发送请求后,后端接收并查询相关数据库的基本步骤。根据你使用的具体技术和需求,可能会有一些细微的差异。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值