Here I have written this code for a rest web service in Spring Controllor Class . After build the project I try to use this service using a Restful-Client
RestService Code :-
#RequestMapping(value="/someurl/{prm_passPhraseCode}/{prm_email}", method= RequestMethod.POST)
public #ResponseBody User sendResetLink(#PathVariable("prm_passPhraseCode") String prm_sPassPhrase, #PathVariable("prm_email") String prm_sEmail , HttpServletRequest prm_ObjRequest, HttpServletResponse prm_ObjResponse){
......
..... //some more logical Code.
return new User(); //just dummy object for reference.
}
Here how I tried to access the Url. I have selected the method type as post.
I have also added two headers
Content-Type : application/json
Accept : application/json
URL http://127.0.0.1:8080/webservice.staff.backend/someurl/23812397997713/kumarvikrant625#gmail.com
Although all my other Rest services urls either it is GET or POST are working fine.
I have also try by change the method = RequestMethod.GET but still get the same error.
Error :-
Status Code 406 : The resource identified by this request is only capable of
generating responses with characteristics not acceptable according to the request "accept" headers.
please help if any one have a Idea.
your Url isn't mapped correctly, you are missing sendResetPasswordLink
#RequestMapping(value="/someurl/sendResetPasswordLink/{prm_passPhraseCode}/{prm_email}", method= RequestMethod.POST)
Try this.. May be it can work...
#RequestMapping(value="/someurl/{prm_passPhraseCode}/{prm_email}",headers="Accept=*/*", method= RequestMethod.POST)
Related
I have a web application written on Spring 3.1 (not boot) and running on Tomcat 7.
I have a #Controller implements method PUT on a certain URL.
In some cases When sending a PUT request from Postman, I get a 403 response instead of what is expected.
For example:
Sending the request to a non-implemented URL (on GET to the same URL I get a 404)
Sending an invalid JSON as the request body (Expected 400)
Sending a string instead of a numeric request parameter (Expected 400)
I also implement a filter that excepts all requests and just before the filter exists, I can verify I get the expected status from the rest of the chain.
This is an example of a controller code:
#RequestMapping(value = "/{book}", method = RequestMethod.PUT)
#ResponseStatus(HttpStatus.OK)
#ResponseBody
protected Book put(#PathVariable(value = "bookId") String id, #RequestBody #Valid Book book) {
return book; // just a stub
}
And this is the relevant part in the filter:
filterChain.doFilter(req, res);
// res.getStatus() is the expected status
return; // after this line I move to internal code of Tomcat which I cannot debug, but something happens there.
What do I miss?
Thanks
Check out CORS filter configuration first as Andreas said: https://tomcat.apache.org/tomcat-8.5-doc/config/filter.html
Check out this flowchart also https://tomcat.apache.org/tomcat-8.5-doc/images/cors-flowchart.png
Check out this stackoverflow post finally 403 on JSON PUT request to Tomcat with Spring 3.0.5 and Jackson
Your path variable value is bookId, but your url uses {book}; both should match. Try changing the url to "/{bookId}" or the path variable to #PathVariable(value = "book"). It might be useful to know the URL that you are calling to help analyse the issue.
I have a spring mvc controller, which accepts a post request and it needs to redirect to a URL (GET request).
#RequestMapping(value = "/sredirect", method = RequestMethod.POST)
public String processForm(HttpServletRequest request) {
System.out.println("Ews redirect hit !!! ");
request.setAttribute(View.RESPONSE_STATUS_ATTRIBUTE,HttpStatus.MOVED_PERMANENTLY);
return "redirect:https://www.google.com/";
}
And the class is annotated with #RestController. I am always getting 405, method not allowed for the redirect url. (i.e google.com).
As per docs (https://www.rfc-editor.org/rfc/rfc7238), it should allow the method to be changed . I am not sure what am I doing wrong? Can someone help
It looks like Rest Controllers can't use the simple "redirect:" convention, like non-Rest Controllers can. See Spring MVC #RestController and redirect
Have you tried accepting GET in the request mapping?
method = { RequestMethod.POST, RequestMethod.GET }
I have this Controller :
#Controller
public class HelloWorldController {
#RequestMapping("/hello.html")
public ModelAndView helloWorld() {
String message = "Hello World, Spring 3.0!";
return new ModelAndView("hello", "message", message);
}
#RequestMapping(value = "/login", method = RequestMethod.GET)
public String viewLogin(Map<String, Object> model) {
User user = new User();
model.put("userForm", user);
return "LoginForm";
}
#RequestMapping(value = "/login", method = RequestMethod.POST)
public String doLogin(#Valid #ModelAttribute("userForm") User userForm,
BindingResult result, Map<String, Object> model) {
if (result.hasErrors()) {
return "login";
}
return "LoginSuccess";
}
}
I have 2 methods having different http methods for the same url /login
so when clicking on the first url 'localhost:8080/project_name/login' the first method with GET will be handled and will redirect me to the /LoginForm
So from my understanding the second method handler will not be executed as the request for /login is always with GET.
If my understanding is wrong please explain to me how can the second method will be exectued and thanks.
the request for /login is always with GET
I think this is where you are getting confused. It's GET because the browser makes a GET call by default. If you want to evoke the second method, you may have to write a custom form / JSP page or check out postman to set the HTTP method to POST.
You can also use curl from command line:
$ curl -d "param1=value1¶m2=value2" -X POST http://localhost:3000/data
If you want to be able to make POST calls from your browser itself, checkout these browser add-ons :
firefox, chrome,
If you do not like extensions in your browser, create a bookmark with the following text and use it :
javascript:var%20my_params=prompt("Enter%20your%20parameters","var1=aaaa&var2=bbbbb");%20var%20Target_LINK=prompt("Enter%20destination",%20location.href);%20function%20post(path,%20params)%20{%20%20%20var%20xForm=%20document.createElement("form");%20%20%20xForm.setAttribute("method",%20"post");%20%20%20xForm.setAttribute("action",%20path);%20xForm.setAttribute("target",%20"_blank");%20%20%20for(var%20key%20in%20params)%20{%20%20%20if(params.hasOwnProperty(key))%20{%20%20%20%20%20%20%20%20var%20hiddenField%20=%20document.createElement("input");%20%20%20%20%20%20hiddenField.setAttribute("name",%20key);%20%20%20%20%20%20hiddenField.setAttribute("value",%20params[key]);%20%20%20%20%20%20%20%20%20xForm.appendChild(hiddenField);%20%20%20%20%20}%20%20%20}%20%20%20document.body.appendChild(xForm);%20%20xForm.submit();%20}%20%20%20parsed_params={};%20my_params.split("&").forEach(function(item)%20{var%20s%20=%20item.split("="),%20k=s[0],%20v=s1;%20parsed_params[k]%20=%20v;});%20post(Target_LINK,%20parsed_params);%20void(0);
A hit from the browser for the url localhost:8080/project_name/login will be a GET call; so your first /login GET method will be executed.
To have the second method executed, make a POST call from any Rest client like PostMan or ARC etc.
click here
The Browser default choose the GET method . so if you try in postman you can see the difference. you have option to choose GET / POST.
For realtime also from the UI they will mention specific to GET request / Post request so no worries.
you can use the postman for better way
I am using spring rest APIs and getting Http 405 error for all the POST methods.
I have following POST method,
#RequestMapping(value = "/GetPlanByBasicContext/", method = RequestMethod.POST)
public #ResponseBody Plan getPlanByBasicContext(#RequestBody BasicPlanContext basicPlanContext)
{
return planService.getPlanByBasicContext(basicPlanContext);
}
I am using fiddler to post the following request,
POST
http://localhost:8080/now/Plan/GetPlanByBasicContext
{ "sourceLocation":"",
"destinationLocation":"",
"modeOfTransport":"car"
"budget":"any"
}
Same attributes are present in BasicPlanContext on the server, along with getters and setters.
I have tried other solutions mentioned and nothing has worked.
Note: Security is not configured for spring yet.
you are posting to a wrong URL , you are missing a trailing slash in the end of your URL, try posting to : http:// localhost:8080/now/Plan/GetPlanByBasicContext/
I am getting Internal Error when trying to make an ajax POST Call which returns JSON.
The ajax call is made from JS page:
$.post(
'FilterAsJson',
$(formWithReportData).serialize(),
function(data){funtion_body}
);
This is my Spring MVC calling method:
#RequestMapping(value = "/Reporting/FilterAsJson", method = RequestMethod.POST)
public #ResponseBody PagedQueryResult<GetEntitlementOverviewReportResult> filterAsJson(#ModelAttribute GetEntitleReportQuery query, HttpSession session)
{
getEntitlementOverviewFromSession(session).updateFromQuery(query, session);
return queryDispatcher.dispatch(query);
}
The issue comes where I am setting only few fields in this class GetEntitlementOverviewReportResult(17 out of 30). This is a bean class with simple setter getters. If I set all the 30 fields it works fine.
Can you suggest how the JSON response is set so I can rectify this issue.
A 500 error means that your server encountered an error while processing the request. Since you are using AJAX, you do not see the full message from the server.
2 Options:
A - Check the server logs
B - See below:
Best way I know of to check this with an asynchronous call is to press F12 to bring up your developer tools in your web browser.
Then, you click the "Network" tab on the browser tool and you can see all of the requests that your application makes.
Make your request that is giving you a 500 error, then find it in the list of network requests. You should see the 500 error and be able to see the actual output (server response) that will give you an actual message.
#RequestMapping(value = "/Reporting/FilterAsJson", headers = "Accept=application/json", method = RequestMethod.POST)
public #ResponseBody PagedQueryResult<GetEntitlementOverviewReportResult> filterAsJson(#ModelAttribute GetEntitleReportQuery query, HttpSession session) {
getEntitlementOverviewFromSession(session).updateFromQuery(query, session);
return queryDispatcher.dispatch(query);
}
UPDATED
Oh, i see. I didn't understand question properly.
Show us please class GetEntitleReportQuery which propagate #ModelAttribute.
Also check what does method serialize when you filled not all fields. Does it exist?
UPDATED
An idea.
When u filled up not all fields of class, he try to find class with such fields and can't find. So, try to named your class in Controller and add binding result param: filterAsJson(#ModelAttribute("query") GetEntitleReportQuery query, HttpSession session, BindingResult result) also send from JSP with name "query".