Rohan Gaonkar
Rohan Gaonkar

Reputation: 3

Spring boot crud repository

I am new to spring and trying to learn basic crud operations but I am stuck with delete operation my entity looks like following

public class Alien {
@Id
int aid;
String aname;
public int getAid() {
    return aid;
}
public void setAid(int aid) {
    this.aid = aid;
}
public String getAname() {
    return aname;
}
public void setAname(String aname) {
    this.aname = aname;
}

My home.jsp file looks like the following

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<form action="addAlien">
<input type="text" name="aid"><br>
<input type="text" name="aname"><br>
<input type="submit"><br>
</form>

<form action="deleteAlien">
<input type="text" name="aid"><br>
<input type="submit"><br>
</form>
</body>
</html>

And controller looks like following i want submit button in delete operation where i want to delete entry bases on id

public class HomeController {
@Autowired
Alienrepo alienrepo;

@RequestMapping("/")
public String home() {
  return "home.jsp";
  }

@RequestMapping("/addAlien")
public String addAlien(Alien alien) {
    alienrepo.save(alien);
    return "home.jsp";

}
@RequestMapping("/deleteAlien")
public String deleteAlien(Integer id) {
    alienrepo.deleteById(id);
    return "home.jsp";
}
}

What is that I am missing?

Upvotes: 0

Views: 217

Answers (2)

Kamila Nowak
Kamila Nowak

Reputation: 59

It should look like this:

@RequestMapping("/deleteAlien/{id}")
public String deleteAlien(@PathVariable int id) {
    alienrepo.deleteById(id);
    return "home.jsp";
}

You have to pass the id of the object you would like to delete. Note that passing name in @Pathvariable is optional if name of your parameter is exact to name of variable which is an argument.

Upvotes: 1

user9065831
user9065831

Reputation:

Your understanding on HTTP request is not complete. You are not configuring HTTP method in any API, so all APIs have default method GET. You need to configure the parameter you are sending in the request. Like :

@RequestMapping("/deleteAlien/{id}")
public String deleteAlien(@PathVariable("id") Integer id) {
    alienrepo.deleteById(id);
    return "home.jsp";
}

You should read about HTTP, RestControllers first..

Upvotes: 1

Related Questions