SpringMVC写一个简单的书籍搜索功能,借阅功能,但是一直415
代码;
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