一切困难都能打倒我 2024-10-14 14:25 采纳率: 87.1%
浏览 6
已结题

SpringMVC搜索功能415问题

SpringMVC写一个简单的书籍搜索功能,借阅功能,但是一直415

img

img

代码;
index.jsp


```java
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>图书借阅系统</title>
    <script>
        async function searchBooks() {
            const name = document.getElementById("name").value;
            const author = document.getElementById("author").value;
            const publisher = document.getElementById("publisher").value;
            const params = { name, author, publisher };

            // 输出查询参数
            console.log(params);

            const response = await fetch('/search', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(params)
            });

            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}
                    - 借阅状态: ${book.isBorrowed ? '已借阅' : '未借阅'}
                    - 归还状态: ${book.isReturned ? '已归还' : '未归还'}
                    <button onclick="borrowBook(${book.id})">借阅</button>`;
                bookList.appendChild(li);
            });
        }

        async function borrowBook(id) {
            const response = await fetch(`/borrow?id=${id}`, {
                method: 'POST'
            });

            if (response.ok) {
                alert('借阅成功!');
            } else {
                alert('借阅失败!');
            }
        }
    </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>

<div id="bookList">
    <ul></ul>
</div>
</body>
</html>


Book

```java
package example.springmvcdemo01;

public class Book {
    private int id;
    private String name;
    private String author;
    private String publisher;
    private boolean isBorrowed;

    public Book(int id, String name, String author, String publisher,boolean isBorrowed) {
        this.id = id;
        this.name = name;
        this.author = author;
        this.publisher = publisher;
        this.isBorrowed = false;
    }

    // Getter和Setter

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public String getPublisher() {
        return publisher;
    }

    public void setPublisher(String publisher) {
        this.publisher = publisher;
    }

    public boolean isBorrowed() {
        return isBorrowed;
    }

    public void setBorrowed(boolean borrowed) {
        isBorrowed = borrowed;
    }
}

BookService

package example.springmvcdemo01;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class BookService {
    private List<Book> books;

    public void  BookService() {
        books = new ArrayList<>();
        books.add(new Book(1, "红楼梦", "曹雪芹", "人民邮电出版社",false));
        books.add(new Book(2, "西游记", "吴承恩", "吉林出版社",false));
        books.add(new Book(3, "三国演义", "罗贯中", "人民邮电出版社",false));
        books.add(new Book(4, "水浒传", "施耐庵", "吉林出版社",false));
        // 继续添加
    }

    /*搜索书籍*/
    public List<Book> searchBooks(String name, String author, String publisher) {
        List<Book> result = new ArrayList<>();

        for (Book book : books) {
            boolean matches = false;

            if (name != null && !name.isEmpty() && book.getName().contains(name)) {
                matches = true;
            }
            if (author != null && !author.isEmpty() && book.getAuthor().contains(author)) {
                matches = true;
            }
            if (publisher != null && !publisher.isEmpty() && book.getPublisher().contains(publisher)) {
                matches = true;
            }

            if (matches) {
                result.add(book);
            }
        }

        return result;
    }

    /*借出*/
    public void borrowBook(int id) {
        Book book = books.stream().filter(b -> b.getId() == id).findFirst().orElse(null);
        if (book != null && !book.isBorrowed()) {
            book.setBorrowed(true);
        }
    }

    /*归还*/
    public void returnBook(int id) {
        Book book = books.stream().filter(b -> b.getId() == id).findFirst().orElse(null);
        if (book != null && book.isBorrowed()) {
            book.setBorrowed(false);
        }


    }
}


BookControl

package example.springmvcdemo01;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

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

@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 "借阅成功!";  // 返回借阅成功的消息
    }

    @PostMapping("/return")
    public String returnBook(@RequestParam int id) {
        bookService.returnBook(id);
        return "还书成功!";  // 返回还书成功的消息
    }
}

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>example</groupId>
    <artifactId>springMVCdemo01</artifactId>
    <version>1.0-SNAPSHOT</version>
    <name>springMVCdemo01</name>
    <packaging>war</packaging>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.target>1.8</maven.compiler.target>
        <maven.compiler.source>1.8</maven.compiler.source>
        <junit.version>5.9.2</junit.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
<!--        项目配置文件-->
        <!--web项目改造成MVC,导入springmvc坐标-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.39</version>
        </dependency>
<!--JSON-->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.13.1</version>
        </dependency>


    </dependencies>


</project>


web.xml


```java
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <!--Tomcat配置文件-->
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name><!--配置及文件名-->
            <param-value>classpath:spring-mvc.xml</param-value> <!-- 根据实际情况修改 -->
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern> <!-- 所有请求 -->
    </servlet-mapping>

</web-app>

spring-mvc.xml

```java
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!-- 启用注解支持 -->
    <context:component-scan base-package="example.springmvcdemo01" /> <!-- 修改为你的包名 ,扫描这个包-->

   <!-- <mvc:default-servlet-handler/>-->

    <!--视图-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/webapp" />
        <property name="suffix" value=".jsp" />
    </bean

  • 写回答

1条回答 默认 最新

  • 关注

    下午好🌅🌅🌅
    本答案参考ChatGPT-3.5

    415是SpringMVC中的400 Bad Request异常。这是一个由服务器产生的错误,通常是因为客户端发送的数据格式不正确。

    以下是一些解决这个问题的方法:

    1. 更改请求头:在index.jsp中,你需要检查请求头是否正确,例如,URL是否使用了正确的协议(http或https),请求方法是否正确等。

    2. 调整数据编码:如果你的请求体中包含的是JSON格式的数据,那么你需要确保你的数据已经进行了适当的编码。这可以通过在前端添加一个json_encode()函数来实现。

    3. 更改数据库连接配置:如果请求体中包含的是XML格式的数据,那么你需要确保你的数据库连接配置已经正确设置。

    下面是一个示例:

    // 修改请求头
    formEnv.put("accept-language", "zh-CN");
    
    // 更改数据库连接配置
    connectionManager.initConfig("jdbc:mysql://localhost/mydatabase", "root", "password");
    
    // 改变请求体编码
    String jsonData = "{\"name\":\"小明\", \"age\":20}";
    ObjectMapper mapper = new ObjectMapper();
    String encodedJsonData = mapper.writeValueAsString(jsonData);
    
    // 创建POST请求
    try {
        POST httpPostRequest = new HttpPost("http://localhost:8080/search");
        httpPostRequest.setHeader("Accept", "application/json");
        httpPostRequest.setHeader("Content-Type", "application/json; charset=UTF-8");
        httpPostRequest.setEntity(encodedJsonData);
    
        // 发送请求
        response = httpClient.execute(httpPostRequest);
        
        // 防止415错误
        response есть谷歌
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 10月24日
  • 已采纳回答 10月16日
  • 创建了问题 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就会非常慢,这是为什么呢