Spring Boot: Ambiguous handler methods mapped for HTTP path 'http://localhost:8080/error' - ajax

Everytime I used ajax for posting, I'm getting this error but the passing of data works successfully. Some said that it is because of my return statement. I also don't have any mapping for /error. This is one of my work that causes this error.
AJAX:
$.ajax
({
type: 'post',
url: '/SaveDependent',
data:
{
dependent_id: 0,
reference_no: referenceNo,
dependent_name: dNameValue[i],
dependent_dob: dDobValue[i],
dependent_gender: dGenderValue[i],
dependent_occupation: dOccupationValue[i],
dependent_relationship: dRelationshipValue[i],
dependent_beneficiary: dBeneficiaryValue[i]
},
success: function (response)
{
alert("success");
},
});
CONTROLLER:
#RequestMapping(value= "/SaveDependent", method=RequestMethod.POST)
public String saveDependent(ClientApplicationDependent clientApplicationDependent) {
clientApplicationDependentService.saveOrUpdate(clientApplicationDependent);
return "success";
}
SERVICE:
public interface ClientApplicationDependentService {
public void saveOrUpdate(ClientApplicationDependent clientApplicationDependent);
}
SERVICE IMPL:
#Override
public void saveOrUpdate(ClientApplicationDependent clientApplicationDependent) {
clientApplicationDependentRepository.save(clientApplicationDependent);
}

Related

Spring ParamsInterceptor complains about #RequestParam- BEFORE REQUEST

i'am sending ajax get request to spring mvc handler and i can pass parameter-values.
Problem is, that i became ERROR everytime:
spring.interceptor.ParamsInterceptor - BEFORE REQUEST:
org.springframework.beans.NotWritablePropertyException: Invalid
property 'fromDate' of bean class
[com.example.CallDbController]: Bean
property 'fromDate' is not writable or has an invalid setter method.
Does the parameter type of the setter match the return type of the
getter?
[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
My Ajax-Requst:
$.ajax({
type : "GET",
url : 'myUrl.action',
data : {
"fromDate" : start
},
success : function(msg) {
console.log('something to do...');
}
});
and my controller handler:
#Controller
#RequestMapping("/calldb/*")
public class CallDbController {
#RequestMapping(value = { "myUrl.action" }, method = RequestMethod.GET)
public #ResponseBody String[] getTimeDifference(#RequestParam("fromDate") String startDate) {
//something to do...
}
}
I'am confusing, that "fromDate" Request-Parameter from GET-Request
is being interprited as Bean-Property.
i've finde my problem. Exception has been thrown due to Implementation of some interceptor.

Spring MVC Ajax form properties name

I have a form with a list of fields:
type, name, description, height ,width
I send by ajax to my controller, my controller receive this ajax call but he said that all input fields are null.
My mapped DTO have the same fields but with distinct name, really I don't need use the same name in my call ajax that in my #RequestBody dto class.
Its possible? I am limited to use same names in the class and the ajax calls?
This aren't a problem really, but I can't found any info about this.
My DTO properties:
ResourceCreateDTO [resourceTypeId=null, resourceId=null,
resourceName=null, resourceDescription=null, folderId=null]
My JSON data:
resource-description: "asdfasdfasdfasdfsadfasdfsdfasdfasdfasdfasdfsadfasdfasdf"
resource-folder: "0"
resource-folder-type: "1000"
resource-id: "1006"
resource-name: "asdfasdfasdfasdf"
My AJAX Call:
$("#createModalSubmit").click(function(){
var data = {};
$('#createForm *').filter(':input').each(function(){
var input = $(this);
data[input.attr("name")] = input.val();
delete data["undefined"];
});
$.ajax({
contentType : "application/json; charset=utf-8",
type: "POST",
url: context + "/editor/create",
data: JSON.stringify(data),
dataType : 'json',
cache: false,
success:function(result){
},
error:function(){
}
});
});
My Controller config:
#RequestMapping(value = "/editor/create", method = RequestMethod.POST)
public #ResponseBody ResourceDTO create(#RequestBody ResourceCreateDTO dto)
throws Exception {
System.out.println("dto: " + dto.toString());
This system out prints the above DTO toString.
I am searching any type of anotation or config that I can name the DTO properties:
#MyCustomName("resource-name")
private String resourceName;
Use my "resource-name" from the AJAX call.
If your DTO cannot have the same name that is being used in your ajax, you can then match it manually inside your controller.
#RequestMapping(value = "/editor/create", method = RequestMethod.POST)
public #ResponseBody ResourceDTO create(#RequestBody String dto)
throws Exception {
//mapping
}
Or
#RequestMapping(value = "/editor/create", method = RequestMethod.POST)
public #ResponseBody ResourceDTO create(#RequestBody Map<String,Object> dto)
throws Exception {
//mapping
}

Spring Controller + Ajax return String

I want to return String from Spring MVC Controller to Ajax.
It is not working as expected and gives error.
My Ajax codes for this:
function ajaxRequest(item) {
$.ajax({
type: "POST",
url: "/myPage",
data: {
item: item
},
success: function (html) {
alert(html);
},
error: function(e) {
console.log("Error:" + e);
}
});
}
My Controller:
#RequestMapping(value = "/myPage", method= RequestMethod.POST, produces="text/plain")
public #ResponseBody String myController(HttpServletRequest request) {
String myItem = request.getParameter("item");
...
return myItem + "bla bla bla";
}
Chrome console result:
POST http://localhost:8080/myPage 406 (Not Acceptable) jquery.js
Error:[object XMLHttpRequest]
What am i missing here?
When you return a String from a handler method annotated with #ResponseBody, Spring will use a StringHttpMessageConverter which sets the return content-type to text/plain. However, your request does not have an Accept header for that content-type so the Server (your Spring app) deems it unacceptable to return text/plain.
Change your ajax to add the Accept header for text/plain.
I have solved it. We can return correct values with response writer.
#RequestMapping(value = "/myPage")
public void myController(HttpServletRequest request, HttpServletResponse response) throws IOException {
String myItem = request.getParameter("item");
...
response.getWriter().println(myItem + "bla bla bla");
}
Be sure that you have Jackson dependency. Spring MVC can relies on it.

Passing an object as parameter to Breeze controller action

I'm trying to send an object as a parameter through Breeze without success.
Using the following code I can send a primitive type:
Client:
var query = EntityQuery
.from('account/authenticate')
.withParameters({ loginRequest: "hello" });
Server:
[BreezeController]
public class AccountController : ApiController
{
[HttpGet]
public LoginResult Authenticate(string loginRequest)
{
// String for loginRequest received successfully
}
}
However, if I try and pass a complex type up, the param is always null:
Client:
var loginRequest = { userName: 'me', password: 'pass' };
var query = EntityQuery
.from('account/authenticate')
.withParameters({ loginRequest: loginRequest });
Server:
[BreezeController]
public class AccountController : ApiController
{
[HttpGet]
public LoginResult Authenticate(LoginRequest loginRequest)
{
// Object for loginRequest always null
}
}
I believe this is in part because Breeze always uses a GET for queries. A POST might handle the serialization correctly, but I can't see any way in the Breeze API to force a POST.
If I pass up a JSON string representation of the object I can pick it up server-side, but this requires manual deserialization. I realise I could do this outside of Breeze with a standard WebAPI call, but I'm trying to keep all of my server-side calls running through the same pipeline.
Is it possible to do this?
You may be missing a [FromUri] attribute. Any time I tried to pass a more complex object or set of parameters everything would come back as null until I added that attribute.
[BreezeController]
public class AccountController : ApiController
{
[HttpGet]
public LoginResult Authenticate([FromUri] LoginRequest loginRequest)
{
// Object for loginRequest always null
}
}
Why not use ->
var loginRequest = { userName: 'me', password: 'pass' };
var query = EntityQuery
.from('account/authenticate')
.withParameters( loginRequest);
instead of
var loginRequest = { userName: 'me', password: 'pass' };
var query = EntityQuery
.from('account/authenticate')
.withParameters({ loginRequest: loginRequest });

How to call #RequestMapping method of Controller having specified URL using AJAX

I'm very new to Spring and Portlet. I want to use jqgrid to show some list. I am trying to call a method in controller which is annoted with the #RequestMapping but the method is not being called
My Controller has following method
#Controller(value = "myController")
public class MyController {
#RequestMapping(value="/myURL",method=RequestMethod.GET)
public #ResponseBody MyDTO initItemSearchGrid(RenderResponse response, RenderRequest request){
MyDTO myDto=new MyDTO();
return myDto;
}
}
My JSP code using AJAX
var urlink="/myURL"; /* myURL is the exact String written in value Attribute of
resourceMapping in Controller*/
$.ajax({
url :urlink,
cache: false,
data:$('#myForm').formSerialize(),
dataType: "json",
type: "GET",
contentType: "application/json; charset=utf-8",
success: function(jsondata){
...
}
});
When above AJAX code is executing my method is not called.
You mention Portlets in your question. Working with Spring and portlets is a bit different from servlets.
So, assuming you have a portlet like this
#Controller
#RequestMapping("VIEW") // VIEW mapping (as opposed to EDIT)
public class MyPortlet {
#RenderMapping
public ModelAndView handleRenderView(RenderRequest request, RenderResponse response) {
ResourceURL resourceUrl = response.createResourceURL();
resourceUrl.setResourceID("myResource"); // this is the id used to reference a #ResourceMapping
ModelAndView ret = new ModelAndView("myPortlet");
ret.addObject("resourceUrl", resourceUrl.toString());
return ret;
}
#ResourceMapping("myResource")
public void handleMyResource(ResourceRequest request, ResourceResponse response) {
OutputStream out = response.getPortletOutputStream();
// write whatever to output
}
}
As you can see, the #ResourceMapping is identified by a resource ID. The url for the resource mapping can be created using the standard portlet API methods and classes createResourceURL() and javax.portlet.ResourceURL.
If you prefer to use the portlet taglibrary instead, you can also generate a resource URL using the <portlet:resourceRequest> tag.
Your view might look something like this
myPortlet.jsp
...
<script>
$.ajax({
url :${resourceUrl},
cache: false,
data:$('#myForm').formSerialize(),
dataType: "json",
type: "GET",
contentType: "application/json; charset=utf-8",
success: function(jsondata){
.........
.........
.........
}
});
</script>
...

Resources