Thymeleaf not displaying values from spring controller - java

I am practising thymeleaf template engine for the first time. I have followed the tutorial and so on but I have no idea where I am going wrong.
My controller:
public String mainPage(Model model){
model.addAttribute("data", "Hello Thymeleaf");
return "main";
}
and my html is as follows:
<!DOCTYPE html >
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>th:text="${data}"</h1>
</body>
</html>
When I hit localhost it displays th:text="${data}" instead of Hello Thymeleaf
<h1>"${data}"</h1>
doesn't work either. View resolver config must be correct as it resolves main to main.html. I am using spring4 SpringTemplateEngine and spring4 thymeleaf view resolver.
thanks in advance

You have to use th:text
<h1 th:text="${data}"></h1>
or if you don't want to use the th:text attribute, then you have to use th:inline="text" and make the thymeleaf render the context inside the tag. But make sure you put the variable inside [[ and ]]
<h1 th:inline="text">[[${data}]]</h1>

Thymeleaf isn't Velocity or Freemarker and doesn't replace expressions blindly. You need the expression in an appropriate tag attribute, such as
<h1 data-th-text="${data}" />

remove quotes to "${data}" and just use ${data}. I also agree with #Faraj Farook

Related

Replace custom tags in html with Java

is there a library on Java to help me to achieve custom tags replacement in html
like for example here is a simple template :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div>
<p>$welcome_title</p>
<p>$email_body</p>
<p>$footer_text</p>
</div>
</body>
</html>
Can i replace this custom tags ($welcome_title,$email_body,$footer_text) with values from java ?
The idea is to have template with tags which can be replaced at runtime with values from java objects :)
Also maybe (if there is a library) to generate straight away from html an PDF doc
Thanks :)
In Java world you can use https://www.thymeleaf.org/ or https://freemarker.apache.org/

DOUBLE_WHITESPACE in PATH error

i am learning JSTL and from tutorials point in this link
when i tried to execute that example in the page which is
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title><c:url> Tag Example</title>
</head>
<body>
TEST
</body>
</html>
i am getting following error.
but i could not understand why and what is the solution for that?
The validator is probably confused by the nested double quotes:
TEST
You can make the code cleaner by doing:
<c:url value="/jsp/index.htm" var="myUrl" />
TEST
which assigns the value of the processed URL to a var named 'myUrl' and then uses JSP Expression language to output the URL.
Change this line:
<title><c:url> Tag Example</title>
By:
<title>&LT;c:url&GT; Tag Example</title>
Otherwise, the JSP engine will interpret this (<c:url>) as the beginning of a tag to be processed.
You need to escape your nested quotes as
TEST
Otherwise the HTML parser perceives "<c:url value=" as the href value and complains about the space in between. Alternatively, you can make use of single and double quotes as
<a href='<c:url value="/jsp/index.htm"/>'>TEST</a>
Or,
TEST

How to link different URLs to different items in forEach loop in JSP page? [duplicate]

This question already has an answer here:
How do I pass current item to Java method by clicking a hyperlink or button in JSP page?
(1 answer)
Closed 7 years ago.
I have a facultylist.jsp page which displays List<Faculty> as a request attribute parameter in forEach loop and I want every item in this loop to be a link to specified faculty facultyview.jsp. How can I achieve that ?
facultylist.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">
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Faculties</title>
</head>
<body>
<h1>Faculties list</h1>
<ul>
<c:forEach var="faculty" items="${faculties}">
<li>${faculty.name}</li>
</c:forEach>
</ul>
</body>
</html>
facultyview.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">
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Faculty</title>
</head>
<body>
<h1>${faculty.name}</h1>
<ul>
<li>Faculty name: <c:out value="${requestScope.name}"></c:out></li>
<li>Total seats: <c:out value="${requestScope.total_seats}"></c:out></li>
<li>Budget seats: <c:out value="${requestScope.budget_seats}"></c:out></li>
</ul>
apply for this faculty
</body>
</html>
I don't know if its may help, but I'm using following technologies: tomcat, jsp, servlets and log4j.In my project I have one FrontController, which is a servlet that interacts with Command pattern - each Command returns a path to resource and action type: forward or redirect.
You can solve your issue by adding a query params to the link, edit with respect to the comment. Note that you cannot access directly the JSP pages that reside under WEB-INF folder. Also, to encode properly the paramters, better construct url like
<c:url value="facultyview.jsp" var="url">
<c:param name="name" value="${faculty.name}"/>
<c:param name="total_seats" value="${faculty.total_seats}"/>
<c:param name="budget_seats" value="${faculty.budget_seats}"/>
</c:url>
<li>${faculty.name}</li>
and than than in your facultyview.jsp read from the query params
<li>Faculty name: ${param.name}</li>
<li>Total seats: ${param.total_seats}</li>
<li>Budget seats:${param.budget_seats}</li>
This direct JSP communication should solve your immediate issue, but a truly proper way would be to pass an id of a faculty to servlet, fetch the faculty instance, place in the model and pass to the view.
in other way is just take the selected value from the drop down with a name and forward it to front controller servlet ,there use if else conditions and depends on the value you could forward the request to corresponding jsp or servlet
<select name="value"> in jsp
String value=req.getParameter("value"); in servlet
if()
else if()
If you have a field in Faculty entity simply:
${faculty.name}
#Mark: faculty represents an entity from database, i'm not sure if I want to change it adding another field, or you mean some other way ?
Add a field does not means you must change database, you can have a Helper entity that inherits from Faculty and have more fields you can need,
public class FacultyFormHelper extends Faculty implements Serializable {
private String URL;
and in your view:
${facultyHelper.name}
But, If you don't want to modify your database, either create a helper class, you may add onclick event to the <a>
<a onclick="goToURL(${faculty.id})">
Then retrieve the data... i'm not sure how you get the urls... from a variable in the view, ajax call or wherever you have this URL...

Play! framework. template "include"

I'm planning my website structure as following:
header.scala.html
XXX
footer.scala.html
now, instead of "xxx" there should be a specific page (i.e. "UsersView.scala.html").
what I need is to include (like with well-known languages) the source of the footer and the
header into the the middle page's code.
so my questions are:
How do you include a page in another with scala templating?
Do you think it's a good paradigm for Play! framework based website?
Just call another template like a method. If you want to include footer.scala.html:
#footer()
A common pattern is to create a template that contains the boilerplate, and takes a parameter of type HTML. Let's say:
main.scala.html
#(content: HTML)
#header
// boilerplate
#content
// more boilerplate
#footer
In fact, you don't really need to separate out header and footer with this approach.
Your UsersView.scala.html then looks like this:
#main {
// all your users page html here.
}
You're wrapping the UsersView with main by passing it in as a parameter.
You can see examples of this in the samples
My usual main template is a little more involved and looks roughly like this:
#(title: String)(headInsert: Html = Html.empty)(content: Html)(implicit user: Option[User] = None)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>#title</title>
// bootstrap stuff here
#headInsert
</head>
<body>
#menu(user)
<div id="mainContainer" class="container">
#content
</div>
</body>
</html>
This way a template can pass in a head insert and title, and make a user available, as well as content of course.
Play provide a very convenient way to help implement that!
Layout part from official docs:
First we have a base.html (that's we call in django -_-)
// views/main.scala.html
#(title: String)(content: Html)
<!DOCTYPE html>
<html>
<head>
<title>#title</title>
</head>
<body>
<section class="content">#content</section>
</body>
</html>
How to use the base.html?
#main(title = "Home") {
<h1>Home page</h1>
}
More information here

advice on freemarker templating, want to create a master template

I want to create a master template that every other view page will inherit.
So the master template will have:
HEADER
--CONTENT--
FOOTER
the header will optionally show (if the user is logged in), the username and other user object properties.
the --CONTENT-- is a placeholder that other 'inheriting' view pages will inject their content into.
So my questions are, is this possible with freemarker? If so, any guidance?
How would I pass the user object to the header from my controller actions? ideally the object would be passed in somewhere OTHER than each and every view page (to avoid having to maintain this code on each and every view page).
Yes, it's possible. In our applications things like the user object exist in session scope, but this could be any scope freemarker has access to:
<#if Session.the_user?? && Session.the_user.loggedIn>
<#-- header code -->
</#if>
You can omit the Session. and Freemarker will search the various scopes for the given variable name.
To inject the content, include this at the point in the master template where you'd like the view page to put its content:
<#nested>
The view pages then declare their use of the master template as follows:
<#import "/WEB-INF/ftl/path/to/template/master.ftl" as com>
<#com.template>
View page content
</#com.template>
I made Freemarker template inheritance - https://github.com/kwon37xi/freemarker-template-inheritance
I think it's what you want. It is tested on freemarker 2.3.19.
I implemented something like this:
base.ftl
<#macro page_head>
<title>Page title!</title>
</#macro>
<#macro page_body></#macro>
<#macro display_page>
<!DOCTYPE html>
<html lang="en">
<head>
<#page_head/>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<#page_body/>
</body>
</html>
</#macro>
then index.ftl will inherit the boilerplate templates as:
<#include "base.ftl">
<#macro page_head>
<title>Welcome studs!</title>
</#macro>
<#macro page_body>
<h1> Welcome user</h1>
</#macro>
<#display_page/>
this site was helpful for the above code reference
https://nickfun.github.io/posts/2014/freemarker-template-inheritance.html
In newer Freemarker versions, the <#nested> element is extremely useful:
base.ftl:
<#macro layout>
<html>
<body>
<p>OptaPlanner AI</p>
<#nested>
</body>
</html>
</#macro>
baseWithDownloadButton.ftl:
<#import "base.ftl" as base>
<#base.layout>
${content.body}<#-- Only applicable for jbake -->
<p>Download button</p>
</#base.layout>

Categories