Majid Majid - 4 months ago 19
Java Question

Spring controller, return to specific area of the page

I have this html file

<!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>


and this controller :

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


What I'm trying to do is return to greeting#rightHere but I can't get it work. Any ideas of how to do this?

Answer Source

This is a solution that worked for me:

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