/java/

JEE + JAX-RS + Thymeleaf (way1)

2016-04-08 22:39:39

Messy, but works

package pl.btbw.modules.home;

import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;

@Path("/home")
public class HomeController {

    @Context
    private HttpServletRequest request;

    @Context
    private HttpServletResponse response;

    @GET
    @Path("/html")
    @Produces(MediaType.TEXT_HTML)
    public String html() {

        ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver();
        templateResolver.setTemplateMode("HTML5");

        TemplateEngine templateEngine = new TemplateEngine();
        templateEngine.setTemplateResolver(templateResolver);

        WebContext context = new WebContext(request, response, request.getServletContext());

        context.setVariable("test", "Lorem Ipsum");

        return templateEngine.process("/test.html", context);
    }

}

html - ../src/main/webapp/test.html

<!DOCTYPE html>

<html xmlns:th='"http://www.thymeleaf.org"'>
<body>
<p th:text='"${test}"'>...</p>
</body>
</html>

pom.xml

<?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?>

<project http:="" maven-4.0.0.xsd&quot;="" maven.apache.org="" xmlns='"http://maven.apache.org/POM/4.0.0"' xmlns:xsi='"http://www.w3.org/2001/XMLSchema-instance"' xsd="" xsi:schemalocation='"http://maven.apache.org/POM/4.0.0'>
<modelversion>4.0.0</modelversion>
<groupid>pl.btbw</groupid>
<artifactid>jeeThymeleaf</artifactid>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupid>javax</groupid>
<artifactid>javaee-api</artifactid>
<version>7.0</version>
</dependency>
<dependency>
<groupid>org.thymeleaf</groupid>
<artifactid>thymeleaf</artifactid>
<version>2.1.4.RELEASE</version>
</dependency>
</dependencies>
<build>
<finalname>jeet</finalname>
<plugins>
<plugin>
<groupid>org.apache.maven.plugins</groupid>
<artifactid>maven-compiler-plugin</artifactid>
<configuration>
<source/>1.7
                    <target>1.7</target>
</configuration>
</plugin>
<plugin>
<artifactid>maven-war-plugin</artifactid>
<configuration>
<failonmissingwebxml>false</failonmissingwebxml>
</configuration>
</plugin>
</plugins>
</build>
</project>

Config

package pl.btbw.core;

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@ApplicationPath("/rest")
public class App extends Application {
}