I try to write my website with spring framework in back- and thymeleaf in frontend on tomcat local server. I try add css to my html file. Css file seems to be linked on server, but devtools shows that it is empty. Do you know what could i miss?
EDIST: sorry for posting pictures, I will know better next time. I left minimum i wanted to show.
index.css
h1{
color: red;
}
index.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleag.org">
<head>
<meta charset="UTF-8">
<title>Index</title>
<link rel="stylesheet" href="../css/index.css" th:href="#{../css/index.css}"/>
</head>
<body>
<h1>Hello</h1>
Greeting
Registration
</body>
</html>
HomePageController.java
package com.krs.GreatBookOfDiet.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
#Controller
public class HomePageController {
#GetMapping("")
public String index(Map<String, Object> model){
return "index";
}
}
GreatBookOfDietConfiguration.java
package com.krs.GreatBookOfDiet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.WebProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;
import java.util.Locale;
#Configuration
public class GreatBookOfDietConfiguration implements WebMvcConfigurer {
#Autowired
private ApplicationContext applicationContext;
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/files/**").addResourceLocations("/WEB-INF/pdf/");
}
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(localeChangeInterceptor());
}
#Bean
public LocaleResolver localeResolver(){
SessionLocaleResolver slr = new SessionLocaleResolver();
slr.setDefaultLocale(Locale.US);
return slr;
}
#Bean
public LocaleChangeInterceptor localeChangeInterceptor(){
LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
lci.setParamName("lang");
return lci;
}
#Bean
public ViewResolver thymeleafResolver(){
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(templateEngine());
viewResolver.setOrder(0);
return viewResolver;
}
#Bean
public SpringResourceTemplateResolver templateResolver(){
SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
templateResolver.setApplicationContext(applicationContext);
templateResolver.setPrefix("/WEB-INF/views/");
templateResolver.setSuffix(".html");
return templateResolver;
}
#Bean
public SpringTemplateEngine templateEngine(){
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
templateEngine.setEnableSpringELCompiler(true);
return templateEngine;
}
}
file structure
devtools on server, index.css view
Your static resources in the /WEB-INF/css folder are not served by Spring, therefore a request for http://example.com/app/css/index.css returns a 404 error.
You need to modify your addResourceHandlers method:
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/files/**")
.addResourceLocations("/WEB-INF/pdf/");
registry.addResourceHandler("/css/**")
.addResourceLocations("/WEB-INF/css/");
}
Remark: Given the popularity of Spring Boot, you might consider using the same locations for static resources (cf. documentation), which sums up to the following configuration:
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**")
.addResourceLocations("classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/", "/");
}
Related
It is a very strange issue. Removing the JSON in TestUtil or the executorService/submit will make the following code working:
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInfo;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ATest {
#BeforeAll
public static void setup(TestInfo test) throws Exception {
}
#Test
void testThis(){
int numThreads = 1;
ExecutorService threadPool = Executors.newFixedThreadPool(numThreads);
threadPool.submit(() -> {
TestUtils.doSomething();
});
}
}
Here is the class with the ObjectMapper>
import com.fasterxml.jackson.databind.ObjectMapper;
public class TestUtils {
private static final ObjectMapper JSON;
static {
JSON = new ObjectMapper();
}
public static void doSomething() {
System.out.println("entered the method");
}
}
Currently, the method doSomething() would not be entered at all.
This issue will be resoved if we trigger the Junit test from Maven or if run it from a static main method.
i am using keycloak and spring to get the user list in a rest service, however the rest return the html instead of json data.
here is the service.
import org.keycloak.representations.idm.UserRepresentation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
#Service
public class UserServiceImpl implements UserService{
#Autowired
KeycloakInstance keycloakInstance;
public List<UserRepresentation> loadUsers(String realm) {
return keycloakInstance.getInstance()
.realm(realm)
.users()
.list();
}
}
here is the controller.
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.keycloak.representations.idm.UserRepresentation;
import java.util.List;
#RestController
#RequestMapping("/api/admin/users")
public class UserController {
#Autowired
private UserService userService;
#GetMapping(value = "", produces="application/json")
public List<UserRepresentation> loadUsers() {
String realm = "abc";
return userService.loadUsers(realm);
}
}
any idea how to fix this?
You would need to add the path to #GetMapping, this should work
#ResponseBody
#GetMapping(value = "/api/admin/users", produces="application/json")
public List<UserRepresentation> loadUsers() {
String realm = "abc";
return userService.loadUsers(realm);
}
or using this way
#GetMapping (value = "/api/admin/users", produces = MediaType.APPLICATION_JSON_VALUE)
As #ConstantinKonstantinidis commented, add to RequestMapping produces JSON to apply to your method (and all methods):
#RequestMapping(value = "/api/admin/users", produces = MediaType.APPLICATION_JSON_VALUE
Supported at the type level as well as at the method level
Another option is to add the path to #GetMapping ,e.g.
#RequestMapping("/api/admin")
public class UserController {
#GetMapping(value = "/users", produces="application/json")
I'm trying to upload excel file content to mysql using Spring boot with the help of upload file UI. Need help with that.
But i'm facing Whitelabel Error Page. I've tried couple of things but no luck yet.
Project View
ReadFileApplication.java
package com.springboot.file.parsefiles;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
#Configuration
#EnableAutoConfiguration
#ComponentScan(basePackages= {"com.springboot.file.parsefiles.controller"})
#SpringBootApplication
#Component
public class ReadFileApplication {
public static void main(String[] args) {
SpringApplication.run(ReadFileApplication.class, args);
}
}
ReadFileConrtroller.java
package com.springboot.file.parsefiles.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import com.springboot.file.parsefiles.service.ReadFileService;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.springboot.file.parsefiles.model.User;
#RestController
public class ReadFileController
{
#Autowired private ReadFileService readFileService;
#GetMapping(value="/ ")
public String home(Model model)
{
model.addAttribute("user", new User());
List<User> users = ReadFileService.findAll();
model.addAttribute("users", users);
return "view/users";
}
#PostMapping(value="/fileupload")
public String uploadFile(#ModelAttribute User user, RedirectAttributes redirectAttributes)
{
#SuppressWarnings("unused")
boolean isFlag = readFileService.saveDataFromUploadFile(user.getFile());
return "redirect:/";
}
}
ReadFileRepository.java
package com.springboot.file.parsefiles.repository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.springboot.file.parsefiles.model.User;
#Repository
public interface ReadFileRepository extends CrudRepository<User, Long>
{
}
ReadFileService.java
package com.springboot.file.parsefiles.service;
import java.util.List;
import org.springframework.web.multipart.MultipartFile;
import com.springboot.file.parsefiles.model.User;
public interface ReadFileService
{
List<User> findAll = null;
static List<User> findAll()
{
return null;
}
boolean saveDataFromUploadFile(MultipartFile file);
}
ReadFileServiceImpl.java
package com.springboot.file.parsefiles.service;
import java.util.List;
import com.springboot.file.parsefiles.service.ReadFileService;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import com.springboot.file.parsefiles.model.User;
import com.springboot.file.parsefiles.repository.ReadFileRepository;
#Service
#Transactional
public class ReadFileServiceImpl implements ReadFileService
{
#Autowired private ReadFileRepository readFileRepository;
public List<User> findAll()
{
return (List<User>) readFileRepository.findAll();
}
#Override
public boolean saveDataFromUploadFile(MultipartFile file) {
#SuppressWarnings("unused")
boolean isFlag = false;
String extension = FilenameUtils.getExtension(file.getOriginalFilename());
if(extension.equalsIgnoreCase("json"))
{
isFlag = realDataFromJson(file);
}else if(extension.equalsIgnoreCase("csv"))
{
isFlag = realDataFromCsv(file);
}
return false;
}
private boolean realDataFromCsv(MultipartFile file)
{
return false;
}
private boolean realDataFromJson(MultipartFile file)
{
return false;
}
}
Applicatiopn.properties
spring.datasource.url = jdbc:mysql://localhost:3306/sampledatabase
spring.datasource.username = root
spring.datasource.password = root
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = update
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.servlet.multipart.max-file-size=100MB
spring.servlet.multipart.max-request-size=500MB
Edit:
***************************
APPLICATION FAILED TO START
***************************
Description:
Field readFileService in com.springboot.file.parsefiles.controller.ReadFileController required a bean of type 'com.springboot.file.parsefiles.service.ReadFileService' that could not be found.
The injection point has the following annotations:
- #org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.springboot.file.parsefiles.service.ReadFileService' in your configuration.
Update your controller as below
#PostMapping(value="/fileupload")
public String uploadFile(#RequestParam MultipartFile file, RedirectAttributes redirectAttributes)
{
#SuppressWarnings("unused")
boolean isFlag = readFileService.saveDataFromUploadFile(file);
return "redirect:/";
}
Next i used apache-poi library to convert excel file to list of model object in service class. So my service method is as below
#Autowired
private IPoiji poijiImpl;
#Override
public boolean saveDataFromUploadFile(MultipartFile file) {
List<UserDTO> uploadedUserList = = poijiImpl.fromExcel(file.getOriginalFilename(), file.getInputStream(),UserDTO.class);
// here i can call repository methods to save data in database
}
I'm new to JUnit and was learning the various annotations. The code below however is giving me output that seems wrong
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.After;
import org.junit.BeforeClass;
import org.junit.AfterClass;
import org.junit.Test;
public class SampleTest {
#BeforeClass
public static void beforeClass() {
System.out.println("Before Class"); }
#AfterClass
public static void afterClass() {
System.out.println("After Class"); }
#Before
public void before() {
System.out.println("Before"); }
#After
public void after() {
System.out.println("After"); }
#Test
public void testAreFirstAndLastNCharactersTheSame() {
System.out.println("testAreFirstAndLastNCharactersTheSame");}
#Test
public void testTruncateAinFirstNPositions() {
System.out.println("testTruncateAinFirstNPositions"); }
}
The output I get is
Before
testTruncateAinFirstNPositions
After
Before
testAreFirstAndLastNCharactersTheSame
After
Before Class
After Class
This seems wrong as the "Before Class" print should be first. Am I doing something wrong? My Junit version is 4.12. I ran the above piece of code on Intellij.
The actual output screenshot is below
I have problem with persisting polish PL-pl locale characters in mysql db.
I know that is common issue, and out there in the internet is many solution to this. But I cant figure it out. I think I've tried everything.
All my web page correctly encode and display UTF-8 characters (static from html and from db)
Problem cames when I save somthing in db using form on my application. So I think it is tightly related to JDBC, JPA and hibernate.
Here is my configuration:
application.properties
#DB Properties:
# Mysql
db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3300/derp?characterEncoding=UTF-8
hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
db.username=root
db.password=motorolaa835
# H2
#db.driver=org.h2.Driver
#db.url=jdbc:h2:~/sts/derp/db/derp_db
#hibernate.dialect=org.hibernate.dialect.H2Dialect
#db.username=root
#Hibernate Configuration:
hibernate.show_sql=true
hibernate.hbm2ddl.auto=update
#hibernate.hbm2ddl.auto=create
hibernate.connection.CharSet=utf8
hibernate.connection.characterEncoding=utf8
hibernate.connection.useUnicode=true
services.entitymanager.packages.to.scan=com.derp
cms.entitymanager.packages.to.scan=com.derp.cms.model
common.entitymanager.packages.to.scan=com.derp.common.model
procedure.entitymanager.packages.to.scan=com.derp.procedure.model
Initializer
package com.derp.common.init;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration.Dynamic;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.filter.HiddenHttpMethodFilter;
import org.springframework.web.servlet.DispatcherServlet;
public class Initializer implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(WebAppConfig.class);
ctx.register(ThymeleafConfig.class);
servletContext.addListener(new ContextLoaderListener(ctx));
ctx.setServletContext(servletContext);
Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
servlet.addMapping("/");
servlet.setAsyncSupported(true);
servlet.setLoadOnStartup(1);
// Allow to use Put and Delete method for REST architecture
registerCharachterEncodingFilter(servletContext);
registerHiddenFieldFilter(servletContext);
}
private void registerCharachterEncodingFilter(ServletContext aContext) {
CharacterEncodingFilter cef = new CharacterEncodingFilter();
cef.setForceEncoding(true);
cef.setEncoding("UTF-8");
aContext.addFilter("charachterEncodingFilter", cef).addMappingForUrlPatterns(null ,true, "/*");
}
private void registerHiddenFieldFilter(ServletContext aContext) {
aContext.addFilter("hiddenHttpMethodFilter", new HiddenHttpMethodFilter()).addMappingForUrlPatterns(null ,true, "/*");
}
}
WebAppConfig
package com.derp.common.init;
import java.util.Properties;
import javax.annotation.Resource;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.http.MediaType;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
//import com.derp.common.wicketView.HomePage;
#Configuration
#ComponentScan("com.derp")
#EnableWebMvc
#EnableTransactionManagement
#PropertySource("classpath:application.properties")
public class WebAppConfig extends WebMvcConfigurerAdapter {
private static final String PROPERTY_NAME_DATABASE_DRIVER = "db.driver";
private static final String PROPERTY_NAME_DATABASE_PASSWORD = "db.password";
private static final String PROPERTY_NAME_DATABASE_URL = "db.url";
private static final String PROPERTY_NAME_DATABASE_USERNAME = "db.username";
private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
private static final String PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO = "hibernate.hbm2ddl.auto";
private static final String PROPERTY_NAME_HIBERNATE_CONNECTION_CHARSET = "hibernate.connection.CharSet";
private static final String PROPERTY_NAME_HIBERNATE_CONNECTION_CHARACTERENCODING = "hibernate.connection.characterEncoding";
private static final String PROPERTY_NAME_HIBERNATE_CONNECTION_USEUNICODE = "hibernate.connection.useUnicode";
private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN_SERVICES = "services.entitymanager.packages.to.scan";
private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN_COMMON = "common.entitymanager.packages.to.scan";
private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN_CMS = "cms.entitymanager.packages.to.scan";
private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN_PROCEDURE = "procedure.entitymanager.packages.to.scan";
#Resource
private Environment env;
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER));
dataSource.setUrl(env.getRequiredProperty(PROPERTY_NAME_DATABASE_URL));
dataSource.setUsername(env.getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME));
dataSource.setPassword(env.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD));
return dataSource;
}
#Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSource());
//sessionFactoryBean.setPackagesToScan(env.getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN));
sessionFactoryBean.setPackagesToScan(new String[] {
env.getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN_SERVICES),
env.getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN_COMMON),
env.getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN_CMS),
env.getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN_PROCEDURE)
});
sessionFactoryBean.setHibernateProperties(hibProperties());
return sessionFactoryBean;
}
private Properties hibProperties() {
Properties properties = new Properties();
properties.put(PROPERTY_NAME_HIBERNATE_DIALECT, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));
properties.put(PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO));
properties.put(PROPERTY_NAME_HIBERNATE_CONNECTION_CHARSET, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_CONNECTION_CHARSET));
properties.put(PROPERTY_NAME_HIBERNATE_CONNECTION_CHARACTERENCODING, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_CONNECTION_CHARACTERENCODING));
properties.put(PROPERTY_NAME_HIBERNATE_CONNECTION_USEUNICODE, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_CONNECTION_USEUNICODE));
properties.put("jadira.usertype.autoRegisterUserTypes", "true");
return properties;
}
#Bean
public HibernateTransactionManager transactionManager() {
HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager;
}
#Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
// Simple strategy: only path extension is taken into account
configurer.favorPathExtension(true).
ignoreAcceptHeader(true).
useJaf(false).
defaultContentType(MediaType.TEXT_HTML).
mediaType("html", MediaType.TEXT_HTML).
mediaType("xml", MediaType.APPLICATION_XML).
mediaType("json", MediaType.APPLICATION_JSON);
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/img/**").addResourceLocations("/WEB-INF/img/*");
registry.addResourceHandler("/css/**").addResourceLocations("/WEB-INF/css/*");
registry.addResourceHandler("/js/**").addResourceLocations("/WEB-INF/js/*");
registry.addResourceHandler("/lib/**").addResourceLocations("/WEB-INF/lib/*");
}
}
ThymeleafConfig
package com.derp.common.init;
import nz.net.ultraq.thymeleaf.LayoutDialect;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;
#Configuration
public class ThymeleafConfig {
#Bean
public ServletContextTemplateResolver templateResolver() {
ServletContextTemplateResolver resolver = new ServletContextTemplateResolver();
resolver.setPrefix("/WEB-INF/view/");
resolver.setSuffix(".html");
resolver.setTemplateMode("HTML5");
resolver.setOrder(1);
resolver.setCacheable(false);
return resolver;
}
#Bean
public SpringTemplateEngine templateEngine() {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
templateEngine.addDialect(new LayoutDialect());
//templateEngine.addDialect(new SpringStandardDialect());
return templateEngine;
}
#Bean
public ThymeleafViewResolver thymeleafViewResolver() {
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
resolver.setTemplateEngine(templateEngine());
resolver.setCharacterEncoding("UTF-8");
return resolver;
}
}
Edit
There is no utf-8 characters when using this method on controller
controller
#RequestMapping(value="/test", method=RequestMethod.PUT)
#ResponseBody
public String ajaxTest() {
return "Characters test: ęółąśżźćń";
}
and the javasscript ajax method
$(document).ready(function() {
$('h1').click(function() {
$.ajax({
type: "PUT",
url: "/derp/procedury/test",
data: "none",
success: function (response, status, xhr) {
showNotifications(status, xhr.responseText);
},
error: function (response, status, xhr) {
showNotifications('error', JSON.stringify(response));
showNotifications('error', status);
showNotifications('error', xhr);
}
});
});
The result I get is:
Characters test: ?�???????
Please give some helpful suggestions. Thanks in advance.
I had the same problem, I've added the following filter config to my MyServletInitializer
and there's no more problem (in my case other configs don't work):
public class MyServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
....
#Override
protected Filter[] getServletFilters() {
CharacterEncodingFilter filter = new CharacterEncodingFilter();
filter.setEncoding("UTF-8");
filter.setForceEncoding(true);
return new Filter[]{filter};
}
....
}
Working solution:
Code to add in initializer class:
private void registerCharachterEncodingFilter(ServletContext aContext) {
CharacterEncodingFilter cef = new CharacterEncodingFilter();
cef.setForceEncoding(true);
cef.setEncoding("UTF-8");
aContext.addFilter("charachterEncodingFilter", cef).addMappingForUrlPatterns(null ,true, "/*");
}
and then call it in initializer in
onStartup method
with ServletContext:
registerCharachterEncodingFilter