【问题标题】:Java Spring simple HTML LinkJava Spring 简单的 HTML 链接
【发布时间】:2019-01-31 01:27:48
【问题描述】:

我对 Spring Webapplication 还很陌生,需要为大学做一个小项目。目前我有一个简单的 html 站点,其中显示了一些我手动插入到数据库中的数据。

现在我正在处理一个新的 html 文件,以通过单独的表单插入数据。 在我的“主”页面上,我有一个导航栏,我想在其中单击一个项目并重定向到特定页面。 我尝试将链接直接重定向到资源文件夹中的 html 文件,但它似乎不起作用。

<li class="nav-item active">
    <a class="nav-link" href="/inputbook.html">Add Book <span class="sr-only">(current)</span></a>
</li>

我也尝试通过以下方式链接它:

  • “${pageContext.servletContext.contextPath}/inputbook.html”(在另一个线程中找到)
  • "./inputbook.html"
  • "../inputbook.html"

有没有办法简单地链接这个页面或者我需要在控制器中做一个动作+一个方法?

谢谢!

更新:

刚刚发生了一件有趣的事。我在控制器中添加了映射站点的方法。 当我尝试通过导航栏打开此站点时,它告诉我它未映射。现在(为了测试,我的主页中也有来自“inputbook.html”文件的表单)当我通过主页表单输入数据时,它会将其保存到数据库并正确显示。在此过程之后,当我再次单击导航栏时,它会打开“inputbook.html”站点而没有任何问题?

控制器:

@RequiredArgsConstructor
@Controller
@RequestMapping("/books")
public class BookController {
private final BookService bookService;
private final BookRepository bookRepository;

@GetMapping
public String showBooks(Model model) {
    List<Book> books = bookService.findAll();
    model.addAttribute("books",books);
    return "books"; //view name
}

@PostMapping(value="/search")
public String serachByTitle(Model model, @RequestParam Optional<String> searchTerm) {//Parameter heißt wie Feld in html form
    List<Book> books = searchTerm.map(bookService::findByTitleLike)
            .orElseGet(bookService::findAll);
    model.addAttribute("searchTerm",searchTerm.get());
    model.addAttribute("books",books);
    return "books";
}

@GetMapping("inputbook.html")
public String inputbook() {
    return "inputbook"; // this returns the template name to be rendered from resources/templates. You don't need to provide the extension.
}
@PostMapping(value="/insert")
public String insertBook(Model model,@RequestParam String title) {
    Book book = Book.builder()
            .title(title)
            .description("beschreibung")
            .author("auth" )
            .isbn(12353)
            .creator("creator") // fake it till spring security
            .creationTS(LocalDateTime.MIN)
            .publisher("pub")
            .available(true)
            .deliveryTimeDay(2)
            .build();
    bookRepository.save(book);
    return showBooks(model);
}

}

books.html(“主”页)

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Books</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
          integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"/>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
        <ul class="navbar-nav mr-auto">
            <li class="nav-item active">
                <a class="nav-link" href="inputbook.html">Add Book <span class="sr-only">(current)</span></a>
            </li>
            <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
            </li>
            <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
            </li>
        </ul>
    </div>
</nav>
    <div class="container">
        <form method="post" th:action="@{/books/search}">
             <div class="form-group">
                <label th:for="searchTerm">Searchterm</label>
                <input type="text" class="form-control" th:name="searchTerm">
            </div>
            <button type="submit" class="btn btn-primary">Search</button>
        </form>

        **<form method="post" th:action="@{/books/insert}">
            <div class="form-group">
                <label th:for="title">Titel</label>
                <input type="text" class="form-control" th:name="title">
            </div>
            <button type="submit" class="btn btn-primary">Save</button>
        </form>**
        <table  class="table">
            <thead>
                <tr>
                    <th>Title</th>
                    <th>CreationTS</th>
                    <th>Author</th>
                    <th>Creator</th>
                </tr>
            </thead>
            <tbody>
                <tr th:each="book : ${books}">
                    <td th:text="${book.title}">Betreff</td>
                    <td th:text="${book.creationTS}">2018-01-01 10:01:01</td>
                    <td th:text="${book.author}">TestAuthor</td>
                    <td th:text="${book.creator}">TestCreator</td>
                </tr>
            </tbody>
        </table>
    </div>
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
            integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
            crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"
            integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49"
            crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"
            integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy"
            crossorigin="anonymous"></script>
</body>
</html>

inputbook.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Books</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
          integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"/>
</head>
<body>
<div class="container">
    <form method="post" th:action="@{/books/insert}">
        <div class="form-group">
            <label th:for="title">Titel</label>
            <input type="text" class="form-control" th:name="title">
        </div>
        <button type="submit" class="btn btn-primary">Save</button>
    </form>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
        integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
        crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"
        integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49"
        crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"
        integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy"
        crossorigin="anonymous"></script>

</body>
</html>

【问题讨论】:

    标签: java html spring-mvc spring-boot


    【解决方案1】:

    确保您在控制器中有一个方法映射到此 URL /inputbook.html 并返回您希望看到的页面,如下所示。

    @GetMapping("inputbook.html")
      public String method() {
        return "inputbook.html"; //extension depends on view resolver.
    }
    

    如果您不想在加载页面之前执行任何业务逻辑,那么您现在需要在控制器中创建一个方法,可以直接使用如下。

    XML 配置(Spring-mvc):

    <mvc:view-controller path="/"view-name="index"/>
    

    注解配置(Spring-boot):

    @Override
    public void addViewControllers(ViewControllerRegistry registry){
    registry.addViewController("/").setViewName("index");
    }
    

    【讨论】:

    • 刚刚发生了一些有趣的事情。我将您的方法添加到我的控制器中以映射“inputbook.html”。当我尝试通过导航栏打开此站点时,它告诉我它未映射。现在(为了测试,我的主页中也有来自“inputbook.html”文件的表单)当我通过主页表单输入数据时,它会将其保存到数据库并正确显示。在此过程之后,当我再次单击导航栏时,它会打开“inputbook.html”站点而没有任何问题?我将使用 html 文件和我的控制器更新我的帖子
    • 一旦我注释掉主页上的表格,它就可以正常工作了。谢谢!
    【解决方案2】:

    最简单最干净的方法是定义一个简单的 Spring Controller 来处理请求。因此 HTML 文件将被渲染。 你用的是什么模板引擎?你在使用 Spring Boot 吗?你有代码吗?

    此类控制器的示例:

    @Controller
    public class SimpleController {
    
      @GetMapping("inputbook.html")
      public String inputbook() {
        return "inputbook"; // this returns the template name to be rendered from resources/templates. You don't need to provide the extension.
      }
    }
    

    【讨论】:

    • 嗨迈克尔,谢谢你的帮助!我正在使用百里香叶。我应该发布什么代码?我的控制器和 html 文件?
    • 刚刚发生了一些有趣的事情。我将您的方法添加到我的控制器中以映射“inputbook.html”。当我尝试通过导航栏打开此站点时,它告诉我它未映射。现在(为了测试,我的主页中也有来自“inputbook.html”文件的表单)当我通过主页表单输入数据时,它会将其保存到数据库并正确显示。在此过程之后,当我再次单击导航栏时,它会打开“inputbook.html”站点而没有任何问题?我将使用 html 文件和我的控制器更新我的帖子
    • 一旦我注释掉主页上的表单,它就可以正常工作了。谢谢!
    • 嗯很奇怪,有时它可以工作,有时映射不起作用。我认为这取决于我目前所处的道路。当我启动应用程序并尝试单击链接时,它不起作用。只要我点击我的搜索按钮,然后点击链接,它就可以正常工作......
    猜你喜欢
    • 2011-04-08
    • 2015-03-18
    • 1970-01-01
    • 2023-03-26
    • 2016-12-21
    • 1970-01-01
    • 2021-10-26
    • 2016-05-08
    • 1970-01-01
    相关资源
    最近更新 更多