我正在尝试使用 post 方法创建一个简单的函数。我想要的是在表单中输入并提交的任何内容 - 它应该出现在表单下方的同一页面上。然而,一旦我点击“提交”,文本就会消失。这是我的代码
Controller
@Controller
public class SearchController {
@RequestMapping(value = "/search", method = RequestMethod.GET)
public String goToSearch(Model model) {
model.addAttribute("item", new Item());
return "itemsearch";
}
@RequestMapping(value = "/search", method = RequestMethod.POST)
public String search(Item item, Model model, @RequestParam String itemId) throws IOException{
model.addAttribute("item", new Item());
return "itemsearch";
}
}
Jsp 文件
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="s" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="sf" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>Search for an item</h2>
<sf:form action="search" method="POST" modelAttribute="item">
<label>Please enter the item Id number:<sf:input type="text" name="itemId" id="itemId" path="itemId" /></label><br/>
<input type="submit" value="Submit" path="submit" />
<br> You are trying to search for Id Number: <b><h3>${item.itemId}<h3></h3></b>
</sf:form>
元素类别
public class Item {
private String itemId;
private List<String> itemDetails;
public List<String> getItemDetails() {
return itemDetails;
}
public void setItemDetails(List<String> itemDetails) {
this.itemDetails = itemDetails;
}
public String getItemId() {
return itemId;
}
public void setItemId(String itemId) {
this.itemId = itemId;
}
}
非常感谢
最佳答案
我认为您需要基本了解 Spring MVC 的工作原理。
看看这张图片:
您会看到来自客户端的传入请求(您的 POST
请求),该请求被重定向到所需的 Controller 。 Controller (您的 SearchController
)发挥了一些商业魔法并将模型返回到前端 Controller 。该模型默认为空。您可以通过 model.addAttribute("someId", someObject);
添加应渲染的对象
传递的模型现在由 View 模板 ( itemsearch
) 处理,它将模板和模型连接到传递给客户端的(静态)响应。
问题来了。您正在传递 Controller new Item()
到模型。它是一个空对象,没有任何值(也没有您想要在表单提交后呈现的 id
)。因此,您的 JSP 页面上可能不会显示任何内容。只需将找到的项目或您请求的项目传递给模型即可。
关于java - Spring MVC表单提交,在同一页面填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40603838/