简体   繁体   English

Spring 引导 crud 存储库

[英]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我是 spring 的新手并尝试学习基本的 crud 操作,但我坚持删除操作,我的实体如下所示

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我的 home.jsp 文件如下所示

<%@ 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 controller 看起来像下面我想在删除操作中提交按钮,我想根据 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?我错过了什么?

Your understanding on HTTP request is not complete.您对 HTTP 请求的理解不完整。 You are not configuring HTTP method in any API, so all APIs have default method GET.您没有在任何 API 中配置 HTTP 方法,因此所有 API 都有默认方法 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..您应该首先阅读有关 HTTP、RestControllers 的信息。

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.您必须传递要删除的 object 的 ID。 Note that passing name in @Pathvariable is optional if name of your parameter is exact to name of variable which is an argument.请注意,如果您的参数名称与作为参数的变量名称完全相同,则在 @Pathvariable 中传递名称是可选的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM