Uncaught SyntaxError: Unexpected token < - java

I am using ajaxupload.js from here and I see the file doing the upload work alright. But I am getting <pre style="word-wrap: break-word; white-space: pre-wrap;">{"id":"006","path":"006.png"}</pre> in the response.
I think the response should be just {"id":"006","path":"006.png"} but for some reasons it got wrapped around <pre> and hence the Uncaught SyntaxError: Unexpected token <.
I am using spring mvc 3, tomcat. I am using java.io.Writer to write the response as writer.write(json.toString());
Could someone help me understand this error and how to resolve it?
Thanks.
UPDATE:
CODE:
<form id="app-form" class="cols" action="#" method="POST">
<fieldset class="w50">
<!-- set of form fields -->
</fieldset>
<fieldset class="w50">
<button id="uploadButton" class="csbutton-grey" >Upload</button>
<ul id="locationImages"></ul>
</fieldset>
<div style="float: left;">
<button type="submit" class="cool-button">Submit</button>
</div>
</form>
$(document).ready(function(){
var button = $('#uploadButton'), interval;
new AjaxUpload(button, {
action: 'uploadImage',
name: 'qqfile',
responseType: "json",
onSubmit : function(file, ext){
this.disable();
console.log("file - " + file);
console.log("ext - " + ext);
if (! (ext && /^(jpg|png|jpeg|gif)$/.test(ext))){
alert('Error: invalid file extension');
return false;
}
else {
$.ajax({
type:"GET",
url:"file",
data:'file='+file,
success:function(data, textStatus, jqXHR){
console.log(jqXHR.status);
console.log(data);
},
error:function(jqXHR, textStatus, errorThrown) {
console.log(jqXHR.status);
},
});
}
},
onComplete: function(file, response){
this.enable();
console.log("file - " + file);
console.log("response.id - " + response.id + ", response.path - " + response.path);
$('<li></li>').appendTo('#locationImages').text(file);
}
});
});

Have you set the responseType property as json in AjaxUpload?

If you want to send JSON to the client, use Jackson. Spring MVC had native support for it. Create a bean class like this:
public class Result{
private String id;
private String path;
public Result(String id, String path){
this.id=id;this.path=path;}
public Result(){}
// add getters and setters
}
Now create your controller method like this
#ResponseBody // this is important
#RequestMapping("/path/to/mapping")
public Result someMethodName(SomeParameter param1, SomeParameter param2){
// do something here
return new Result(id, path);
}
As long as you have Jackson on your classpath and have configured your Spring app through <mvc:annotation-config />, this will automatically serialize your response Object to correct JSON (including correct mime type)

Related

Spring boot + Thymeleaf + ajax cannot send VO or DTO Controller

I try to send form data through thymeleaf + ajax to Java Controller.
But at ReplyDto, can't receive data.
This is my code.
Themeleaf, Ajax .html
function insertReply() {
$.ajax({
type: 'POST',
url: '/reply/insertReply',
data: $("#replyForm").serialize(),
contentType: "application/json",
success: function(data) {
alert("test");
},
error: function(request, status, error) {
alert("Error : " + error + "\nStatus : " + status + "\nRequest : " + request);
}
});
}
<form id="replyForm" th:object="${replyDto}" th:method="post">
<input type="hidden" th:field="${post.postNo}" th:value="${post.postNo}">
<input class="form-control" type="text" th:field="*{replyTitle}" placeholder="replyTitle">
<textarea class="form-control" th:field="*{replyContent}" placeholder="insert" id="replyContentData" style="height: 100px"></textarea>
<button class="btn btn-primary" id="replyInsertButton" type="button" onclick='insertReply()'>댓글 입력</button>
</form>
ReplyDto.java
private int replyNo;
private String replyTitle;
private String replyContent;
private int postNo;
ReplyContoller.java
#PostMapping("/insertReply")
public int insertReply(ReplyDto replyDto) {
System.out.println(replyDto.getPostNo());
System.out.println(replyDto.getReplyTitle());
System.out.println(replyDto.getReplyContent());
return replyService.insertReply(replyDto);
}
Controller has annotation #RestController.
At console, log 0, null, null each postNo, replyTitle, replyContent.
How can I get form data to Controller?
Please help!
Your are missing #RequestBody
public int insertReply(#RequestBody ReplyDto replyDto) { ...
$("#replyForm").serialize() turns form into query string. You need valid JSON
You should probably go for a solution like this: Spring RestController POST accepting a basic HTML form
If you insist on proceeding with your current solution:
Start with verifying controller in Postman when fixed missing #RequestBody.
Converting form to JSON:
https://www.learnwithjason.dev/blog/get-form-values-as-json/
https://medium.com/#mwakatumbula_/code-15ecdb18c2ef
https://css-tricks.com/snippets/jquery/serialize-form-to-json/

Can't Pass MultipartFile through Ajax JAVA [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I'm trying to send a file from my jsp to controller via ajax, im getting EXCEPTION:Null Error, below is my code:
Controller:
#RequestMapping(value = "/schedulebatch",method =
RequestMethod.POST,params="insertData")
public #ResponseBody String addBatch(#RequestParam(
#RequestParam(value="upfile",required=false) MultipartFile upfile) throws
Exception { if(!upfile.isEmpty()){
System.out.println("test1");}
View:
$("#submit-btn").click(function(){
var upfile = document.getElementById('upfile').enctypeVIEW;
alert('test');
if(batchname==null || fromdate == null || partners == null || interval ==
null){
$('#insertmodalalert').empty();
$('#insertmodalalert').append('<div class="alert alert-info"><strong
>NOTICE |</strong> Please fill out the required form. </div>');
$('#alertMod').modal();
$('#okbtn').click(function(){
window.location.reload(true);
});
}
else{
$.ajax({
type: "POST",
url: "schedulebatch?insertData",
data: {"upfile" : upfile},
success: function(response){
// alert('test');
$('#insertmodalalert').empty();
$('#insertmodalalert').append('<div class="alert alert-
info"><strong >NOTICE |</strong> '+response+' </div>');
$('#alertMod').modal();
$('#okbtn').click(function(){
$('#alertMod').modal('hide');
window.location.reload(true);
});
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
// alert('test');
// Display the specific error raised by the server
(e.g. not a
// valid value for Int32, or attempted to divide by
zero).
$('#insertmodalalert').append('<div class="alert
alert-danger"><strong >NOTICE |</strong> '+err.Message+'</div>');
$('#activateMod').modal();
$('#okbtn').click(function(){
$('#alertMod').modal('hide');
window.location.reload(true);
});
}
});
//alert("Test");
}
HTML:
File to upload: <input class="form-control" type="file" name="upfile"
accept=".csv" id="upfile">
<button type="submit" class="btn btn-success" id="submit-
btn">Submit</button>
I narrowed down the code to the only thing that gives me error, thanks in advance. It gets the Multipart file successfully but im not sure why it gives a null exception error
When I uploading files with my RestController in Spring Boot I used like below and everything is fine :
#PostMapping
public ResponseEntity<User> post(UserCreateRequest request, #RequestPart("file") MultipartFile file) throws IOException {
ftpService.uploadPhoto(file.getOriginalFilename(), file.getInputStream());
return ResponseEntity.ok(userService.create(request));
}
So may be you can try to change your code as below:
#RequestMapping(value = "/schedulebatch",method =
RequestMethod.POST,params="insertData")
public #ResponseBody String addBatch(#RequestPart("upfile") MultipartFile upfile) throws Exception {
if(!upfile.isEmpty()){
System.out.println("test1");
}
}
And your content-type should be multipart/form-data so I added an example html&ajax form request:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script>
$(document).ready(function () {
$('#btnSubmit').click( function(e) {
e.preventDefault();
var form = $('#my-form')[0];
var data = new FormData(form);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "http://localhost:8080/schedulebatch",
data: data,
processData: false,
contentType: false,
cache: false,
timeout: 600000,
success: function (data) {
alert("success")
},
error: function (e) {
alert("ERROR : ", e);
}
});
});
});
</script>
</head>
<body>
<form method="POST" enctype="multipart/form-data" id="my-form">
<input type="file" name="upfile"/><br/><br/>
<input type="submit" value="Submit" id="btnSubmit"/>
</form>
</body>
</html>

Sending Cyrillic string from jsp to java class trough ajax with correct encoding

I am having a few input fields in my jsp page that get a Cyrillic input which I am then upon pressing a button trying to send to this java method using ajax. The strings in the java method end up being gibberish.
The fields in the jsp page:
<div class="span1">
<form:label cssClass="control-label" path="">
<spring:message code="web.messages.someMessage" />
</form:label>
<form:input cssClass="input-block-level" path="" id="articleId" />
</div>
<div class="span1">
<label> </label>
<button type="button" id="search-btn" class="btn" >
<spring:message code="web.messages.buttonMessage" />
</button>
</div>
The ajax in the script:
$("#search-btn").on("click", function(e) {
e.preventDefault();
showDialog("${pageContext.request.contextPath}");
});
function showDialog(baseContext) {
var article = $('#articleId').val().replace(/\s+/g, "");
if (article) {
article = "?article=" + article;
}
$.ajax({
type : "GET",
url : "${pageContext.request.contextPath}/sync/getFilter"
+ article,
success : function(data) {
onClickTable();
}
});
}
This is part of the java method, where the value turns into gibberish:
#RequestMapping(value = "/getFilter", method = RequestMethod.GET)
public #ResponseBody ModelAndView getFilter(HttpServletRequest request) {
String article = (String) request.getParameter("article");
.
.
Fixed the problem by putting the information in a JSON and sending it like that.
The changed made:
The ajax in the script part of the jsp:
function showDialog(baseContext) {
var article = $('#articleId').val().replace(/\s+/g, "");
var data = {
"article": $('#articleId').val().replace(/\s+/g, ""),
// other keys and values
"lastKey": $('#lastValueId').val().replace(/\s+/g, "")
}
$.ajax({
type : "POST",
url : "${pageContext.request.contextPath}/sync/getFilter",
data: data,
success : function(data) {
onClickTable();
}
});
}
The java method handling the data:
#RequestMapping(value = "/getFilter", method = RequestMethod.POST)
public #ResponseBody ModelAndView getFilter(SomeObject receivedData) {
String article = receivedData.getArticle();
// rest of the method
Where SomeObject is an object containing the values that we receive in the data with proper set and get methods for them.

Communicate with backend method through Ajax

I am trying to communicate with a method using Ajax and AngularJS but I'm not getting a response and the alert outputs undefined.
Index.cshtml
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body ng-app="myApp">
// Displaying the table is working
<div>
<table class="table" ng-controller="UpdateController">
<tr>
<th>Id</th>
<th>Name</th>
<th>Country</th>
</tr>
<tr ng-repeat="c in cities">
<td>{{c.Id}}</td>
<td>{{c.City1}}</td>
<td>{{c.Country}}</td>
</tr>
</table>
</div>
// Here I add the controller for adding records -->
<div ng-controller="AddRecord">
<form id="form1" ng-submit="send()">
<table>
<tr>
<td>City: </td>
<td>
<input type="text" id="txtCity" ng-model="addCity" />
</td>
</tr>
<tr>
<td>Country: </td>
<td>
<input type="text" id="txtCountry" ng-model="addCountry" />
</td>
</tr>
<tr>
<td>
<input type="submit" id="btnSubmit" value="Submit" />
</td>
</tr>
</table>
</form>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('UpdateController', function ($scope, $http) {
$http.get("http://localhost:50366/api/cities")
.success(function (response) { $scope.cities = response });
});
app.controller('AddRecord', function ($scope, $http) {
// Function responsible for communicating with backend
$scope.send = function () {
$.ajax({
type: "POST",
url: "AddCity.asmx.cs/PostCity",
data: "{'city':'" + $scope.addCity + "','country':'" + $scope.addCountry + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
},
error: function (msg) {
alert(msg.d);
}
});
//Here is one I tried using text as the datatype:
$.ajax({
type: "POST",
url: "AddCity.asmx/PostCity",
data: "city=" + $scope.addCity + "&country=" + $scope.addCountry,
dataType: "text",
success: function (msg) {
alert(msg.d);
},
error: function (msg) {
alert(msg.d);
}
});
};
});
</script>
</body>
</html>
AddCity.asmx with the method I'm trying to access
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using AngularWebApi.Models;
using AngularWebApi.Controllers;
namespace AngularWebApi.Views
{
/// <summary>
/// Summary description for AddCity
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class AddCity : System.Web.Services.WebService
{
[WebMethod]
public string PostCity(string city, string country)
{
City newCity = new City();
newCity.City1 = city;
newCity.Country = country;
//Eventually I want to add the city to the database
CitiesController controller = new CitiesController();
controller.PostCity(newCity);
return "Posted!";
}
}
}
Index.cshtml resides in Views/Home and AddCity.asmx resides in Views. I tried to use url: "../AddCity.asmx/PostCity" as well.
Edit
I quickly created a new project and set it up, the exact same thing is happening, here are the steps:
New web api project
New ADO.net Entity data model and link it to my DB
New Web API 2 controller with actions using Entity Framework passing the table from DB and entity I got from pevious step.
Then I edit Index.cshtml to show the XML from API/CITIES as a table. This time I added my service in the root of the project and just trying to call the auto created HelloWorld with the $.ajax POST function.
I do see a warning in the FF error console. Literal translation from dutch: Cross-Origin-Request blocked: ....
Furthermore the error is triggered within the ajax call. The WebService is not being reached afaik.
This is the complete reply I get when I click the button:
<!DOCTYPE html>
<html>
<head>
<title>The resource cannot be found.</title>
<meta name="viewport" content="width=device-width" />
<style>
body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;}
p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px}
b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px}
H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red }
H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon }
pre {font-family:"Consolas","Lucida Console",Monospace;font-size:11pt;margin:0;padding:0.5em;line-height:14pt}
.marker {font-weight: bold; color: black;text-decoration: none;}
.version {color: gray;}
.error {margin-bottom: 10px;}
.expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; }
#media screen and (max-width: 639px) {
pre { width: 440px; overflow: auto; white-space: pre-wrap; word-wrap: break-word; }
}
#media screen and (max-width: 479px) {
pre { width: 280px; }
}
</style>
</head>
<body bgcolor="white">
<span><H1>Server Error in '/' Application.<hr width=100% size=1 color=silver></H1>
<h2> <i>The resource cannot be found.</i> </h2></span>
<font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif ">
<b> Description: </b>HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
<br><br>
<b> Requested URL: </b>/Home/MyWebService.asmx/HelloWorld<br><br>
<hr width=100% size=1 color=silver>
<b>Version Information:</b> Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18408
</font>
</body>
</html>
<!--
[HttpException]: A public action method 'MyWebService.asmx' was not found on controller 'AngularTutorial.Controllers.HomeController'.
at System.Web.Mvc.Controller.HandleUnknownAction(String actionName)
at System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult](IAsyncResult asyncResult, Object tag)
at System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag)
at System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult)
at System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult](IAsyncResult asyncResult, Object tag)
at System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag)
at System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult)
at System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult)
at System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult](IAsyncResult asyncResult, Object tag)
at System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag)
at System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)
at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
-->
Edit
The POST method in the controller:
// POST: api/Cities
[ResponseType(typeof(City))]
public IHttpActionResult PostCity(City city)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Cities.Add(city);
db.SaveChanges();
return CreatedAtRoute("DefaultApi", new { id = city.Id }, city);
}
hmmm, I think I got it: you try to create a new POST-Method, but according to the tutorial, there is already a POST-Method in the City-Controller:
By clicking on Add, we are able to create the Cities Web API using the scaffolding. The created controller class will have a Web API for all the CRUD operations on the city table.
that means you simply need to send your ajax-call to http://localhost:50366/api/cities:
$.ajax({
type: "POST",
url: "http://localhost:50366/api/cities",
data: "{'country':'" + country + "','name':'" + cityName + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
},
error: function (msg) {
alert(msg.d);
}
});
Make sure you only have 1 web application running, so you can avoid unnecessary problems.
btw. I'm not sure, if the controller will accept json maybe you need to send the data as xml...
EDIT:
I updated the json data. Your city-object has 3 properties: country, id and name. If you send a POST request you are about to create a new object, so you don't need to send the id.
For PUT and DELETE (if you want to implement this functions) you will need to add the idto the url:
http://localhost:50366/api/cities/:id
EDIT2:
ok, the xml should looks like this:
data: "<City><Country>" + country + "</Country><Name>" + cityName + "</Name></City>",
don't forget to change:
contentType: "application/xml; charset=utf-8",
dataType: "xml",
Don't use ajax, even if it worked you would still have problems because $.ajax calls are not in Angular.js context and you would have to manually $scope.apply() the returned value. Use angular $http service instead. You can find how to use it in official documentation. It is very flexible, supports all request methods, query params, request body, etc... also supports interceptors to handle all your requests. All $http calls return promise by default (also use .then() handler instead of success and failure handlers).

java.io.EOFException: No content to map to Object due to end of input Spring MVC Jackson Processor

I am using Spring MVC and JSP to send JSON to Spring MVC Controller. Actually, my JSON works for 1 method but does not work for another and I don't understand why. The code is below:
JSP - index.jsp
<%#page language="java" contentType="text/html"%>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$('#myForm').submit(function() {
var form = $( this ),
url = form.attr('action'),
userId = form.find('input[name="userId"]').val(),
dat = JSON.stringify({ "userId" : userId });
$.ajax({
url : url,
type : "POST",
traditional : true,
contentType : "application/json",
dataType : "json",
data : dat,
success : function (response) {
alert('success ' + response);
},
error : function (response) {
alert('error ' + response);
},
});
return false;
});
});
</script>
<script type="text/javascript">
$(function() {
$('#emailForm').submit(function() {
var form = $( this ),
url = form.attr('action'),
from = form.find('input[name="from"]').val(),
to = form.find('input[name="to"]').val(),
body = form.find('input[name="body"]').val(),
subject = form.find('input[name="subject"]').val(),
fileName = form.find('input[name="fileName"]').val(),
location = form.find('input[name="location"]').val(),
dat = JSON.stringify({ "from" : from,"to" : to,"body" : body,"subject" : subject,"fileName" : fileName,"location" : location });
$.ajax({
url : url,
type : "GET",
traditional : true,
contentType : "application/json",
dataType : "json",
data : dat,
success : function (response) {
alert('success ' + response);
},
error : function (response) {
alert('error ' + response);
},
});
return false;
});
});
</script>
</head>
<body>
<h2>Application</h2>
<form id="myForm" action="/application/history/save" method="POST">
<input type="text" name="userId" value="JUnit">
<input type="submit" value="Submit">
</form>
<form id="emailForm" action="/application/emailService/sendEmail" method="GET">
<input type="text" name="from" value="name#localhost.com">
<input type="text" name="to" value="user#localhost.com">
<input type="text" name="body" value="JUnit E-mail">
<input type="text" name="subject" value="Email">
<input type="text" name="fileName" value="attachment">
<input type="text" name="location" value="location">
<input type="submit" value="Send Email">
</form>
</body>
</html>
The 1st form works correctly and is deserilized in Spring MVC. A sample of that code is:
#Controller
#RequestMapping("/history/*")
public class HistoryController {
#RequestMapping(value = "save", method = RequestMethod.POST, headers = {"content-type=application/json"})
public #ResponseBody UserResponse save(#RequestBody User user) throws Exception {
UserResponse userResponse = new UserResponse();
return userResponse;
}
For the 2nd form I am getting exceptions:
#Controller
#RequestMapping("/emailService/*")
public class EmailController {
#RequestMapping(value = "sendEmail", method = RequestMethod.GET, headers = {"content-type=application/json"})
public void sendEmail(#RequestBody Email email) {
System.out.println("Email Body:" + " " + email.getBody());
System.out.println("Email To: " + " " + email.getTo());
}
}
Below is the stack trace:
java.io.EOFException: No content to map to Object due to end of input
org.codehaus.jackson.map.ObjectMapper._initForReading(ObjectMapper.java:2022)
org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:1974)
org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1331)
org.springframework.http.converter.json.MappingJacksonHttpMessageConverter.readInternal(MappingJacksonHttpMessageConverter.java:135)
org.springframework.http.converter.AbstractHttpMessageConverter.read(AbstractHttpMessageConverter.java:154)
org.springframework.web.bind.annotation.support.HandlerMethodInvoker.readWithMessageConverters(HandlerMethodInvoker.java:633)
org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolveRequestBody(HandlerMethodInvoker.java:597)
org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolveHandlerArguments(HandlerMethodInvoker.java:346)
org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:171)
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:426)
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:414)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
I have tried using the POST too, but still the same problem. I need to use JSP to send JSON data to the Spring MVC Controller.
I am not sure where the problem is.
beans.xml
<context:component-scan base-package="com.web"/>
<mvc:annotation-driven/>
<context:annotation-config/>
Any ideas?
EDIT
public class Email implements Serializable {
private String from;
private String to;
private String body;
private String subject;
private String fileName;
private String location;
public Email() {
}
// Getters and setters
}
JSON sent is in form2 which is #emailForm.
You should check if you have set "content-length" header.
I ran into the same problem, but I used curl to verify the server side function.
The initial data section in my curl command is
-d "{'id':'123456', 'name':'QWERT'}"
After I changed the command to
-d '{"id":"123456", "name":"QWERT"}'
then it worked.
Hope this gives some hints.
I had this problem when I tried to use POST method with path parameter, but I forgot to put '#PathParam("id") Integer id', I just had 'Integer id ' in parameters.

Categories

Resources