Spring + Thymleaf

January 25, 2024 |

 


SPRING + Thymeleaf

==============================================================
Basic Setup
Eclipse


Spring initializr:
Ref: https://start.spring.io/


Project structures:


build.gradle

implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'

implementation 'org.springframework.boot:spring-boot-starter-web'

implementation 'org.springframework.boot:spring-boot-starter-web-services'

testImplementation 'org.springframework.boot:spring-boot-starter-test'


SpringWebConfig:

@Configuration

@EnableWebMvc

@ComponentScan

public class SpringWebConfig implements WebMvcConfigurer , ApplicationContextAware {

private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {

"classpath:/META-INF/resources/", "classpath:/resources/",

"classpath:/static/", "classpath:/public/" };

private ApplicationContext applicationContext;


public SpringWebConfig() {

}


@Override

public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

this.applicationContext = applicationContext;

}

/* ******************************************************************* */

/* GENERAL CONFIGURATION ARTIFACTS */

/* Static Resources, i18n Messages, Formatters (Conversion Service) */

/* ******************************************************************* */

@Override

public void addResourceHandlers(final ResourceHandlerRegistry registry) {

registry.addResourceHandler("/**")

.addResourceLocations(CLASSPATH_RESOURCE_LOCATIONS);

//registry.addResourceHandler("/images/**").addResourceLocations("/images/");

//registry.addResourceHandler("/css/**").addResourceLocations("/css/");

//registry.addResourceHandler("/js/**").addResourceLocations("/js/");

}


@Bean

public ResourceBundleMessageSource messageSource() {

ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();

messageSource.setBasename("Messages");

return messageSource;

}


@Override

public void addFormatters(final FormatterRegistry registry) {

//registry.addFormatter(varietyFormatter());

registry.addFormatter(dateFormatter());

}



@Bean

public DateFormatter dateFormatter() {

return new DateFormatter();

}




/* **************************************************************** */

/* THYMELEAF-SPECIFIC ARTIFACTS */

/* TemplateResolver <- TemplateEngine <- ViewResolver */

/* **************************************************************** */


@Bean

public SpringResourceTemplateResolver templateResolver(){

// SpringResourceTemplateResolver automatically integrates with Spring's own

// resource resolution infrastructure, which is highly recommended.

SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();

templateResolver.setApplicationContext(this.applicationContext);

templateResolver.setPrefix("classpath:/templates/");

templateResolver.setSuffix(".html");

// HTML is the default value, added here for the sake of clarity.

templateResolver.setTemplateMode(TemplateMode.HTML);

// Template cache is true by default. Set to false if you want

// templates to be automatically updated when modified.

templateResolver.setCacheable(true);

return templateResolver;

}


@Bean

public SpringTemplateEngine templateEngine(){

// SpringTemplateEngine automatically applies SpringStandardDialect and

// enables Spring's own MessageSource message resolution mechanisms.

SpringTemplateEngine templateEngine = new SpringTemplateEngine();

templateEngine.setTemplateResolver(templateResolver());

// Enabling the SpringEL compiler with Spring 4.2.4 or newer can

// speed up execution in most scenarios, but might be incompatible

// with specific cases when expressions in one template are reused

// across different data types, so this flag is "false" by default

// for safer backwards compatibility.

templateEngine.setEnableSpringELCompiler(true);

return templateEngine;

}


@Bean

public ThymeleafViewResolver viewResolver(){

ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();

viewResolver.setTemplateEngine(templateEngine());

return viewResolver;

}

}


Include javascript to html file:
<script type="text/javascript" th:src="@{/color-modes.js}"></script>


Include css to html file:
<link th:href="@{/styles/cssandjs/main.css}" rel="stylesheet" />

Auto Reload HTML Template:
setCaheable is true or fall



==============================================================
Build and Deploy
1. Build to war file

build.gradle:

gradle.properties: (if you want to set specific JDK)

Run Gradle to build:
$ gradlew build

You can see in build\libs

==============================================================
Tips:
1. Img cannot load in Tomcat.
HTML Native:
<img class="mb-4" src="/vcare/logo/logo-vicare.png" alt=""
width="140" height="100">
Thymleaf:
<img class="mb-4" th:src="@{/vcare/logo/logo-vicare.png}" alt=""
width="140" height="100">

Because when html rendered, url image is http://hostname/vcare/logo/logo-vicare.png but actual url is: http://hostname/<path_context_tomcat>/vcare/logo/logo-vicare.png

2. Call Ajax in Thymleaf in JS file

jQuery.ajax({
url:  "user/getSecurityCode",
type: "POST",
data: JSON.stringify(requestData),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(results) {
alert(results.msg);
}
});

Should:
<script th:inline="javascript"> var contextRoot = /*[[@{/}]]*/ ''; </script>

jQuery.ajax({
url: contextRoot + "user/getSecurityCode",
type: "POST",
data: JSON.stringify(requestData),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(results) {
alert(results.msg);
}
});


3. Get Context Path in Java

@Autowired
private ServletContext context;

String contextPath = context.getContextPath();

4. Change logo of tomcat

Add to head of html.
Thymleaf: 
<link rel="shortcut icon" type="image/png" th:href="@{/vcare/logo/logo.png}"/>


is updating...

Read more…

Setup SSL of NoIP Domain Name (DDNS.NET) on NGINX

January 04, 2024 |

 



Ref: https://www.digicert.com/kb/csr-ssl-installation/nginx-openssl.htm

1. Generate SSL

- Access to: https://www.digicert.com/easy-csr/openssl.htm 
- Fill the information and click Generate. It will auto-general the command line. 



- Copy and paste into Command Line Prompt.




- Open and copy content of .csr
- Login NOIP > My Services > SSL Certificate > Create > Add CRS > Copy belove and Save. Waiting to validate from Digicert.

- Click Certificate Action > Download :


- Choose CRT Zipped to local PC and unzip.

2. Merge SSL

Windows:

$ copy /b your_domain_name.crt + DigiCertCA.crt bundle.crt

Linux:

$ cat your_domain_name.crt DigiCertCA.crt >> bundle.crt

3. Upload SSL to servers 

4. Config NGINX (nginx.cfg)




Read more…