简体   繁体   English

为什么我的控制器中的保存功能不起作用?

[英]Why the function save in my controller does not work?

I am doing a simple crud with springboot and thymeleaf but when i try to do the update or create with the function save I lose the data of the object.我正在用 springboot 和 thymeleaf 做一个简单的 crud,但是当我尝试使用函数 save 进行更新或创建时,我丢失了对象的数据。 I click on the buttons new and update I open the modal correctly with the data with the object charged but when i click in save i loss the object.我点击新按钮和更新按钮,我用充电对象的数据正确打开模态,但是当我点击保存时,我丢失了对象。

I believe that my problem is in the form and I do not know what it is.我相信我的问题在形式上,我不知道它是什么。 I have tried with postman and I do not receive a request when I click on save or update我尝试过邮递员,但在单击保存或更新时没有收到请求

index:指数:

    <!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script th:src="@{js/main.js}" src="../static/js/main.js"></script>
  </body>
</head>
<body>

    <div class="container">
        <div class="jumbotron">
            <h1>Paginación con SpringBoot</h1>
        </div>  
        <button class="btn btn-success nBtn">New</button>
        <div class="card">
            <div class="card-block">
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>COUNTRY</th>
                            <th>CAPITAL</th>
                            <th>ACTION</th>
                        </tr>   
                    </thead>
                    <tbody>
                        <tr th:each="country :${data.content}">
                            <td th:text="${country.id}"></td>
                            <td th:text="${country.name}"></td>
                            <td th:text="${country.capital}"></td>
                            <td>
                                <a th:href="@{/delete/(id=${country.id})}" class="btn btn-danger dBtn">Delete</a>
                                <a th:href="@{/findOne/(id=${country.id})}" class="btn btn-primary eBtn">Edit</a>
                            </td>
                        </tr>   
                    </tbody>
                </table>
                <hr>
            </div>
            <div>
                <ul class="nav nav-pills  nav-justified">
                    <li class="nav-item" th:each="i :${#numbers.sequence(0,data.totalPages-1)}">
                        <a th:href="@{/(page=${i})}" th:text="${i}" class="nav-link" th:classappend="${currentPage}==${i}?'active':''"></a>
                    </li>   
                </ul>
            </div>
        </div>


        <div class="myForm">
     <form th:action="@{/save}" th:object="${country}" method="post">
        <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
          <div class="modal-dialog" role="document">
            <div class="modal-content">
              <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLabel">Update or Create</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                  <span aria-hidden="true">&times;</span>
                </button>
              </div>
              <div class="modal-body">
                  <div class="form-group">
                    <label for="id" class="col-form-label">Id:</label>
                    <input type="text" class="form-control" id="id" name="id" th:value="*{''}" disabled/>
                  </div>
                  <div class="form-group">
                    <label for="name" class="col-form-label">Name:</label>
                    <input type="text" class="form-control" id="name" name="name" th:value="*{''}"/>
                  </div>
                  <div class="form-group">
                    <label for="capital" class="col-form-label">Capital:</label>
                    <input type="text" class="form-control" id="capital" name="capital" th:value="*{''}"/>
                  </div>                      
              </div>
              <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <input type="submit" class="btn btn-primary" data-dismiss="modal" value="Save"/>
              </div>
            </div>
          </div>
        </div>
        </form>
    </div>
        <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
          <div class="modal-dialog" role="document">
            <div class="modal-content">
              <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                  <span aria-hidden="true">&times;</span>
                </button>
              </div>
              <div class="modal-body">
              <p class="alert alert-danger">Are you sure you want to delete this?</p>
              </div>
              <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <a href="" class="btn btn-danger" id="delRef">Delete</a>
              </div>
            </div>
          </div>
        </div>
    </div>


</body>
</html>

controller :控制器 :

        @Controller
public class CountryController {

    @Autowired
    private CountryRepository countryRepository;

    @SuppressWarnings("deprecation")
    @GetMapping("/")
    public String showPage(Model model, @RequestParam(defaultValue="0") int page) {
        model.addAttribute("data", countryRepository.findAll(new PageRequest(page,4)));
        model.addAttribute("currentPage", page);
        return "index";
    }

    @PostMapping("/save")
    public String save(Country country) {
        countryRepository.save(country);
        return "redirect:/";
    }

    @GetMapping("/delete")
    public String deleteCountry(Integer id) {
        countryRepository.deleteById(id);;
        return "redirect:/";
    }

    @GetMapping("/findOne")
    @ResponseBody
    public Optional<Country> FindOne(Integer id) {
        return  countryRepository.findById(id);


    }
}

js: js:

    $(document).ready(function(){
$('.nBtn, .table .eBtn').on('click', function(event){
    event.preventDefault();
    var href = $(this).attr('href');
    var text = $(this).text();
    if(text=='Edit'){
        $.get(href,function(country,status){
            $('.myForm #id').val(country.id);
            $('.myForm #name').val(country.name);
            $('.myForm #capital').val(country.capital);
        });
        $('.myForm #exampleModal').modal();
    }else{
        $('.myForm #id').val('');
        $('.myForm #name').val('');
        $('.myForm #capital').val('');
        $('.myForm #exampleModal').modal();
    }
});
$('.table .dBtn').on('click', function(event){
    event.preventDefault();
    var href = $(this).attr('href');
    $('#myModal #delRef').attr('href',href);
    $('#myModal').modal();
});});

class:班级:

@Entity
public class Country {

    @Id
    @GeneratedValue
    private Integer id;
    private String name;
    private String capital;


    public Country(String name, String capital) {
        this.name = name;
        this.capital = capital;
    }

    public Country() {
    }


    @Override
    public String toString() {
        return "Country [id=" + id + ", name=" + name + ", capital=" + capital + "]";
    }


    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getCapital() {
        return capital;
    }
    public void setCapital(String capital) {
        this.capital = capital;
    }
}

repository:存储库:

public interface CountryRepository extends JpaRepository<Country,Integer>{

}

Possibly missing the @RequestBody annotation on the save method可能缺少 save 方法上的 @RequestBody 注释

@PostMapping("/save")
public String save(@RequestBody Country country) {
    countryRepository.save(country);
    return "redirect:/";
}}
  • @RequestBody as mentioned already. @RequestBody 已经提到过。
  • Provide your country class code提供您的国家/地区类别代码
  • What is the code for CountryRepository? CountryRepository 的代码是什么?
  • If you put a break point in your controller save method do you actually get country data or is it null?如果您在控制器保存方法中放置一个断点,您实际上是获得了国家/地区数据还是为空?

As an aside you shouldn't be hitting your repository from your controller as there is no transaction management.顺便说一句,您不应该从控制器访问您的存储库,因为没有事务管理。

Use @RequestBody and repository.saveAndFlush(entity)使用@RequestBodyrepository.saveAndFlush(entity)

By using @RequestBody annotation you will get your values mapped with the model you created in your system for handling any specific call通过使用@RequestBody注释,您将获得与您在系统中创建的模型映射的值,以处理任何特定调用

On saveAndFlush , changes will be flushed to DB immediately in this command.saveAndFlush ,更改将在此命令中DB immediately刷新到DB immediately With save, this is not necessarily true and might stay just in memory, until flush or commit commands are issued.使用保存,这不一定是真的,并且可能只保留在内存中,直到发出刷新或提交命令。

@PostMapping("/save")
    public String save(@RequestBody Country country) {
        countryRepository.saveAndFlush(country);
        return "redirect:/";    
    }

@mantamusica if you are still interested in, I have a solution for you. @mantamusica如果您仍然感兴趣,我为您提供解决方案。

@Jason Portnoy @Patel Romil @Jason Portnoy @Patel Romil

In this exact case, add annotations @RequestBody returns error code 415.在这种确切的情况下,添加注释@RequestBody返回错误代码 415。

The solution to this problem lies on the HTML side, or rather Bootstrap.这个问题的解决方案在于 HTML 端,或者更确切地说是 Bootstrap。

Just delete删除即可

data-dismiss="modal"

from input从输入

 <div class="modal-footer">
    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
    <input type="submit" class="btn btn-primary" data-dismiss="modal" value="save"/>
  </div>

... and it works for me :) ...它对我有用:)

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

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