一切困难都能打倒我 2024-10-14 08:56 采纳率: 87.1%
浏览 7

SpringMVC练习搜索功能415错误

一个简单的搜索功能,点击搜索总是415,找不到解决方法

@Controller
public class BookController {
    private final BookService bookService = new BookService();

    @GetMapping("/")
    public String index() {
        return "index";
    }

 @PostMapping("/search")
 public List<Book> search(@RequestBody Map<String, String> params) {
     System.out.println("Received params: " + params); // 打印接收到的参数
     String name = params.get("name");
     String author = params.get("author");
     String publisher = params.get("publisher");
     return bookService.searchBooks(name, author, publisher);
 }

    @PostMapping("/borrow")
    public String borrow(@RequestParam int id) {
        bookService.borrowBook(id);
        return "redirect:/";  // 重定向到首页
    }

    @PostMapping("/return")
    public String returnBook(@RequestParam int id) {
        bookService.returnBook(id);
        return "redirect:/";  // 重定向到首页
    }
}

前端代码

<%@ page import="java.util.ArrayList" %>
<%@ page import="example.springmvcdemo01.Book" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>图书借阅系统</title>

    <script>
        function toggleBorrowReturn(bookId) {
            const button = document.getElementById("btn-" + bookId);
            if (button.innerText === "借阅") {
                button.innerText = "归还";
            } else {
                button.innerText = "借阅";
            }
        }
        
        async function searchBooks() {
            const name = document.getElementById("name").value;
            const author = document.getElementById("author").value;
            const publisher = document.getElementById("publisher").value;

            const response = await fetch('/search', {
                method: 'POST', // 确保与后端一致
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ name, author, publisher })
            });

            if (response.ok) {
                const books = await response.json();
                displayBooks(books);
            } else {
                const errorText = await response.text(); // 获取错误信息
                alert(`查询失败:${errorText}`);
            }
        }

        function displayBooks(books) {
            const bookList = document.getElementById("bookList");
            bookList.innerHTML = ""; // 清空之前的内容

            if (books.length === 0) {
                bookList.innerHTML = "<li>没有找到相关图书。</li>";
                return;
            }

            books.forEach(book => {
                const li = document.createElement("li");
                li.innerHTML = `${book.name} - ${book.author} - ${book.publisher} <button id="btn-${book.id}" onclick="toggleBorrowReturn(${book.id})">${book.isBorrowed ? '归还' : '借阅'}</button>`;
                bookList.appendChild(li);
            });
        }
    </script>
</head>

<body>
<h1>图书借阅系统</h1>
<div>
    <input type="text" id="name" placeholder="图书名称" />
    <input type="text" id="author" placeholder="图书作者" />
    <input type="text" id="publisher" placeholder="出版社" />
    <button onclick="searchBooks()">查询</button>
</div>
<h3>推荐书目</h3>
<div id="bookList">
    <ul>
        <%
            // 创建 Book 对象列表
            ArrayList<Book> books = new ArrayList<>();
            books.add(new Book(1, "Java 编程思想", "Bruce Eckel", "电子工业出版社", false));
            books.add(new Book(2, "Effective Java", "Joshua Bloch", "机械工业出版社", true));
            books.add(new Book(3, "深入理解 Java 虚拟机", "周志明", "电子工业出版社", false));

            // 遍历书籍列表动态生成列表项
            for (Book book : books) {
        %>
        <li>
            <%= book.getName() %> - <%= book.getAuthor() %> - <%= book.getPublisher() %>
            <button id="btn-<%= book.getId() %>" onclick="toggleBorrowReturn(<%= book.getId() %>)">
                <%= book.isBorrowed() ? "归还" : "借阅" %>
            </button>
        </li>
        <%
            }
        %>
    </ul>
</div>
</body>
</html>


img

  • 写回答

2条回答 默认 最新

  • 何心而为殇 2024-10-14 09:16
    关注

    前端代码这个:JSON.stringify({ name, author, publisher });感觉应该是前段传参的格式不对,导致后端接受不到参数。参考这个看看:https://www.cnblogs.com/frank-link/p/15041633.html

    评论

报告相同问题?

问题事件

  • 创建了问题 10月14日

悬赏问题

  • ¥15 报酬10000,做一个简单的换汇网站
  • ¥15 关于#vue.js#的问题:word excel和ppt预览问题语言-javascript)
  • ¥15 Apache显示系统错误3该如何解决?
  • ¥30 uniapp小程序苹果手机加载gif图片不显示动效?
  • ¥20 js怎么实现跨域问题
  • ¥15 C++dll二次开发,C#调用
  • ¥15 请教,如何使用C#加载本地摄像头进行逐帧推流
  • ¥15 Python easyocr无法顺利执行,如何解决?
  • ¥15 为什么会突然npm err!啊
  • ¥15 java服务连接es读取列表数据,服务连接本地es获取数据时的速度很快,但是换成远端的es就会非常慢,这是为什么呢