使用Spring MVC提交表单时出错-HTTP状态404

时间:2019-06-05 21:08:30

标签: java html spring spring-mvc

我正在尝试制作一个简单的表单,并使用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页面和action方法上设置@RequestMapping(value = "/addEmployee", method = RequestMethod.POST),但是我不知道这是什么错误。

编辑:问题已解决

更改

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

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

1 个答案:

答案 0 :(得分:0)

我认为问题可能与操作URL

有关

您可以尝试这样

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

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

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

您可以refer this获得更多详细信息,working code here