簡體   English   中英

Spring controller,返回頁面特定區域

[英]Spring controller, return to specific area of the page

我有這個 html 文件

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Getting Started: Handling Form Submission</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
    <h1>Form</h1>
    <form action="#" th:action="@{/greeting}" th:object="${greeting}" method="post">
        <p>Id: <input type="text" th:field="*{id}" /></p>
        <p>Message: <input type="text" th:field="*{content}" /></p>
        <p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
    </form>

    <div style="height: 1200px">
    </div>

    <p id="rightHere">
      There there
    </p>
</body>
</html>

還有這個 controller:

@GetMapping("/greeting")
public String greetingForm(Model model) {
    model.addAttribute("greeting", new Greeting());
    return "greeting";
}

我想要做的是返回問候#rightHere,但我無法讓它工作。 關於如何做到這一點的任何想法?

這是對我有用的解決方案:

@GetMapping("/greeting")
public String greetingForm(Model model) {
    model.addAttribute("greeting", new Greeting());
    return "redirect:greeting#rightHere";
}

我認為說“ return greeting#rightHere ”沒有任何意義。 那是一個超鏈接,如果您正在創建REST API,那么您將返回超鏈接。 不知道像Spring這樣的框架是否甚至知道#之后的內容。 #假定用於瀏覽器,如果存在,它將為您滾動到該元素。 盡管我可能是錯的,但是我相信Spring Controller不會知道greeting#rightHere的get URL請求和greeting之間的區別,而無需訪問底層的HTTP請求對象(大多數情況下,您永遠都不要這樣做)的行為。您的應用程序應該相同。

我建議您進行測試,確保頁面上分配了文本,以便您可以注意到跳轉到id = rightHere的html元素。 並且在您的應用程序中的/greeting#rightHere某處有一個超鏈接,看看它是否有效。 我認為可以,您不必在Spring控制器中做任何事情。

編輯:我認為目前尚不清楚在問什么。 我假設您的意思是,當您單擊網頁/greeting#rightHere上的鏈接時,您希望網絡瀏覽器導航到問候頁面,然后滾動到id為rightHere的html元素。 我告訴您Spring對#后面的內容一無所知,#是用於瀏覽器的,瀏覽器本身將查看URL /greeting#rightHere ,導航至greeting,然后查找一個ID為rightHere的HTML元素,並在頁面加載后滾動到此處。

但是也許您的意思是您希望您的控制器返回問候語頁面的一個小節,就像僅在rightHere元素中那樣,您可以使用模板或包含在JSP中。 但是很難確定您要問的是什么,因為您似乎不明白我在寫什么,並且混在一起談論兩種不同的事物,即返回和跳躍……請考慮重新編寫問題並保持簡潔實現使用正確的語言。

對我來說,它是這樣工作的:

在模板(index.html):

<div id="index-section4">
...
<form id="addLeaduser" th:action="@{/save}" method="POST" 
th:object="${leaduser}">
 ...
 <input  type="submit" value="Apply">
 </form>
 ...
</div>

在索引控制器:

@PostMapping("/save")
public String saveLeaduser(@ModelAttribute("leaduser")
                                   LeaduserEntity leaduser,
                           @RequestParam(name="g-recaptcha-response")
                                   String captcha, Model model)
{
...
return "redirect:#index-section4";
}

模板索引只有一個。html,提交表單后跳轉到表單位置,本例為頁面底部。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM