Spring Failed to load resource when adding #GetMapping - spring

Im facing an issue while Im adding a method to the controller class with when i add this #GetMapping to my controller I have a Failed to load ressource error Failed to load resource: the server responded with a status of 405 () and 404() and on the Run logs I get this message: o.s.web.servlet.PageNotFound : Request method 'GET' not supported
When I remove this method from the controller class, all works fine. Dont know why is this happening.
#GetMapping("/projet/{id}")
public String projet(#PathVariable("id") int itemId, Model model) {
model.addAttribute("datauser", userDao.findAll());
Project project = projectDao.findById(itemId).get();
model.addAttribute("projet",project);
model.addAttribute("task", new Task());
return "projet";
}
I don't understand where it comes from because before that my resources worked just fine. This is how I call it in my html :
<form action="#" th:action="#{'/projet/'+${proj.id}}" th:object="${proj}" method="GET">
<button><td th:text="${proj.nom}"></td></button>
</form>
Could you help me ? Thanks :) Eliane

You can try this way...
a)for GET methods:
#RequestMapping(value = "/projet/{id}", method = RequestMethod.GET)
b)for POST methods:
#RequestMapping(value = "/projet/{id}", method = RequestMethod.POST)

Related

Getting 404 error calling another JSP from link

I have a menu in my web page, and I have added a new link is not working. I am getting this error message.
HTTP Status 404 – Not Found
Type Status Report
Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
Here is the HTML code for the link.
<td><img src="images/menu/35-year-reunion.jpg" alt="Memories" /></td>
I do have a Spring controller method, and this is it. My web page is named reunion2021.jsp.
#RequestMapping(value = "/35yearreunion")
public String thirtyfiveYearReunion(Model model) {
return "reunion2021";
}
Try adding the request method to your controller's method , either this way :
#RequestMapping(value = "/35yearreunion",method = RequestMethod.GET)
public String thirtyfiveYearReunion(Model model) {
return "reunion2021";
}
or this way :
#GetMapping(value = "/35yearreunion")
public String thirtyfiveYearReunion(Model model) {
return "reunion2021";
}

PostMapping errors asking for GetMapping

I am trying to save data to my Postgres database. This should use a PostMapping annotation on the method so that it sends the object accordingly. However, for some reason it is expecting a "GET" method. Any thoughts and if others have run into a similar issue. I also cannot debug into that method as well.
Inventory.java
#RestController
public class InventoryController {
#Autowired
private InventoryService inventoryService;
#RequestMapping(value="/add", method=RequestMethod.POST)
public Inventory addItem(#RequestBody(required = false) Inventory item) {
System.out.print("This is a test");
return inventoryService.save(item);
}
#GetMapping(path="/test")
#ResponseBody
public String testMethod() {
return "Method works!";
}
}
Stacktrace
There was an unexpected error (type=Method Not Allowed, status=405).
Request method 'GET' not supported
org.springframework.web.HttpRequestMethodNotSupportedException:
Request method 'GET' not supported at
org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping.handleNoMatch(RequestMappingInfoHandlerMapping.java:201)
at
org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.lookupHandlerMethod(AbstractHandlerMethodMapping.java:421)
at
org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.getHandlerInternal(AbstractHandlerMethodMapping.java:367)
at
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping.getHandlerInternal(RequestMappingHandlerMapping.java:449)
at
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping.getHandlerInternal(RequestMappingHandlerMapping.java:67)
at
org.springframework.web.servlet.handler.AbstractHandlerMapping.getHandler(AbstractHandlerMapping.java:393)
I have tried the following annotations on the "addItem" method and it still returns the aforementioned trace.
#RequestMapping(value="/add", method=RequestMethod.POST)
#PostMapping(path="/add")
I am running Spring Boot 2.2.0.RELEASE
It's not asking for GetMapping, the error said Request method 'GET' not supported. It means you call endpoint for HttpGet Method, but your defined endpoint in the Controller is HttpPost Method !
Call using curl, should be like below :
curl -d "param1=value1&param2=value2" -H "Content-Type: application/json" -X POST http://localhost:8080/add
You do not need to add #ResponseBody as in #RestController is combination of #Controller and #ResponseBody. Also try to test the code from PostMan alike tools before handing over API end points to Frontend or mobile team.
Example:
#RestController
#RequestMapping(value = "/users")
public class UserController {
...
...
#GetMapping
#PreAuthorize("hasRole('ADMIN')")
public List<User> getAllUsers() {
return userService.getAllUsers();
}
}
Also sometime if we get any particular resource by Id so we should check if resource is null than return blank object or standard NOT_FOUND error, error we can override with #RestControllerAdvice extended from ResponseEntityExceptionHandler where we can extended all the error on controller level.
But if error comes in resource server, so in that case we have to add entrypoints in websecurity configure -> http security method overrid and add custom entrypoint as well failure and success handlers.

Static website does not want to work with a simple POST endpoint

I've made a simple static website, with some CSS & JS:
If I run this with SpringBoot, everything works pretty well, even JS works.
Now, I want to add a simple POST endpoint:
#RestController
public class Generator {
#RequestMapping(name = "/generator", method = RequestMethod.POST)
public String payload(final GeneratorPayload payload) {
System.out.println("This is your payload: " + payload.getFirstName());
return "testresp";
}
}
Which throws
org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' not supported when accessing the main page (I'm not even calling that endpoint), displaying an error.
If I delete the inner mapping ("/generator"), everything works fine.
It's like he was overriding the default method and applies it to the index?
What's going on here?
There was an error here:
#RequestMapping(name = "/generator", method = RequestMethod.POST)
I've specified name, instead of value and the mapping was being attached to "/".
The correct version:
#RequestMapping(value = "/generator", method = RequestMethod.POST)

Avoid Spring MVC form resubmission when refreshing the page

I am using spring MVC to save the data into database. Problem is it's resubmitting the JSP page when I am refreshing the page.
Below is my code snippet
<c:url var="addNumbers" value="/addNumbers" ></c:url>
<form:form action="${addNumbers}" commandName="AddNumber" id="form1">
</<form:form>
#RequestMapping(value = "/addNumbers", method = RequestMethod.POST)
public String addCategory(#ModelAttribute("addnum") AddNumber num){
this.numSrevice.AddNumbers(num);
return "number";
}
You have to implement Post/Redirect/Get.
Once the POST method is completed instead of returning a view name send a redirect request using "redirect:<pageurl>".
#RequestMapping(value = "/addNumbers", method = RequestMethod.POST)
public String addCategory(#ModelAttribute("addnum") AddNumber num){
this.numSrevice.AddNumbers(num);
return "redirect:/number";
}
And and have a method with method = RequestMethod.GET there return the view name.
#RequestMapping(value = "/number", method = RequestMethod.GET)
public String category(){
return "number";
}
So the post method will give a redirect response to the browser then the browser will fetch the redirect url using get method since resubmission is avoided
Note: I'm assuming that you don't have any #RequestMapping at controller level. If so append that mapping before /numbers in redirect:/numbers
You can return a RedirectView from the handler method, initialized with the URL:
#RequestMapping(value = "/addNumbers", method = RequestMethod.POST)
public View addCategory(#ModelAttribute("addnum") AddNumber num,
HttpServletRequest request){
this.numSrevice.AddNumbers(num);
String contextPath = request.getContextPath();
return new RedirectView(contextPath + "/number");
}
My answer shows how to do this, including validation error messages.
Another option is to use Spring Web Flow, which can do this automatically for you.

Spring. Bind post method request to base url without trailing slashes

I have problem which solution might be obvious.
I want to bind both post and get method to application base url. I am using annotated controller witch one of the method looks like :
#RequestMapping(value = { "/*" }, method = { RequestMethod.GET, RequestMethod.POST })
public void init(HttpServletRequest request) {
logger.info("Method: " + request.getMethod());
}
And in both cases when i send get or post request i always get result "Method: GET". How can i solve this problem?
It is seems that somewhere in app there is redirection but a can not find any.
Thanks in advance!
The problem is with how you test your program, you are only using GET method by entering url in your browser window in order to test POST
you can create simple html page with content like
<form action="http://localhost:8080/yourapp/yourEntryPoint" method="post">
<input type="text" name="data" value="mydata" />
<input type="submit" />
</form>
and open it in the browser
or use plugin to the browser of your choice (google) "REST services test"
more about Spring MVC
http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/htmlsingle/#mvc-ann-requestmapping
In order to map it to the base url for that controller you do not need to put value= on a method
#Controller
#RequestMapping("/yourEntryPoint")
public class YourClass {
#RequestMapping(method = {RequestMethod.GET, RequestMethod.POST })
public void get() {
logger.info("Method: " + request.getMethod());
}
#RequestMapping(value="/new", method = RequestMethod.GET)
public void getNewForm() {
logger.info("NewForm" );
}
}
this will map both request POST and GET to the url
http://host:port/yourapp/yourEntryPoint
and this will map to GET
http://host:port/yourapp/yourEntryPoint/new

Resources