【问题标题】:Spring not finding @GetMapping and @PostMapping with urlSpring没有找到带有url的@GetMapping和@PostMapping
【发布时间】:2022-11-13 07:53:05
【问题描述】:

我正在构建一个博客应用程序,在这种情况下,我想创建一个新帖子。我用@GetMapping 和@PostMapping 创建了一个控制器,值为“/posts/new”。我用了 th:action = "@{'/posts/new'}" (LINE 14) 在 thymeleaf 中,但是当我启动网络应用程序并访问 localhost:8080/posts/new 时,它给出了 404 错误,指出找不到 url,但它在那里……我仔细检查了拼写,代码...几乎所有内容,但似乎无法弄清楚我犯了什么错误。这是代码:

post_new.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Blog :: New Post</title>
</head>

<body>
<div class="container">
    <a th:href="@{/}">Home</a>
    <form action="#"
          th:action="@{'/posts/new'}"
          th:object="${post}">
        <input type="hidden" th:field="*{account}" />
        <input type="hidden" th:field="*{createdAt}" />
        <h2>Write new post</h2>
        <div>
            <label for="new-post-title">Title</label>
            <input id="new-post-title" type="text" th:field="*{title}" placeholder="Title"/>
        </div>
        <div>
            <label for="new-post-body">Body</label>
            <textarea id="new-post-body" th:field="*{body}"></textarea>
        </div>
        <button type="submit">Publish post</button>
    </form>
</div>
</body>
</html>

PostController.java

package com.hellion.writeup.controller;

import com.hellion.writeup.models.Account;
import com.hellion.writeup.models.Post;
import com.hellion.writeup.service.AccountService;
import com.hellion.writeup.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.Optional;

@Controller
public class PostController {

    @Autowired
    private PostService postService;

    @Autowired
    private AccountService accountService;


    @GetMapping("/posts/{id}")
    public String getPost(@PathVariable Long id, Model model) {
        Post post = postService.getPost(id, model);

        if (post != null) {
            model.addAttribute("post", post);
            return "post";
        } else {
            return "404";
        }
    }

    @GetMapping("/posts/new")
    public String createNewPost(Model model){
        return postService.createNewPost(model);
    }

    @PostMapping("/posts/new")
    public String saveNewPost(@ModelAttribute Post post){
        postService.save(post);
        return "redirect:/posts/" + post.getId();
    }
}

PostService.java

package com.hellion.writeup.service;

import com.hellion.writeup.models.Account;
import com.hellion.writeup.models.Post;
import com.hellion.writeup.repository.PostRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
public class PostService {

    @Autowired
    private PostRepository postRepository;

    @Autowired
    private AccountService accountService;;

    public Optional<Post> getById(Long id) {
        return postRepository.findById(id);
    }

    public List<Post> getAll() {
        return postRepository.findAll();
    }

    public Post save(Post post) {
        if (post.getId() == null) {
            post.setCreatedAt(LocalDateTime.now());
        }

        return postRepository.save(post);
    }

    public Post getPost(Long id, Model model) {
        Optional<Post> optionalPost = getById(id);

        if (optionalPost.isPresent()) {
            Post post = optionalPost.get();
            return post;
        }
        return null;
    }

    public String createNewPost(Model model){
        Optional<Account> optionalAccount = accountService.findByEmail("user.user@domain.com");

        if(optionalAccount.isPresent()){
            Post post = new Post();
            post.setAccount(optionalAccount.get());
            model.addAttribute("post", post);
            return "post_new";
        }else{
            return "404";
        }
    }
}

post.html

<!DOCTYPE HTML>
<html  land= "en" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE-edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link th:href="@{/styles/style.css}" rel="stylesheet" />
  <title>Writeup :: Post</title>
</head>
<body>
<div class ="container">
  <a th:href="@{'/'}">Home</a>
  <div class="post">
    <h2 th:text="${post.title}">Title</h2>
    <h5 th:text="'Written by: ' + ${post.account.getFirstName()}">Account First Name</h5>
    <h5 th:text="'Created on: ' + ${post.createdAt}">Created At</h5>
    <p th:text="${post.body}">Body text</p>
  </div>
</div>
</body>
</html>

【问题讨论】:

    标签: java spring spring-boot thymeleaf


    【解决方案1】:

    /posts/newGET 方法调用服务层中的createNewPost 方法。如果optionalAccount 不存在,则返回页面404。一个可能的问题是optionalAccount 为空,因此返回404

    if(optionalAccount.isPresent()) {
        Post post = new Post();
        post.setAccount(optionalAccount.get());
        model.addAttribute("post", post);
        return "post_new";
    } else {
        return "404";
    }
    

    th:action 应该是 th:action="@{/posts/new}"

    【讨论】:

      【解决方案2】:

      我找到了解决方案......所以基本上,我得到了stackoverflow错误,解决方案是,因为我在我的“模型”包中使用了Lombok和@Data注释,@Data导致了一些错误并将其更改为@ Getter 和@Setter 问题已解决。

      【讨论】:

        猜你喜欢
        • 2022-01-07
        • 1970-01-01
        • 1970-01-01
        • 2022-11-18
        • 1970-01-01
        • 2020-07-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多