首页 > 解决方案 > 使用 Spring MVC 提交表单时出错 - HTTP 状态 404

问题描述

我正在尝试制作一个简单的表单并使用 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

员工主页.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";
    }

} 

我认为问题在于设置actionon .jsp 页面和 on@RequestMapping(value = "/addEmployee", method = RequestMethod.POST)方法,但我不知道出了什么问题。

编辑:问题已解决

改变

<form:form method="post" action="/addEmployee" modelAttribute="employee">

<form:form method="post" action="addEmployee" modelAttribute="employee">

标签: javahtmlspringspring-mvc

解决方案


我认为问题可能出在行动上URL

你可以这样尝试

<form:form method="POST" action="${pageContext.request.contextPath}/addEmployee" modelAttribute="employee">

或硬编码baseUrl(如果有的话)

<form:form method="POST" action="baseContextPath/addEmployee" modelAttribute="employee">

您可以在此处参考此内容以获取更多详细信息和工作代码


推荐阅读