【发布时间】:2019-10-21 09:50:42
【问题描述】:
我正在尝试制作一个简单的表单并使用 Spring MVC 提交它。我尝试了几种方法,所有页面都映射到web.xml,我检查它使用简单页面导航。但是当单击按钮时,我收到以下错误:
HTTP Status 404 – Not found
Type Status Report
Message /addEmployee
Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
Apache Tomcat/9.0.20
employeeHome.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="form" 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>
<title>Cadastro</title>
</head>
<body>
<h1>Cadastro</h1>
<form:form method="POST" action="/addEmployee" modelAttribute="employee">
<table>
<tr>
<td><form:label path="name">Name</form:label></td>
<td><form:input path="name"/></td>
</tr>
<tr>
<td><form:label path="id">ID</form:label></td>
<td><form:input path="id"/></td>
</tr>
<tr>
<td><form:label path="contactNumber">Contact Number</form:label></td>
<td><form:input path="contactNumber"/></td>
</tr>
<tr>
<td><input type="submit" value="Submit"/></td>
</tr>
</table>
</form:form>
</body>
</html>
控制器:SpringMVCHelloWorld
@Controller
public class SpringMVCHelloWorld {
// Employee
@GetMapping("/employeeHome")
public ModelAndView showForm() {
return new ModelAndView("employeeHome", "employee", new Employee());
}
@RequestMapping(value = "/addEmployee", method = RequestMethod.POST)
public String addEmployee(@ModelAttribute("employee") Employee employee, BindingResult result, ModelMap model) {
if(result.hasErrors()) {
return "error";
}
model.addAttribute("name",employee.getName());
model.addAttribute("contactNumber",employee.getContactNumber());
model.addAttribute("id", employee.getId());
return "employeeView";
}
}
我认为问题是在.jsp页面和@RequestMapping(value = "/addEmployee", method = RequestMethod.POST)方法上设置action,但我不知道有什么问题。
编辑:问题已解决
改变
<form:form method="post" action="/addEmployee" modelAttribute="employee">
到
<form:form method="post" action="addEmployee" modelAttribute="employee">
【问题讨论】:
-
试试这个
-
如果我这样做,我如何将表单提交映射到控制器上?
-
试一试,让弹簧为您施展魔法。
-
@AjayKumar 春天的魔力是:
Request method 'POST' not supported -
太棒了。我很高兴它现在为你工作。
标签: java html spring spring-mvc