Sometimes we send a POST HTTP request with POST payload to an endpoint with URL variable, for example:
[POST] http://example.com/update-item?itemid=123456
To get the POST payload in the Spring controller class, I can do something this:
#RequestMapping(value = "/update-item", method = RequestMethod.POST)
public String updateItem(#RequestBody Item json) {
//some logics
return "/update-item-result";
}
However, at the same time, how can I get the variable from the URL (i.e. itemid in the above example) even for method = RequestMethod.POST?
I see a lot of Spring MVC examples on the web either get the GET variables from the URL or the POST variables from the payload, but I never see getting both in action.
You can use multiple HTTP requests by specifying the method attribute as an array in the #RequestMapping annotation.
#RequestMapping(value = "/update-item", method = {RequestMethod.POST,RequestMethod.GET})
public String updateItem(#RequestBody Item json) {
//some logics
return "/update-item-result";
}
Related
I want to fetch a header value I am passing during a GraphQl Query call. Something like we can do prior in case of rest api
HttpServletRequest.getheader()
I wanted to fetch it from the dataFetchingEnvironment but the context fetched from this value did not get me any means to fetch the header values from request.
try {
GraphQLContext context = env.getGraphQlContext();
String Id= context.getHeader("headerkeyIpass");
// I know this method does not exist i am trying to paint a picture as to what i am asking
I do not intend to change the resolver method calls but any inputs to improve my code would be great.
Like you said getHttpServletRequest does not exist on DataFetchingEnvironment.getGraphQlContext() when using the new official Spring 2.7 spring-boot-starter-graphql (not the legacy GraphQL Java Kickstart ones).
Instead you can add an autowired HttpServletRequest request variable at the top of your controller and inside each query resolver it will be filled with the request context.
#Controller
public class SomeGraphQLController {
...
#Autowired
private HttpServletRequest request; // will be filled inside each #QueryResolver and #MutationResolver method.
...
#QueryResolver
public XXX yyyy() {
...
try {
String someHeader = request.getHeader("someHeader");
...
}
}
The GraphQLContext has method getHttpServletRequest() which returns
java.util.Optional<javax.servlet.http.HttpServletRequest>
So from there u can get the headers
GraphQLContext context = env.getGraphQlContext();
HttpServletRequest request = context.getHttpServletRequest().get();
String Id= request.getHeader("headerkeyIpass");
If you are using the latest graphql libraries there are some breaking changed and you can get the headers from GraphQLServletContext as shown here
GraphQLServletContext graphQLServletContext = (GraphQLServletContext) env.getContext();
String user = graphQLServletContext.getHttpServletRequest().getHeader("user");
I am trying to access the POST API from my spring app to angular but little bit confused how to use and access the given API in my angular app.
Spring REST API
#RequestMapping(value = "/getWelcomeMessage", method = RequestMethod.POST)
public String getLoginWelcomeMessage() {
return details.getLoginWelcomeMessage();
}
The given API is fetching the welcome message details from my oracle DB and returning a string value. I am trying to access the given REST API in my angular code through services. I had define the post service as follows
export class LoginService {
constructor(private http : HttpClient) { }
welcomeMessageService(){
const headers = {'content-type':'application/text'}
return this.http.put("http://localhost:8080/API/getWelcomeMessage",null,
{'headers':headers});
}
}
As the post method requires three arguments URL, Body and header. But in my case my spring REST API doesn't contain any body and returning a string. So, I had define the body as null and change the header type to text as it is JASON by default.
At last, I am trying to access the given service method by injecting it in my component as follows-
export class LoginComponent implements OnInit {
message:string;
constructor(private loginService : LoginService) { }
ngOnInit(): void {
this.loginService.welcomeMessageService().subscribe(
response =>{
console.log(response);
this.message = response;
}
)
}
}
But when I am trying to assign the response to the string I am getting the error that string cannot be assigned to the object. I am little bit confused why this error is occurring as I had also changed the header type to string while defining my service but still getting the error.
It can be a great help if anybody guide me regarding this as I am new to angular and little bit confused with integration part of API with angular.
Use { responseType: 'text' } and also send an empty body not null
export class LoginService {
constructor(private http : HttpClient) { }
welcomeMessageService(){
return this.http.put("http://localhost:8080/API/getWelcomeMessage",{},
{ responseType: 'text' });
}
}
Maybe you have copied the function wrong but check also here
#RequestMapping(value = "/getWelcomeMessage", method = RequestMethod.POST)
public String getLoginWelcomeMessage() {
return details.getLoginWelcomeMessage();
}
This is a Post method not a put that you are trying to call
As for cors error add the following to the backend just above #Controller or #RestControler whatever you have
#CrossOrigin(value = {"http://localhost:4200"}, methods = {GET,POST,PUT,DELETE})
I'm working with Facebook messenger app (chatbot) and I want to see what GET request I'm receiving from it. I'm using Spring Framework to start http server and ngrok to make it visible for facebook.
Facebook sending webhooks to me and i receive them, but i don't understand how to extract data from this request. Here what i get when I try HttpRequest to receive GET request. ngrok screenshot (error 500).
When I tried without HttpRequest, i had response 200 (ok).
What do i need to put to parameters of my find method to see GET request data?
My code:
#RestController
public class botAnswer {
#RequestMapping(method= RequestMethod.GET)
public String find(HttpRequest request) {
System.out.println(request.getURI());
String aaa = "222";
return aaa;
}
}
I guess HttpRequest will not help you here. For simplicity, just change HttpRequest to HttpServletRequest. You can access all query string parameters from it using request.getParameter("..."). Something like the following should work:
#RequestMapping(value = "/", method = RequestMethod.GET)
public String handleMyGetRequest(HttpServletRequest request) {
// Reading the value of one specific parameter ...
String value = request.getParameter("myParam");
// or all parameters
Map<String, String[]> params = request.getParameterMap();
...
}
This blog post shows how to use the #RequestParam annotation as an alternative to reading the parameters from HttpServletRequest directly.
I'm trying to make a simple AJAX call in my Spring MVC project but am running into trouble. I am making my AJAX request by sending an String type argument and I'm wanting to get an ArrayList type back. I've read many tutorials at this point and can't figure out what's wrong with my AJAX/Controller configuration. I am using the ResponseBody annotation when trying to return my needed result back to the view. In this controller I am not returning an updated ModeAndView object, but this shouldn't matter since the page does not need to be refreshed because I'm using AJAX. Below is my AJAX call and controller code. I would really appreciate it if someone could give me a hint on what I'm doing wrong here.
function getdays() {
var monthSelected = $("#monthselect option:selected").text();
alert(monthSelected);
$.ajax({
url : '${pageContext.request.contextPath}/ajaxdays',
data: monthSelected,
success : function(data)
{
$('#daySelect').html(data);
alert(data);
}
});
}
Here is my controller class:
#Controller
#SessionAttributes
public class WorkstationController
{
#RequestMapping(value = "/ajaxdays", method = RequestMethod.GET)
public #ResponseBody
ArrayList<String> getTime(HttpServletRequest request)
{
ArrayList<String> retList = new ArrayList<>();
retList = this.getList();
return retList;
}
}
you have following errors
wrong url
change url : 'ajaxdays.html'to ${pageContext.request.contextPath}/ajaxdays
no parameter passed
you are not passing any data to server side so there is no need to write data: monthSelected
URL mentioned in ajax call should be the context path followed by the controller mapping. And '.html' should not be specified.
url: ${pageContext.request.contextPath}/ajaxdays
I have this piece of code:
#RequestMapping(value = "/test.json", method = RequestMethod.GET)
#ResponseStatus(HttpStatus.OK)
public #ResponseBody Object[] generateFile(#RequestParam String tipo) {
Object[] variaveis = Variavel.getListVariavelByTipo(tipo);
return variaveis;
}
As far as I know it should take a request to test.json?tipo=H and return the JSON representation of Variavel[], however when I make such request I get:
HTTP Status 406 -
type Status report
message
descriptionThe resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers ()
By using the following function I can get the expected json:
#RequestMapping(value = "/teste.json")
public void testeJson(Model model, #RequestParam String tipo) {
model.addAttribute("data", Variavel.getListVariavelByTipo("H"));
}
What I'm doing wrong?
#RequestBody/#ResponseBody annotations don't use normal view resolvers, they use their own HttpMessageConverters. In order to use these annotations, you should configure these converters in AnnotationMethodHandlerAdapter, as described in the reference (you probably need MappingJacksonHttpMessageConverter).