Thymeleaf not showing values on Web with Springboot - java

I'm new to springboot and I'm trying to create a simple website with Springboot and Thymeleaf. I created a HTML table but my table is not being rendered in the web page. This is what I see , this is what it should look like .
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>listado de estudiantes</title>
</head>
<body>
<tbody>
<tr th:each="estudiante : ${estudiantes}">
<td th:text="${estudiante.nombre}">Nombre</td>
<td th:text="${estudiante.apellido}">apelido</td>
<td th:text="${estudiante.email}">email</td>
</tr>
</tbody>
</div>
</body>
</html>
This is my POM Thymeleaf dependency in Springboot
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
Controller
package com.app.web.controlador;
import com.app.web.servicio.EstudianteServicio;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
#Controller
public class EstudianteControlador {
#Autowired
private EstudianteServicio servicio;
#GetMapping({"/estudiantes","/"})
public String listarEstudiantes(Model modelo){
modelo.addAttribute("estudiantes", servicio.listarTodosLosEstudiantes());
return "estudiantes";
}
}
Application properties
spring.datasource.url=jdbc:mysql://localhost:3306/db_crud
spring.datasource.username=root
spring.datasource.password=%password%
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.ddl-auto=none
spring.jpa.show.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
thanks in advance.

Related

Redirection Problem from HTTPS Spring Boot app to External HTTPS URLs

This question is a continuation of this one but now with some changes that I was hoping to solve the initial problem. I have created a Spring Boot app that currently runs on HTTPS. For that matter I used this Youtube guide.
PROBLEM
I can't find a way to redirect from my HTTPS Spring Boot app to URLs on external HTTPS server. I am fetching those URLs from external API through POJO class, store them in PostgreSQL and expose them through Thymeleaf on HTML page. If, for example, my initial URL is
`https://www.investing.com/news/cryptocurrency-news/tether-liquidates-celsius-position-with-no-losses-to-stablecoin-issuer-2845626`
gets chopped off to
https://www.investing.com/
Is it possible while my controller method being invoked as GET request, to simutaneously implement an auto-POST request in order to grab the URLs, have another controller with #RequestBody that deserializes them, returns them as String Values, and returns a redirection to them? In the initial question I made, I used a GET controller with #RequestParam anootation, but I am getting null values.
Controller Method
//Method to handle the HTTP request for showing DB contents
#GetMapping("/show-newscontents")
public String showAllRates(HttpServletRequest request){
request.setAttribute("rates", newsService.showAllRates());
return "newsdbcontents";
}
HMTL Thymeleaf
<!DOCTYPE HTML>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Spring Boot Thymeleaf Hello World Example</title>
<link rel="stylesheet" th:href="#{/webjars/bootstrap/css/bootstrap.min.css}"/>
<link rel="stylesheet" th:href="#{/styles/db.css}"/>
<script type="text/javascript" th:src="#{/webjars/bootstrap/js/bootstrap.min.js}"></script>
</head>
<body>
<ul>
<li>Home</li>
<li>Movies Contents</li>
<li>Github</li>
</ul>
<main role="main" class="container">
<div class="starter-template">
<h1>Cryptocurrency News</h1>
</div>
</main>
<!--Display DB contents on HTML and Thymeleaf-->
<div class="container text-center" id="tasksDiv">
<hr>
<div class="table-responsive">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Related Image</th>
<th>News Provider Name</th>
<th>News Link</th>
</tr>
</thead>
<tbody>
<tr th:each="rate: ${rates}">
<td> <img th:src="${rate.related_image}" alt="error displaying image"> </td>
<td th:text="${rate.news_provider_name}"> </td>
<td>
<a
href="#"
th:href="#{${rate.news_link}}"
th:text="${rate.HEADLINE}">
</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html>
Since I am involving security issues here, I think it is appropiate to mention that I've implemented Spring Security with some simple Basic Auth, as follows.
Security Configuration Class
package com.andrekreou.iot.security;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
//WebSecurityConfigurerAdapter has been deprecated
#Configuration
public class ApplicationSecurityConfig {
#Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.httpBasic();
return http.build();
}
}
Finally I am providing my application.properties file code
Application Properties
spring.datasource.url=jdbc:postgresql://localhost:5432/iot
spring.datasource.username=
spring.datasource.password=
spring.datasource.driver-class-name=org.postgresql.Driver
spring.jpa.hibernate.ddl-auto=create
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.properties.hibernate.format_sql=true
#Server properties for HTTPS configuration
server.ssl.enabled=true
server.ssl.key-store-type=PKCS12
server.ssl.key-store=classpath:local-ssl.p12
server.ssl.key-store-password=
server.ssl.key-password=
server.servlet.context-path=/
server.ssl.key-alias=local_ssl
server.port=8443
#This message will be injected in Welcome MoviesController
welcome.message= User
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.cache=false
server.error.include-message=always

Thymeleaf fragment processor and Spring 5

Could somebody, please, help with Thymeleaf? I need to create a template layout and I've got stuck with <div th:fragment="content"></div>. The point is layout:fragment doesn't replace code on the dashboard page. By the way, other processors like layout:decorate or th:replace works well. I'm using Intellij IDEA with Spring 2.5.4.
My template structure
#dashboard.html
<!DOCTYPE html>
<html xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{admin/share/template.html}">
<head>
<title>Admin dashboard</title>
</head>
<body>
<div layout:fragment="content">
<h1>Admin Dashboard</h1>
</div>
</body>
</html>
#template.html
<!DOCTYPE html>
<html xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
<style th:replace="~{admin/share/style}"></style>
</head>
<body>
<div class="app-container app-theme-white body-tabs-shadow fixed-sidebar fixed-header">
<div th:replace="/admin/share/header"></div>
<div class="app-main">
<div th:replace="/admin/share/sidebar"></div>
<div class="app-main__outer">
<div class="app-main__inner">
<div th:fragment="content">
<p>Page content goes here</p>
</div>
</div>
</div>
</div>
<div th:replace="/admin/share/js"></div>
</div>
</body>
</html>
#pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>nz.net.ultraq.thymeleaf</groupId>
<artifactId>thymeleaf-layout-dialect</artifactId>
<version>3.0.0</version>
</dependency>
#Thymeleaf.class
#Configuration
public class Thymeleaf {
#Bean
public LayoutDialect layoutDialect() {
return new LayoutDialect();
}
}
Result of Dashboard page
UPDATE:
The issue is solved. Just need to use layout:fragment instead of th:fragment =)
Just need to use layout:fragment instead of th:fragment =)

Client side error, I guess related to utf-8 or something related to form tags. But can't solve it

I am trying to submit form request with Spring MVC form and add data to db with Hibernate. But it shows such error "The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing)."
I researched this question and looked through almost all related questions here, but can't find appropriate for me solution.
My jsp file
<%# page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<title>New Plan Form</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css"
href="${pageContext.request.contextPath}/resources/css/new-plan-form.css">
<link rel="stylesheet" type="text/css"
href="${pageContext.request.contextPath}/resources/js/jquery.datetimepicker.min.css">
<script type="text/javascript" src="${pageContext.request.contextPath}/resources/js/jquery.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/resources/js/jquery.datetimepicker.full.js"></script>
</head>
<body>
<h2>New Plan Form</h2>
<div class="container">
<form:form action="saveNewPlan" modelAttribute="newPlan" method="POST" acceptCharset="utf-8">
<div class="row">
<div class="col-25">
<label for="fname">Title</label>
</div>
<div class="col-75">
<form:input path="title" id="title" name="title"
placeholder="Title" />
</div>
</div>
<div class="row">
<div class="col-25">
<label for="subject">Description</label>
</div>
<div class="col-75">
<form:textarea path="description" id="description"
name="description" placeholder="Write about plan in detail"
style="height:200px" />
</div>
</div>
<div class="row">
<div class="col-25">
<label for="lname">Begin Date</label>
</div>
<div class="col-75">
<form:input path="beginDate" id="beginDate" name="beginDate"
placeholder="When you will begin to realize this plan" />
<script type="text/javascript">
$("#beginDate").datetimepicker();
</script>
</div>
</div>
<div class="row">
<div class="col-25">
<label for="lname">End Date</label>
</div>
<div class="col-75">
<form:input path="endDate" id="endDate" name="endDate"
placeholder="Until when you should finish this plan" />
<script type="text/javascript">
$("#endDate").datetimepicker();
</script>
</div>
</div>
<div class="row">
<input type="submit" value="Submit">
</div>
</form:form>
</div>
</body>
</html>
My request handler method for that form action in my UserController class
#Controller
#RequestMapping("/user")
public class UserController {
#PostMapping("/saveNewPlan")
public String savePlan(#ModelAttribute("newPlan") Plan thePlan) {
planService.savePlan(thePlan);
return "home-page";
}
}
And the ViewResolver part of my Config file
package com.todolist.webbapp.config;
import java.beans.PropertyVetoException;
import java.util.Properties;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import com.mchange.v2.c3p0.ComboPooledDataSource;
#Configuration
#EnableTransactionManagement
#EnableWebMvc
#ComponentScan(basePackages = "com.todolist.webbapp")
#PropertySource("classpath:persistence-mysql.properties")
public class WebAppConfig implements WebMvcConfigurer {
#Autowired
private Environment env;
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/view/");
viewResolver.setSuffix(".jsp");
viewResolver.setContentType("text/html ; charset=UTF-8");
return viewResolver;
}

Unable to render thymleaf page from Spring-Boot controller. Prints only the return string in output

Issue : I have developed a Spring-Boot rest api which I can call from POSTMAN. Now I am requesting the same REST API method from a Thymleaf page. But it renders only a string. The actual page doesn't gets loaded..
This is my controller :
#RestController
#RefreshScope
#RequestMapping("/shopping")
public class ShoppingController {
#RequestMapping(value="/productList")
public String listAllProducts(ModelMap model){
logger.info("ShoppingMS : listAllProducts()");
ResponseEntity<List<Product>> responseProductList = prodServ.listAllProducts();
List<Product> products = responseProductList.getBody();
if(products.isEmpty()) {
logger.info("No Products Found");
}
logger.info("No of products fetched : " +products.size());
model.addAttribute("products", products);
return "productList";
}
}
This is my Thymleaf page productsList.html :
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
<meta charset="UTF-8">
<title>Product List</title>
<link rel="stylesheet" type="text/css" th:href="#{/css/styles.css}">
</head>
<body>
<th:block th:include="/_header"></th:block>
<th:block th:include="/menu"></th:block>
<div class="page-title">Product List</div>
<div class="product-preview-container"
th:each="prodInfo : ${products.list}">
<ul>
<li>Product Code: <span th:utext="${prodInfo.productCode}"></span></li>
<li>Product Name: <span th:utext="${prodInfo.productName}"></span></li>
<li>Product Price: <span th:utext="${#numbers.formatDecimal(prodInfo.productPrice,3,2,'COMMA')}"></span></li>
<li><a th:href="#{|/buyProduct?code=${prodInfo.code}|}">Buy Now</a></li>
</ul>
</div>
<br />
<div class="page-navigator">
<th:block th>
<a th:href="#{|/productList|}" class="nav-item"></a>
<span class="nav-item" > ... </span>
</th:block>
</div>
<th:block th:include="/_footer"></th:block>
</body>
</html>
Maven Dependency for Thymleaf
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
Project Structure Image
Output :
Calling URL : http://localhost:1000/shopping/productList
It returns only the string `productList` in the page.
Please tell me where I am doing wrong. I am able to render a index.html page. But not this page.
That's because you are using #RestController annotation on top of your controller, which is nothing but #Controller+#ResponseBody.
Try to use only #Controller and then based on your method use #ResponseBody exclusively.
For example . If you want to return json response body then use #ResponseBody on method.
If you want to render thymeleaf page then don't use #ResponseBody.

why Thymeleaf's th:text not working in my Spring project?

I have included Thymeleaf for my Spring project for the first time and want to create a simple project(display one word using th:text). But I get nothing in my html page. Why?
Greeting.java
package com.supermegaproject.Main;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
#Controller
public class Greeting
{
#GetMapping("/")
public String getMessage(Model model)
{
model.addAttribute("name", "John");
return "mainPage";
}
}
mainPage.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Title</title>
</head>
<body>
<h1>Main Page</h1> // DOES APPEAR
<h1 th:text="${name}"></h1> // DOESN'T APPEAR AT ALL
</body>
</html>
At first I thought it may be because of build.gradle. But after checking it looks ok, thymeleaf included, so I don't know why then.
compile('org.springframework.boot:spring-boot-starter-thymeleaf')
Thank you in advance.
I solved it. All you had to do - is to delete Mustache dependency.

Categories