My requirement is simple i.e i want to write a common methods which suppose to have auto intelligence based on user request it will generate response, like if i submit as a html it should produce html . if i submit as a Json it should produce Json.
Below is 2 sample code ,If i write 2 separate method it works fine but i want to write it to one common method.
1)below is sample code which works for html
#Controller
public class Program1Controller {
#RequestMapping("/helloworld")
public #ResponseBody ModelAndView helloWord(){
String message = "Welcome to TEST";
return new ModelAndView("Test1", "message",message);
}
}
2)below is sample code which work for json
#RequestMapping(value = DUMMY_EMP, method = RequestMethod.GET)
public #ResponseBody String getDummyEmployee() {
String message = "Welcome to TEST";
return message;
}
Instead writing 2 separate method i want to write one method which should have auto intelligence to send a response based on user request.
Above Query for GET ,Same also how can i do for POST.
You can handle that one in ajax. In your controller you have 2 different methods returning JSON, POST and GET and it can have the same value for its RequestMapping. Example:
#RequestMapping(value = "/returnJSON", method = RequestMethod.GET)
public #ResponseBody String getDummyEmployee() {
String message = "Welcome to TEST";
return message;
}
#RequestMapping(value = "/returnJSON", method = RequestMethod.POST)
public #ResponseBody String getDummyEmployee2() {
String message = "Welcome to TEST";
return message;
}
This should also be done for the one returning the HTML Object:
#RequestMapping(value = "/helloworld", method = RequestMethod.GET)
public #ResponseBody ModelAndView helloWord(){
String message = "Welcome to TEST";
return new ModelAndView("Test1", "message",message);
}
}
#RequestMapping(value = "/helloworld", method = RequestMethod.POST)
public #ResponseBody ModelAndView helloWord2(){
String message = "Welcome to TEST";
return new ModelAndView("Test1", "message",message);
}
}
Now, before going to the jquery ajax call, pass as parameter the url and type:
$.ajax({
type: type,
url: url,
data: { name: "John", location: "Boston" }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
Related
#RequestMapping(value="/postdata", method= RequestMethod.POST, consumes="application/json")
public String postdata(#RequestBody String test, #RequestBody String data) {
logger.info("password reset Request " + requestbody.get("test"));
logger.info("password reset Request " + data);
return "Hello";
}
Resolved [org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public java.lang.String mail.controller.EmailNotifictaionController.postdata(java.lang.String,java.lang.String)]
My Input in the SOAPUI is
{
"test":"my",
"data":"god"
}
You are using two #RequestBody which is not the correct way as one request can only have one request body.
You can either combine both the request bodies into single request body or you can build a wrapper class having both the test and data variables like:
public class Body {
public String test;
public String data;
// You can also keep them private and have getters/setters.
}
and use this class in the API method argument
#RequestMapping(value="/postdata", method= RequestMethod.POST, consumes="application/json")
public String postdata(#RequestBody Body body) {
logger.info("password reset Request " + body.test);
logger.info("password reset Request " + body.data);
return "Hello";
}
You can try this way, it should work.
I know that this question has been asked many times, but I have looked at every variation I could find and have still not been able to find out my issue.
Here is my ajax call:
function sendFormData(endpoint) {
console.log("CLICKING BUTTON");
var input = {
"userInputOne": "hello1",
"userInputTwo": "hello2",
"userInputThree": "hello3",
"userInputFour": "hello4",
"userInputFive": "hello5"
}
$.ajax({
type:"post",
contentType: "application/json",
data: JSON.stringify(input),
url: endpoint,
asynch: false,
success: function() {
alert("success");
}
});
}
The endpoint works. You can take my word for it.
Spring controller:
#RequestMapping(value = "endpoint", method = RequestMethod.POST)
private #ResponseBody String getFormData(#RequestBody FormInput userInput, HttpServletRequest request, final ModelMap model) {
String userInput1 = userInput.getInputOne();
String userInput2 = userInput.getInputTwo();
String userInput3 = userInput.getInputThree();;
String userInput4 = userInput.getInputFour();
String userInput5 = userInput.getInputFive();
return "success";
}
And here is my model class:
public class FormInput {
private String userInputOne;
private String userInputTwo;
private String userInputThree;
private String userInputFour;
private String userInputFive;
public FormInput(String userInputOne, String userInputTwo, String userInputThree, String userInputFour, String userInputFive) {
this.userInputOne = userInputOne;
this.userInputTwo = userInputTwo;
this.userInputThree = userInputThree;
this.userInputFour = userInputFour;
this.userInputFive = userInputFive;
}
public String getUserInputOne() {
return this.userInputOne;
}
public String getUserInputTwo() {
return this.userInputTwo;
}
public String getUserInputThree() {
return this.userInputThree;
}
public String getUserInputFour() {
return this.userInputFour;
}
public String getUserInputFive() {
return this.userInputFive;
}
}
I keep getting a HTTP status code of 415, which means unsupported media type. I set the contentType to "application/json", and I also tried to add "consumes= 'application/json'" to my Spring controller and that didn't help either. Thank you for any help you can give.
EDIT: I am now getting the following error after changing RequestMethod.GET to RequestMethod.POST: "Error 405: Request method 'GET' not supported"
There is no need to send parameter as json,you have made things complicated
In javascript code,you can remove contentType: "application/json", and change the format of data property to send data directly
function sendFormData(endpoint) {
console.log("CLICKING BUTTON");
var input = {
"userInputOne": "hello1",
"userInputTwo": "hello2",
"userInputThree": "hello3",
"userInputFour": "hello4",
"userInputFive": "hello5"
}
$.ajax({
type:"post",
//contentType: "application/json",
data: input,//send data directly
url: endpoint,
asynch: false,
success: function() {
alert("success");
}
});
}
In java code,you can remove #ResponseBody annotation before FormInput
#RequestMapping(value = "endpoint", method = RequestMethod.POST)
private #ResponseBody String getFormData(FormInput userInput, HttpServletRequest request, final ModelMap model) {
String userInput1 = userInput.getInputOne();
String userInput2 = userInput.getInputTwo();
String userInput3 = userInput.getInputThree();;
String userInput4 = userInput.getInputFour();
String userInput5 = userInput.getInputFive();
return "success";
}
The java controller method you have written is of type 'GET', it should be changed to 'POST', as the ajax call you are making is also of type POST
Try this and it will work
#RequestMapping(value = "endpoint", method = RequestMethod.POST)
private #ResponseBody String getFormData(#RequestBody FormInput userInput, HttpServletRequest request, final ModelMap model) {
String userInput1 = userInput.getInputOne();
String userInput2 = userInput.getInputTwo();
String userInput3 = userInput.getInputThree();;
String userInput4 = userInput.getInputFour();
String userInput5 = userInput.getInputFive();
return "success";
}
I guess main problem in not match http methods. You sent by POST method, but controller wait for GET method.
This is because your method signature doesn't match. Just remove contentType: "application/json".
In my controller I am having if condition and two different response type. I will get response in JSON format from "if" condition, but I am getting response from else condition like unexpected '0 , instead I need to get my error message'.
My controller code snippet
#RequestMapping(value = "/saveuser", produces = { "application/json" }, consumes = { "application/json" }, method = RequestMethod.POST)
public ResponseEntity<?> addUser(#RequestBody TestUser user)
throws NotFoundException {
System.out.println(user.getAnswer().size());
if(questioncount == user.getAnswer().size())
{
return new ResponseEntity<TestUser>(service.addUser(user),
HttpStatus.OK);
}else {
String one="one";
String erromessage = "Only" + questioncount +" questions are allowed";
System.out.println(erromessage);
return new ResponseEntity<String>(erromessage,HttpStatus.NOT_ACCEPTABLE);
}
}
I have this class DemoController. In this class I want to send a message along with REST request.
How can I send it? Suppose M sending http://localhost:8080/sendmessage...
How can I send a message along with this request?
#RestController
#EnableAutoConfiguration
public class DemoController {
#Autowired
DemoPublisher demopublisher;
#Autowired
DemoConsumer democonsumer;
#RequestMapping(value="/sendmessage", method= {RequestMethod.POST})
#ResponseBody
public String messageSenderController(#RequestParam String message, Model model){
try {
demopublisher.demoPublishMessage(message);
} catch (JMSException e) {
e.printStackTrace();
}
return message;
}
}
QueryParam
url: /sendMessage?msg=HelloWorld!
#RequestMapping(value="/sendmessage",method= {RequestMethod.POST})
#ResponseBody
public String messageSenderController(#QueryParam("msg") String message,Model model){
}
UrlParam
url: /sendMessage/HelloWorld!
#RequestMapping(value="/sendmessage/{message}",method= {RequestMethod.POST})
#ResponseBody
public String messageSenderController(#PathVariable String message,Model model){
}
When you are posting data to the server, you can also send data in the body parameter too. I recommend you use this for when you have a form or other data you want to send to the server.
RequestBody
url: /sendMessage
body (RAW in postman or other rest client, accept need to be application/xml):
{
"my message"
}
controller
#RequestMapping(value="/sendmessage",method= {RequestMethod.POST})
#ResponseBody
public String messageSenderController(#RequestBody String message,Model model){
}
I want to use x-editable into my page, and I learn it from this document.
The html element is here:
Click and input
And my controller is:
#RequestMapping(value = "/candidates/updateDisplayName", method = RequestMethod.POST)
public #ResponseBody String updateDisplayName(#RequestParam(value = "displayName") String displayName, HttpServletRequest request) {
System.out.println("Update display name");
System.out.println(displayName);
return "";
}
However, I got error again and again, the error message is like:
{"timestamp":1417250586743,"status":400,"error":"Bad
Request","exception":"org.springframework.web.bind.MissingServletRequestParameterException","message":"Required
String parameter 'displayName' is not
present","path":"/candidates/updateDisplayName"}
I knew that it's caused by the request parameter but not sure how to solve, could anyone help with this? Thanks a lot.
I changed the "displayName" to "name" in the #RequestParam it works, thanks for chrome developer tools, it helps me.
#RequestMapping(value = "/candidates/updateDisplayName", method = RequestMethod.POST)
public #ResponseBody String updateDisplayName(#RequestParam(value = "name") String displayName, HttpServletRequest request) {
System.out.println("Update display name");
System.out.println(displayName);
return "";
}