Spring Boot / Redirect user to given website

Viewed 51

I am building an App where a new website can be added to the list and I would now like to be able to redirect the user to this given website. How do I do that? For example, a user can add to the list: www.example.com. Clicking the link (inside Index.html) will take the user to the example homepage.

index.html is where I would like the link to appear to the user

    <td><a th:href="@{'/website.link'}">Link</a></td>

new.html page can add links

        <div alight="left">
        <tr>
             <label class="form-label">Link</label>
             <td><input type="text" th:field="*{link}" class="form-control" 
             placeholder="Link" /></td>
        </tr>
        </div>

Notice I don't have anything in the Controller yet.

1 Answers

Consider a Contr-application like:

@Controller
@SpringBootApplication
public class Application {

  private final List<URI> allLinks = Collections.synchronizedList(new ArrayList<>());

  public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
  }

  @ModelAttribute("allLinks")
  public List<URI> allLinks() {
    return allLinks;
  }

  @GetMapping("/")
  public String index() {
    return "index";
  }

  @PostMapping(value = "/", params = "send")
  public void sendMeThere(@RequestParam String link, HttpServletResponse response) throws IOException {
    // response send redirect! (relative/absolute/throws exception)
    response.sendRedirect(link);
  }

  @PostMapping(value = "/")
  public String addLink(@RequestParam String link) throws URISyntaxException {
    links.add(new URI(link)); // throws exception!
    return "redirect:/";
  }
}

We can try it out with an index.html like this:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org" lang="en">
  <head>
    <title>Hello Links</title>
  </head>
  <body>
    <h2>Add More Lnks</h2>
    <form action="" th:action="@{/}" method="post">
      <label>Link</label>
      <input type="text" name="link" 
             placeholder="http://www.example.com" />
      <input type="submit" value="Add Link" />
    </form>
    <hr/>
    <h2>Naviagte via form submit</h2>
    <form action="" th:action="@{/}" method="post">
      <select name="link">
        <option th:each="link : ${allLinks}" th:value="${link}" th:text="${link}" />
      </select>
      <input type="submit" value="Send me There" />
      <input type="hidden" name="send" />
    </form>
    <hr/>
    <h2>Naviagte via link</h2>
    <ul>
      <li th:each="link : ${allLinks}">
        <!-- encapsulate ${link} in thymeleaf url @{...} (relative or absolute) -->
        <a th:href="@{${link}}" th:text="${link}"/>
      </li>
    </ul>
  </body>
</html>

It looks like:

link sample screenshot


References:

Related