How to pass message along with RESTful request? - java

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){
}

Related

Catch all requested paths in Springboot RestController

I am looking for a way to get an Endpoint in Springboot that catches all requests send to /. Ideally everything behind / should be handed in as a String parameter.
An example request could look like this: http://myproxy.com/foo/bar?blah=blubb
I tried a RestController for /
#RestController
public class ProxyRestController {
#RequestMapping("/{restOfPath}", method = RequestMethod.GET)
public ResponseEntity<String> handleGetRequests(#PathVarialbe("restOfPath") String path) {
return ResponseEntity.of(Optional.of(""));
}
}
The endpoint doesn't catch the example because it would be routed to /foo/bar whereas /foo is caught.
How would I achieve a "catch all" endpoint in SpringBoot? It could also be in another way than a #RestController I just need to be inside a component and send a http response back to the caller.
Adapt this code to match yours:
#Controller
public class RestController {
#RequestMapping(value = "/**/{path:.*}")
public String index(final HttpServletRequest request) {
final String url = request.getRequestURI();
return "something";
}
}

Spring Boot: How to send an object to RestController from another Controller?

I have the method in my RestController, that accepts an object:
#RestController
#RequestMapping(value = "/statistic")
public class MyController {
#Autowired
private StatisticService statistic;
#RequestMapping(method=RequestMethod.POST, value="/add")
public ResponseEntity<String> add(#RequestBody PersonData personData) {
if(statistic.addToStatistic(personData)) {
return new ResponseEntity<String>(HttpStatus.OK);
}
return new ResponseEntity<String>("Person already exists", HttpStatus.CONFLICT);
}
}
I want to send the object from my another Controller. I only read, that I can send the object to /statistic/add as json via different browser tools (REST clients). But my another controller accepts only "login" (unique name) and it should create the object from this login and send to /statistic/add. Like this I wanted to create json object and send it, but I get the error
org.springframework.web.client.RestClientException: No HttpMessageConverter for org.codehaus.jettison.json.JSONObject
Here is my attempt:
#Controller
#RequestMapping("/main")
public class ViewController {
#RequestMapping(value = "/newPerson/{login}", method = RequestMethod.GET)
#ResponseBody
public ResponseEntity<String> registerNewPerson(#PathVariable String login) {
RestTemplate restTemplate = new RestTemplate();
try {
String uri_create = "http://localhost:8082/add/";
//creation of json doesnt't help
JSONObject entity = new JSONObject();
entity.put("login", login);
entity.put("points", 0);
ResponseEntity<String> responce = restTemplate.postForEntity(uri_create, entity, String.class);
return responce;
} catch(Exception e) {
e.printStackTrace();
return null;
}
}
}

Getting String body from Spring serverrequest

I am trying to get simple string from request body but keep getting errors
Handler:
#RestController
public class GreetingHandler {
public Mono<ServerResponse> hello(ServerRequest request) {
String contentType = request.headers().contentType().get().toString();
String body = request.bodyToMono(String.class).toString();
return ServerResponse.ok().body(Mono.just("test"), String.class);
}
}
Router:
#Configuration
public class GreetingRouter {
#Bean
public RouterFunction<ServerResponse> route(GreetingHandler greetingHandler) {
return RouterFunctions
.route(RequestPredicates.POST("/hello"),greetingHandler::hello);
}
}
Request works i can see the contenType (plainTexT) and i get the response in postman but no way i cant get to request body. The most common error i get is MonoOnErrorResume. How do i convert the body from request into String?
You will have to block to get to the actual body string:
String body = request.bodyToMono(String.class).block();
toString() will just give you the string representation of your Mono object.
Here is what block does:
https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Mono.html#block--
Update:
I wasn't aware that blocking on the http thread is not possible (anymore?).
Here is an adapted version of your hello controller method that prints "Hello yourInput" on the console and also returns that string in the response.
public Mono<ServerResponse> hello(ServerRequest request) {
Mono<String> requestMono = request.bodyToMono(String.class);
Mono<String> mapped = requestMono.map(name -> "Hello " + name)
.doOnSuccess(s -> System.out.println(s));
return ServerResponse.ok().body(mapped, String.class);
}
Can you use #RequestBody annotation?
public Mono<ServerResponse> hello(#RequestBody String body, ServerRequest request) {
String contentType = request.headers().contentType().get().toString();
return ServerResponse.ok().body(Mono.just("test"), String.class);
}

Spring boot Java post request

I am trying to do a simple post request from React (client side) to Java server side. Here is my controller below.
package com.va.med.dashboard.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import com.va.med.dashboard.services.VistaServiceImpl;
import gov.va.med.exception.FoundationsException;
#RestController
#RequestMapping("/dashboard")
public class DashboardController {
#Autowired
private VistaServiceImpl vistaService;
#RequestMapping("/main")
String home() {
return "main route";
}
#RequestMapping("/rpc")
String test() throws FoundationsException {
vistaService.myAuth();
return "this is rpc route";
}
#RequestMapping(method = RequestMethod.POST, produces =
"application/json", value = "/vista")
#ResponseStatus(value = HttpStatus.ACCEPTED)
public String getVistaConnection(#RequestBody String ipString, #RequestBody String portString, #RequestBody String accessPin,
#RequestBody String verifyPin) {
System.out.println(ipString);
System.out.println(portString);
System.out.println(accessPin);
System.out.println(verifyPin);
vistaService.connect(ipString, portString, accessPin, verifyPin); // TO-DO populate with serialized vars
if (vistaService.connected) {
return "Connected";
} else {
return "Not Connected";
}
}
}
Below is my react axios post request
axios.post('/dashboard/vista', {
ipString: this.state.ipString,
portString: this.state.portString,
accessPin: this.state.accessPin,
verifyPin: this.state.verifyPin
})
.then(function (response){
console.log(response);
})
.catch(function (error){
console.log(error);
});
This is also the error that I am getting.
Failed to read HTTP message:
org.springframework.http.converter.HttpMessageNotReadableException:
Required request body is missing:
Can anyone please shed some light on this error message? I'm coming from a pure JavaScript background so a lot of things I just don't know for Java because it is automatically implemented inside of JavaScrips language.
Thanks again in advance!
You're doing it wrong.
Instead of
public String getVistaConnection(#RequestBody String ipString, #RequestBody String portString, #RequestBody String accessPin,RequestBody String verifyPin)
You should wrap those parameters in a class:
public class YourRequestClass {
private String ipString;
private String portString;
....
// Getter/setters here
}
and your controller method will look like:
public String getVistaConnection(#RequestBody YourRequestClass request)
From #Rajmani Arya:
Since RestContoller and #RequestBody suppose to read JSON body, so in your axios.post call you should put headers Content-Type: application/json
Try to replace all #RequestBody annotations with #RequestParam
public String getVistaConnection(#RequestParam String ipString, #RequestParam String portString, #RequestParam String accessPin, #RequestParam String verifyPin)

Spring MVC 3.2 +Jackson

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 );
});

Categories

Resources