dim
dim

Reputation: 1032

Spring mvc: I cant map form action url to controller action

I apologize in advance if this or a similar question has already been asked, but I could not find a suitable answer.

I have a simple form like this in EditUser.jsp (mapped to: .../admin/users/edit/{userId}):

<form action="/admin/users/edit/addRole/${user.userId}" method="POST">
    <select name="role">
        <c:forEach var="role" items="${roles}">
            <option value="${role}">${role}</option>
        </c:forEach>
    </select>
    <button type="submit" value="AddRole">Add Role</button>
</form>

And @RequestMapping like this:

@RequestMapping(value = "/admin/users/edit/addRole/${userId}", method = RequestMethod.POST)
public String addUserRole(
        Model model,
        @RequestParam("role") String role, 
        @PathVariable(value="userId") long userId) 
{
    ...

    return "redirect:/admin/users/edit/${userId}";
}

The problem is the result of the request: HTTP Status 404 - /admin/users/edit/addRole/7- "The requested resource is not available" (7 is some user id). A cannot map the POST request to the controller action. I already tried with th:action but it redirects me to the previous page .../admin/users.

Any help pointers appreciated .

Upvotes: 0

Views: 1076

Answers (2)

dim
dim

Reputation: 1032

I finally found the error - $ sign in @RequestMapping annotation. A just removе $ from annotation and from return "...url" and that's all.

Upvotes: 1

Ralph
Ralph

Reputation: 120811

I think you url is wrong. As long as you do not deploy the application in the servlets container root path, it will not work because the url is missing the applications name. So a correct url would be something like:

<form action="myAppName/admin/users/edit/addRole/${user.userId}" method="POST">

But better would been using <c:url> or <spring:url>-tag this adds the application name to the url (if the given url starts with an /)

<form action="<c:url value="/admin/users/edit/addRole/${user.userId}" />" method="POST">

for some more information have a look at this two answers:

Upvotes: 1

Related Questions