Spring Mvc Rest Webservice jstl form submittion HT

2019-09-07 09:46发布

问题:

I am Using Spring Mvc Rest Webservice with JSTL form submittion.

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@ page session="false" %>
<html>
<head>
</head>
<body>

<form:form method="POST" action="rest/save" modelAttribute="employee">

<table>
<tr><td>
id &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<form:input type="text" path="id"/>
</td></tr>

<tr><td>
fname <form:input type="text" path="firstName"/>
</td></tr>

<tr><td>
lname <form:input type="text" path="lastName"/>
</td></tr>

<tr><td>
phone <form:input type="text" path="phone"/>
</td></tr>

</table>

<input type="submit" value="submit" >


</form:form>

Here is my controller function that accepts the request.

@RequestMapping(value = EmpRestURIConstants.SAVE_EMP,method =    RequestMethod.POST,consumes=MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody String setemployee(@RequestBody Employee employee){


    dataServices.setemp(employee);
        return "success";   
}

This works fine and saves the employee when i use it with ajax submit or with using RESTClient

The Error returns is.. HTTP Status 415: The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.

org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded' not supported

How Can i set the Mime type with JSTL form submittion and how can i solve the problem. Please Somebody help.

回答1:

When you're posting a form, the data are not sent as JSON, and since you have explicitly set that you're accepting only consumes=MediaType.APPLICATION_JSON_VALUE you get the 415 error. You can have all your cases covered by removing the @RequestBody and the consumes attribute, Spring MVC is smart enough to know what to do in all of your cases (form submition, RESTClient or ajax)

@RequestMapping(value = EmpRestURIConstants.SAVE_EMP,method = RequestMethod.POST)
public @ResponseBody String setemployee(Employee employee){
    dataServices.setemp(employee);
        return "success";   
}