I'm learning Spring Boot and just started to see H2-Database. I managed to send a HTTP GET Request to insert a new line on my database, but I can't delete it.
This is how I inserted a new line:
@GetMapping("/addAlien")
public String addAlien(Alien alien) {
rep.save(alien);
return "home.jsp";
}
This is the JSP code I'm using to send the GET Request:
<form action="addAlien">
<input type="text" name="id"><br>
<input type="text" name="name"><br>
<input type="text" name="points"><br>
<input type="submit"><br>
</form>
And this is the SQL file that I'm using to fill the H2-Database
insert into alien values (101, 'Bilu', 100)
insert into alien values (102, 'Vargínia', 100)
insert into alien values (103, 'Meeseek', 100)
insert into alien values (104, 'Jack', 100)
insert into alien values (105, 'MrPopButthole', 100)
I have another form like the one that I used to send the GET Request, but to submit the "/deleteAlien". And the submit activates the code below, although it doesn't work:
@DeleteMapping("/deleteAlien")
public int deleteAlien(@RequestParam int id) {
rep.deleteById(id);
ModelAndView mv = new ModelAndView("showAlien.jsp");
Alien alien = rep.findById(id).orElse(null);
mv.addObject(alien);
return id;
}
After submiting I get this error here:
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Thu Sep 19 06:12:27 BRT 2019
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...
What I want to do is specify a "int id" through a form, then delete the line that has an equal id.
SOLUTION: I managed to solve the problem using Postman to send the correct HTTP Request. It works, but I would appreciate if someone guided me to do it using a jsp.file and a form.
This is the code that works:
@DeleteMapping("/alien/{id}")
public String deleteAlien(@PathVariable("id") int id) {
Alien a = rep.getOne(id);
rep.delete(a);
return "deleted";
}
I just have to open Postman and config it to send a DELETE using localhost:8080/alien/id
.