Thymeleaf Template Engine do not follow the expression language - java

Spring boot Maven dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
#Service
public class MailContentBuilder {
private TemplateEngine templateEngine;
#Autowired
public MailContentBuilder(TemplateEngine templateEngine) {
this.templateEngine=templateEngine;
}
public String build(String templateName,String user,String email) throws IOException {
Context context=new Context();
context.setVariable("user", "Alpha");
context.setVariable("email", "alpha#gmail.com");
String test=templateEngine.process(templateName, context);
return test;
}
}
this is my mail sender method.
MimeMessage mimeMessage=javaMailSender.createMimeMessage();
//mimeMessage.setContent(mailContentBuilder.build("changepassword","alpha","ema il#email.com"), "text/html");
MimeMessageHelper helper=new MimeMessageHelper(mimeMessage);
helper.setTo(auth0UserService.getUser(userid).getEmail());
helper.setFrom(fromUsername);
helper.setSubject("Password Change Confirmation");
helper.setText(mailContentBuilder.build("changepassword","alpha","email#email.com"), true);
javaMailSender.send(mimeMessage);
this is my template, in src/resources/templates
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Change password</title>
</head>
<body >
helloooo th:text="${user}"
</body>
</html>
This is what it sends, it does not follow the expression language, but writes to the page as it is. no use of variables.
helloooo th:text="${user}"

th:text has to be an attribute to an html tag, so something like
<p th:text="helloooo ${user}" />
should work, judging from a glance at http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#using-texts

Related

Data returned from controller is not displayed in thymeleaf page

I am using thymeleaf for the first time.I was trying to display the details returned from controller class.Nothing is getting displayed in the front end.I am pasting my code below.Please help.
Controller class
#RequestMapping(value = "/getNews", method = RequestMethod.GET)
public String getNews(Model model) {
try {
model.addAttribute("ExampleBeans", newsService.getNews());
System.out.println(" Test" + model.toString());
} catch (Exception e) {
System.out.println(e);
}
return "news";
}
Response is getting printed correctly in sysout
Html
<!DOCTYPE html>
<html lang="en"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" media="all"
href="../../css/gtvg.css" th:href="#{/css/gtvg.css}" />
<title>News</title>
</head>
<body>
<table>
<tbody>
<p th:text="${ExampleBeans.size()}"> </p>
<tr th:each="ExampleBean : ${ExampleBeans}">
<td>inside loop</td>
<td th:text="${ExampleBean.author}"> </td>
<td th:text="${ExampleBean.title}"> </td>
</tr>
</tbody>
</table>
</body>
</html>
Only inside loop is getting printed when i am try to load url from chrome.
Bean Class
public class ExampleBean {
private Long id;
private String author;
private String title;
//getter and setters
Thymeleaf Dependency added
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
Can anyone please help me with this?
Thanks In Advance

Spring Boot ignores CSS / JS when loading page

My page (order.mustache) uses several CSS styles (external and local), images, background video and JS element. Most of the page layout is described in style.css, which is located in the 'resourses/static/css' directory.
When I start a page through Chrome as an HTML document, it displays correctly. But if I run it through Spring Boot (as a mustache page) - all local styles, images, JS and even youtube videos are ignored.
The browser console indicates an error 'Resource interpreted as Stylesheet but transferred with MIME type text / html:' http: // localhost: 8080 / static / css / style.css'.' On the Response tab of the Chrome developer panel, style.css is displayed as a copy of the order.mustache page. On the Headers tab, its type is text / html.
I can’t understand at what point these changes are happening, and what should I change so that the page works properly.
HTML:
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>...</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<link href="../static/css/style.css" type="text/css" rel="stylesheet">
<link href='http://fonts.googleapis.com/css?family=Roboto:400,300,100,500,700,900' rel='stylesheet' type="text/css">
<link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
</head>
Controller:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.Date;
import java.util.Map;
#Controller
public class GreetingController {
#Autowired
private ClientRepo repo;
#GetMapping
public String main(Map<String, Object> model) {
Iterable<Client> clients = repo.findAll();
model.put("clients", clients);
return "order";
}
#PostMapping
public String add(#RequestParam String firstName, #RequestParam String lastName, #RequestParam String nationality,
#RequestParam String sex, #RequestParam Date birthDate, #RequestParam long passNumber, Map<String, Object> model) {
Client client = new Client(firstName, lastName, nationality, sex, birthDate, passNumber);
repo.save(client);
Iterable<Client> clients = repo.findAll();
model.put("clients", client);
return "order";
}
}
Main:
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
#Bean
public ViewResolver getViewResolver(ResourceLoader resourceLoader) {
MustacheViewResolver mustacheViewResolver
= new MustacheViewResolver();
mustacheViewResolver.setPrefix("templates/");
mustacheViewResolver.setSuffix(".mustache");
mustacheViewResolver.setCache(false);
return mustacheViewResolver;
}
Try to swap
<link href="../static/css/style.css" type="text/css" rel="stylesheet">
Maybe your custom styles cannot load after bootstrap.
Do like that :
<!-- My styles firstly -->
<link href="../static/css/style.css" type="text/css" rel="stylesheet">
<!-- And then bootstrap -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<link href='http://fonts.googleapis.com/css?family=Roboto:400,300,100,500,700,900' rel='stylesheet' type="text/css">
<link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">

Using hibernate and tapestry JAVA

I have problem with Tapestry 5. When i try to delete user from an table which have action link on cell it wont delete that user, it delete always last user that is on table... here is my code :
ViewAllUsers.java
public class ViewAllUsers {
#Inject
private Session session;
#Property
#SessionState
private User loginUser;
#Property
#Persist
private User user;
public List<User> getAllUsers() {
return session.createCriteria(User.class).list();
}
#CommitAfter
void onActionFromIzbrisi() {
session.delete(user);
}
}
ViewAllUsers.tml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns:t="http://tapestry.apache.org/schema/tapestry_5_3.xsd"
xmlns:p="tapestry:parameter">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta content="width=device-width, initial-scale=1.0" name="viewport" />
<title></title>
</head>
<body>
<t:Alerts />
<t:Grid t:source="allusers" t:add="Izbrisi,Edit" t:row="user">
<p:izbrisiCell>
<t:actionlink t:id="izbrisi" t:context="user">Delete</t:actionlink>
</p:izbrisiCell>
<p:editCell>
<t:PageLink t:page="EditUser" t:id="edit" t:context="user"> Edit </t:PageLink>
</p:editCell>
<p:deleteOptionCell>
</p:deleteOptionCell>
</t:Grid>
</body>
</html>
EDIT:
All i had to do here is to pass an parameter(Object or ID) in constructor of method for deleting files.
Just replaced
#CommitAfter
void onActionFromIzbrisi() {
session.delete(user);
}
with:
#CommitAfter
void onActionFromIzbrisi(User user) {
session.delete(user);
}
I don't think you can just pass your User instance in the t:context directly like that. A generic object instance cannot be passed between client and server directly. You will have to pass some kind of reference to your instance - usually an id - that your onActionFromIzbrisi() method can use to retrieve the actual object.
According to the doc for ActionLink the t:context attribute represents
The context for the link (optional parameter). This list of values
will be converted into strings and included in the URI.
That doc page also shows an example of how to pass an object.

spring boot load jsp as txt?

I use spring boot to do a simple web page.
Here are the codes:
src/main/java/Application.java
#SpringBootApplication
public class Application
{
public static void main(String[] args)
{
SpringApplication.run(Application.class, args);
}
}
src/mian/java/Config.java
#Configuration
#EnableWebMvc
public class Config extends WebMvcConfigurerAdapter
{
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer)
{
configurer.enable();
}
#Bean
public InternalResourceViewResolver viewResolver()
{
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
}
src/main/java/TestController.java
#Controller
public class TestController
{
String name = "Peter!";
#RequestMapping("/test")
public String admin(ModelAndView mv)
{
System.out.println("in controller");
mv.addObject("name", name);
return "test";
}
}
src/main/webapp/WEB-INF/views/test.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Just for test</title>
</head>
<body>
${name}
</body>
</html>
I start the project from the Application.java,
and put http://localhost:8080/test in the browser,
but the browser just show the source code of test.jsp.
It seems spring boot treat jsp as txt file...
How to fix it?
add this dependency to your pom.xml
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<scope>provided</scope>
</dependency>

Thymeleaf didn't see objects from Spring

My template do not see objects, passed from Spring.
My code:
public class PublicModelAndView extends ModelAndView {
#Autowired
TemplateModulesHandler templateModulesHandler;
public void init() {
setViewName("index");
CSSProcessor cSSProcessor = new CSSProcessor();
cSSProcessor.setSiteRegion("public");
super.addObject("CSSProcessor", cSSProcessor);
JSProcessor jSProcessor = new JSProcessor();
super.addObject("JSProcessor", jSProcessor);
templateModulesHandler.setPublicModelAndView(this);
}
}
Contoller's code:
#SpringBootApplication
#Controller
public class IndexPage {
#Autowired
PublicModelAndView publicModelAndView;
#Autowired
OurServicesBean ourServicesBean;
#Autowired
PortfolioBean portfolioBean;
#RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView indexPage() {
publicModelAndView.setTemplate("publicSiteIndexPage");
publicModelAndView.addObject("pageTitle", "TITLE!!!!!!!!!!!!!!");
publicModelAndView.addObject("ourServices", ourServicesBean.getMenu());
publicModelAndView.addObject("portfolioWorkTypes", portfolioBean.getWorkTypes());
publicModelAndView.addObject("portfolioWorks", portfolioBean.getWorks());
return publicModelAndView;
}
}
Main template's code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
>
<head th:include="headerAndFooter/fragments/header :: publicSiteHeader">
<title></title>
</head>
<body>
hello!
</body>
</html>
Fragment's code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head th:fragment="publicSiteHeader">
<title>${pageTitle}</title>
<!--[if lte IE 8]>
<script src="<?= SITE_TEMPLATE_PATH ?>/js/html5shiv.js"></script>
<![endif]-->
</head>
<body>
</body>
</html>
As result I do not see value of the object pageTitle, but I see in page output code like
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>${pageTitle}</title>
Why thymeleaf didn't paste value of the pageTitle to between title tag's open and close?
The same code works good with JSP, but do not work with thymeleaf.
Thymeleaf is not JSP, so that's why your template does not work as you expect.
Look here http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#using-texts and use something like:
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<title th:text="#{pageTitle}">page title</title>
Edited - my solution is for localised texts which is good practice anyway. if you want to use content of variable than use $.

Categories