Home  >  Thymeleaf

Thymeleaf Conditionals "if", "unless" and Switch Statements Example

By Arvind Rai, October 31, 2015
On this page, we will provide Thymeleaf conditionals "if", "unless" and switch statements example. "unless" is the negative counterpart of "if". "unless" is equivalent to "if" when using with not. To meet the requirement of switch statement, Thymeleaf provides th:switch and th:case. Find the complete example.

Thymeleaf "if" using th:if

<a href="test.html" th:href="@{/profile/writer(id=${writer.id})}" 
                th:if="${not #strings.startsWith(writer.name,'K')}">Profile</a> 

1. For "if" condition, Thymeleaf provides th:if.
2. th:if="${not #strings.startsWith(writer.name,'K')} means that if writer name does not start with letter 'K', it displays the anchor otherwise not.
Output
<a href="/concretepage-1/profile/writer?id=1">Profile</a>
 

Thymeleaf "unless" using th:unless

<p th:text="${writer.location}" 
                th:unless="${#strings.endsWith(writer.location,'ya')}">location</p> 

1. "unless" condition is negative counterpart of "if" condition. It is used by syntax th:unless.
2. th:unless="${#strings.endsWith(writer.location,'ya')} means that if writer location ends with 'ya', it displays the text.
Output
<p>Mathura</p>
 

Thymeleaf Switch Statements using th:switch and th:case

<div th:switch="${writer.name}">
  <p th:case="'Ram'"> Writer Ram</p>
  <p th:case="#{myblog.chiefwriter}">Chief writer Shankar</p>
  <p th:case="*" th:text=${writer.name}>Other Writer</p>
</div> 

1. Thymeleaf achieved switch statements by using th:switch and th:case.
2. th:case="*" executes if no above case is satisfied.
Output
<div>
  <p> Writer Ram</p>

</div> 

Complete Example


ThymeleafAppUtil.java
package com.concretepage;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;
public class ThymeleafAppUtil {
     private static TemplateEngine templateEngine;
     static {
         ServletContextTemplateResolver templateResolver = 
                 new ServletContextTemplateResolver();
         templateResolver.setTemplateMode("XHTML");
         templateResolver.setPrefix("/WEB-INF/templates/");
         templateResolver.setSuffix(".html");
         templateResolver.setCacheTTLMs(3600000L);
         templateEngine = new TemplateEngine();
         templateEngine.setTemplateResolver(templateResolver);
     }
     public static TemplateEngine getTemplateEngine() {
		return templateEngine;
     }
} 

Writer.java
package com.concretepage;
import java.util.ArrayList;
import java.util.List;
public class Writer {
	private int id;
	private String name;
	private String location;
	public Writer(int id, String name, String location) {
		this.id = id;
		this.name = name;
		this.location = location;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getLocation() {
		return location;
	}
	public void setLocation(String location) {
		this.location = location;
	}
	public static List<Writer> getWriters() {
             List<Writer> list = new ArrayList<>();
             list.add(new Writer(1,"Ram","Ayodhya"));
             list.add(new Writer(2,"Krishna","Mathura"));
             list.add(new Writer(3,"Shankar","Himalaya"));
	     return list;
	}
} 

BlogApplication.java
package com.concretepage;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.thymeleaf.context.WebContext;
public class BlogApplication {
    public void process(HttpServletRequest request, HttpServletResponse response) 
   		 throws IOException {
	    WebContext ctx = new WebContext(request, response, request.getServletContext(),
	    		request.getLocale());
	    ctx.setVariable("writers", Writer.getWriters());
	    ThymeleafAppUtil.getTemplateEngine().process("myblog", ctx, response.getWriter());
    }
} 

BlogServlet.java
package com.concretepage;
import java.io.IOException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(urlPatterns = "/myblog", loadOnStartup = 1)
public class BlogServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException{
	     doGet(request,response);
	}
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException{
		response.setContentType("text/html;charset=UTF-8");
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);

		BlogApplication application = new BlogApplication();
		application.process(request, response);
	}
} 

myblog_en.properties
myblog.title= Thymeleaf Blog
myblog.chiefwriter= Shankar 

myblog.html
<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-4.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
  <head>
    <title th:text="#{myblog.title}">Blog Title</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  </head>
  <body>
    <table>
      <tr th:each="writer : ${writers}">
        <td> 
        	<div th:switch="${writer.name}">
	            <p th:case="'Ram'"> Writer Ram</p>
		    <p th:case="#{myblog.chiefwriter}">Chief writer Shankar</p>
		    <p th:case="*" th:text=${writer.name}>Other Writer</p>
		</div>
        </td>
        <td> <p th:text="${writer.location}" 
                th:unless="${#strings.endsWith(writer.location,'ya')}">location</p></td>
        <td> <a href="test.html" th:href="@{/profile/writer(id=${writer.id})}" 
                th:if="${not #strings.startsWith(writer.name,'K')}">Profile</a> </td>
      </tr>
    </table>
  </body>
</html>  

Output

Run the demo using URL http://localhost:8080/concretepage-1/myblog
Find the output as view source.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>Thymeleaf Blog</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  </head>
  <body>
    <table>
      <tr>
        <td> 
        	<div>
			  <p> Writer Ram</p>
			  
			  
			</div>
        </td>
        <td> </td>
        <td> <a href="/concretepage-1/profile/writer?id=1">Profile</a> </td>
      </tr>
      <tr>
        <td> 
        	<div>
			  
			  
			  <p>Krishna</p>
			</div>
        </td>
        <td> <p>Mathura</p></td>
        <td>  </td>
      </tr>
      <tr>
        <td> 
        	<div>
			  
			  <p>Chief writer Shankar</p>
			  
			</div>
        </td>
        <td> </td>
        <td> <a href="/concretepage-1/profile/writer?id=3">Profile</a> </td>
      </tr>
    </table>
  </body>
</html>  

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS


©2019 concretepage.com | Privacy Policy | Contact Us