How to dinamicaly parse html template using thymeleaf + Spring boot? - spring-boot

I have a project and I need users to be able to add content without recompiling the application or using a database. What I want to achieve is for spring to look in a directory called modules / for all folders containing a thymeleaf html file and render them according to their name from a single controller. it's possible?.
I have looked for information on how to render a fragment of thymeleaf from java in real time but I have not found any information.

with the help of this, we can navigate our template path as per our desired location.
#Bean
public ClassLoaderTemplateResolver templateResolver() {
ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
templateResolver().setPrefix("file://C:/test/");// this is
templateResolver.setCacheable(false);
templateResolver.setTemplateMode("HTML5");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode("XHTML");
templateResolver.setCharacterEncoding("UTF-8");
templateResolver.setOrder(1);
return templateResolver;
}

This is also a solution.
use this in application properties file
project.base-dir=file:///E:/Work/WorkSpace/RND WorkSpace/sk
spring.thymeleaf.prefix=${project.base-dir}/src/main/resources/templates/

Related

Thymealeaf text template not printing the current date

I am using spring boot 2.2.4 and using the thymealeaf text templates for the first time with spring boot.
Belowis the texttemplate I am trying to use and I am trying to print the current date and time but it is printing blank on screen.
CurrentDate:[#th:block th:utext="${#temporals.format(now, 'dd/MMM/yyyy HH:mm')}"/]
I have added the Java8 date time dependency in pom.xml and also added the java8dialect in the template resolver bean.
pom.xml
--------
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
<version>3.0.4.RELEASE</version>
</dependency>
ThymeleafConfig.java
----------------------
#Configuration
public class ThymeleafConfig {
#Bean(name = "textTemplateEngine")
public TemplateEngine textTemplateEngine() {
TemplateEngine templateEngine = new TemplateEngine();
templateEngine.addTemplateResolver(textTemplateResolver());
templateEngine.addDialect(new Java8TimeDialect());
return templateEngine;
}
private ITemplateResolver textTemplateResolver() {
ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
templateResolver.setPrefix("/templates/text/");
templateResolver.setSuffix(".txt");
templateResolver.setTemplateMode(TemplateMode.TEXT /* https://github.com/thymeleaf/thymeleaf/issues/395 */);
templateResolver.setCharacterEncoding("UTF8");
templateResolver.setCheckExistence(true);
templateResolver.setCacheable(false);
return templateResolver;
}
}
Can anybody please tell me what am I doing wrong in thymealeaf text template that it is not printing the date?
You can use a Thymeleaf utility method to print various date and time variants.
For example:
<div th:text="${#dates.createNow()}"></div>
I think that may answer your specific question.
However, I suspect your question is more about the wider topic of binding Java objects to Thymeleaf templates in Spring - and I have not used Spring with Thymeleaf.

jar package is not behaving as expected

I have made a code using spring boot and itextpdf 5, actually I am trying to do something like this example
https://github.com/aboullaite/SpringBoot-Excel-Csv
my code is working fine when I run it in my STS IDE, but it shows error as error resolving template when I create jar file and run it, can anyone please help
Edit:- I am using thymeleaf for html view
Code
this is my webconfig class
#Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer
.defaultContentType(MediaType.APPLICATION_JSON)
.favorPathExtension(true).ignoreAcceptHeader(true);
}
#Bean
public ViewResolver contentNegotiatingViewResolver(ContentNegotiationManager manager) {
ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
resolver.setContentNegotiationManager(manager);
// Define all possible view resolvers
List<ViewResolver> resolvers = new ArrayList<>();
resolvers.add(csvViewResolver());
resolvers.add(excelViewResolver());
resolvers.add(pdfViewResolver());
resolver.setViewResolvers(resolvers);
return resolver;
}
/*
* Configure View resolver to provide XLS output using Apache POI library to
* generate XLS output for an object content
*/
#Bean
public ViewResolver excelViewResolver() {
return new ExcelViewResolver();
}
/*
* Configure View resolver to provide Csv output using Super Csv library to
* generate Csv output for an object content
*/
#Bean
public ViewResolver csvViewResolver() {
return new CsvViewResolver();
}
/*
* Configure View resolver to provide Pdf output using iText library to
* generate pdf output for an object content
*/
#Bean
public ViewResolver pdfViewResolver() {
return new PdfViewResolver();
}
}
and here are my controller methods
#GetMapping( "/download")
public String download(Model model) {
model.addAttribute("cards", new StudentsDto());
return "getReportCard";
}
#PostMapping("/download")
public String postReportCard(#ModelAttribute("cards") StudentsDto cards, Model model){
List<Students> sList=studentService.searchByClassSectionBySession(cards.getClassSection(), cards.getSession());
model.addAttribute("studentsList", sList);
return "";
}
My question is , If everythinbg is working fine on running code as spring boot application through my STS IDE then why the jar I have created is not showing pdf views ?
I have created jars from my sts ide, i did maven clean and then i created jar using maven install
Solved
Was a stupid mistake, I don't kn how but in my template folder I changed the name of file getReportCard.html as getReportCArd.html.
Was a silly mistake and I checked upon each and every possible configuration. :-)

Spring Boot: process a html file with thymeleaf without controller

I would like to serve internationalized html pages with my Spring Boot application and I am using Thymeleaf with messages_XX.properties for i18n. I would prefer accessing these as http://localhost:8080/some/path/test.html and having them in e.g. /src/main/resources/html but I am unable to configure Spring Boot to process a page using thymeleaf by default.
As a temporary workaround I have a controller with
#RequestMapping(value="**/*.html")
public String serve(HttpServletRequest req) {
String res = req.getRequestURI().substring(0, req.getRequestURI().length() - 5);
res = res.substring(1);
return res;
}
This works for me now: http://localhost:8080/some/path/file.html processes and serves src/templates/some/path/file.html but can I just configure somewhere that src/resources/html are to be PROCESSED by thymeleaf and then served?
So far I have tried
spring.thymeleaf.prefix=classpath:/html/
in application.properties but it does not seemed to work for me.
Environment:
spring-boot-starter-2.0.0.RELEASE,
spring-webmvc-5.0.4.RELEASE,
thymeleaf-spring5-3.0.9.RELEASE
Since you are cutting of the .html in:
String res = req.getRequestURI().substring(0, req.getRequestURI().length() - 5);
You should probably set
spring.thymeleaf.suffix=.html
Or with Configuration:
#Bean
public SpringResourceTemplateResolver templateResolver(){
SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
templateResolver.setApplicationContext(this.applicationContext);
templateResolver.setPrefix("classpath:/html/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode(TemplateMode.HTML);
templateResolver.setCacheable(true);
return templateResolver;
}

How to configure Soap Webservices using Spring ws

I am new to the Spring ws.For the following things i need some clarification
1.I want to know how to customise the bindings,operations,port names etc..that is generated automatially by Spring.
2.How to specify multiple bindings,port types if we have multiple operations so that all should be generated in same wsdl.
You can customize the dynamic WSDL properties using DefaultWsdl11Definition bean
#Bean
public DefaultWsdl11Definition orders() {
DefaultWsdl11Definition definition = new DefaultWsdl11Definition();
definition.setPortTypeName("Orders");
definition.setLocationUri("http://localhost:8080/ordersService/");
definition.setSchema(new SimpleXsdSchema(new ClassPathResource("echo.xsd")));
return definition;
}
Ref : http://docs.spring.io/spring-ws/docs/current/reference/html/server.html
API Doc : http://docs.spring.io/spring-ws/sites/1.5/apidocs/org/springframework/ws/wsdl/wsdl11/DefaultWsdl11Definition.html

Eclipse Paho Mqtt - Spring Java configuration

I want to use MqTT in my SpringMVC project. In this link,the official example, creates all the objects with new keyword. As far as I know, this is not Spring style. The recommended way to do this creating bean, isn't?
I found some examples (spring-integration-mqtt, which based on eclipse-paho-mqtt) configured xml-based, but I want to make it Java based configuration. I congifured whole project Java-based. There is no .xml file in the project (not even web.xml).
If you suggest me an example with Java-config or good document about converting xml-config to java-config I will be appriciated.
Thanks in advance.
You can track the Pull Request on the matter, but let me share a piece of code to track more info here as well:
#Bean
public MessageProducer inbound() {
MqttPahoMessageDrivenChannelAdapter adapter =
new MqttPahoMessageDrivenChannelAdapter("tcp://localhost:1883", "testClient",
"topic1", "topic2");
adapter.setCompletionTimeout(5000);
adapter.setConverter(new DefaultPahoMessageConverter());
adapter.setQos(1);
adapter.setOutputChannel(mqttInputChannel());
return adapter;
}
#Bean
#ServiceActivator(inputChannel = "mqttOutboundChannel")
public MessageHandler amqpOutbound() {
MqttPahoMessageHandler messageHandler =
new MqttPahoMessageHandler("testClient", mqttClientFactory());
messageHandler.setAsync(true);
messageHandler.setDefaultTopic("testTopic");
return messageHandler;
}

Resources