Search code examples
javamysqlspringintellij-ideathymeleaf

How to display DB items as links Java Spring?


I am studying Java and Spring. I'm doing a small link shortening project (eg www.google.com like gg, etc.). Implemented adding links and displaying them. But after being displayed, these links are not clickable. I tried to use hyperlink, but nothing came of it in the end. How to make links from DB (MySQL) clickable? No repository and class with constructors, getters and setters specified.

Here is my code

@Controller
public class MainController {

    DB db = new DB();

    @Autowired
    private LinkRepository linkRepository;

    @GetMapping("/")
    public String link(Model model) {
        Iterable<Links> links = linkRepository.findAll();
        model.addAttribute("title", "Page with links");
        model.addAttribute("link", links);
        return "link";
    }

    @GetMapping("/uslugi")
    public String uslugi(Model model) {
        model.addAttribute("title", "Page with services");
        return "uslugi";
    }

    @PostMapping("/-add")
    public String linkAdd(@RequestParam String long_link, @RequestParam String short_link, Model model) {
        Links links = new Links(short_link, long_link);
        linkRepository.save(links);

        return "redirect:/";
    }
}

DB

import java.sql.*;

public class DB {

    private final String HOST = "localhost";
    private final String PORT = "3306";
    private final String DB_NAME = "spring";
    private final String LOGIN = "root";
    private final String PASS = "root";

    private Connection dbConn = null;


    private Connection getDbConnection() throws ClassNotFoundException, SQLException {
        String connStr = "jdbc:mysql://" + HOST + ":" + PORT + "/" + DB_NAME +
                "?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";
        Class.forName("com.mysql.cj.jdbc.Driver");

        dbConn = DriverManager.getConnection(connStr, LOGIN, PASS);
        return dbConn;
    }

    public void isConnected() throws SQLException, ClassNotFoundException {
        dbConn = getDbConnection();
        System.out.println(dbConn.isValid(1000));
    }
}

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.java10</groupId>
    <artifactId>serving-web-content</artifactId>
    <version>1.0-SNAPSHOT</version>
    <name>java10</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>



    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><configuration><source>10</source><target>10</target></configuration></plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>8</source>
                    <target>8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

Html, if needed

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <link rel="stylesheet" href="main.css">
</head>

    <header class="d-flex flex-column flex-md-row align-items-center p-3 px-md-4 mb-3 bg-white border-bottom shadow-sm">
        <p class="h5 my-0 me-md-auto fw-normal">Java</p>
        <nav class="my-2 my-md-0 me-md-3">
            <a class="p-2 text-dark" href="/">Главная</a>
            <a class="p-2 text-dark" href="/uslugi">Про нас</a>
        </nav>
    </header>

<body>

<div class="container mt-5">
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory"/>
        <property name="jpaDialect" ref="jpaDialect"/>
    </bean>

    <bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"/>


    <h3 class="mt-2">Все отзывы</h3>

    <div th:each="row : ${link}">
        <h4 class="mt-2" th:text="${row.long_link}"/>
        <h4 th:text="${row.short_link}"/>
    </div>
    <h1 class="mt-5" th:text="${title}"/>

    <form th:action="@{/-add}" method="post">
        <input type="text" name="long_link"
               placeholder="Введите ссылку" class="form-control"><br>
        <input type="text" name="short_link"
               placeholder="Введите короткую ссылку" class="form-control"><br>
        <button type="submit" class="btn btn-success">Добавить</button>
    </form>
</div>
</body>

    <footer class="pt-4 my-md-5 pt-md-5 border-top">
        <div class="row">
            <div class="col-12 col-md">
                <small class="d-block mb-3 text-muted">©2021    Все права защищены</small>
            </div>
        </div>
    </footer>
</html>

Solution

  • Actually, the only thing you'd have to modify to have your links be clickable, is the Thymeleaf template.

    You have to replace the h4 element with an a (anchor element), like so:

    <h4>
      <a th:href="${row.short_link}"
         th:text="${row.short_link}" />
    </h4>
    

    You can read more about the way Thymeleaf can be used to create different types of HTML elements here.