Why internalization is not working with JHIpster Microservices application - spring

I developed one spring boot microservice application using jhipster
tool and we have one quotation.html form it contains name and details
of the product I am trying to apply langauage translations to the name
and details labels based user language
for that i made changes in these classes
#Configuration
public class LocaleConfiguration implements WebMvcConfigurer {
#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;
}
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(localeChangeInterceptor());
}
}
added language messages files at this location
i am sending user language key as request param like this
localhost:8080/api/pord/quotation?lang=de
based on this lang value it shoud read keys from respective messages file
Note: The issue is it is always reading language keys from
messages_en.properties file
sample quotation.html file
<!DOCTYPE HTML>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<body>
<div class="page-content container-fluid">
<div class="title">
<h3>
<center>
<th:block>
<span th:text="#{invoice.quotation}"></span >
</th:block>
</center>
</h3
</div>
</body>
</html>

Have a look at src/main/resources/templates/error.html template it includes th:lang="${#locale.language}" while your template does not.
It's probably not the solution but it will help debugging by showing the value of lanaguage.

Related

Thymeleaf - return rendered template to String

I was using this solution as an example:
Can I render Thymeleaf templates manually from a String?
but after processing template I am getting not rendered template:
my template (plans/test.html):
<!doctype html>
<html lang="pl">
<div th:text="${loki}"></div>
</html>
Java code that should renderd the template:
#RestController
public class PlansPageRestController {
#Autowired
TemplateEngine myTemplateEngine;
#RequestMapping(value = {"/public/plans"}, method = RequestMethod.POST, produces = "application/json")
public Map<String,String> getPlans(#RequestParam Map<String, String> requestParams) {
Context ctx = new Context();
ctx.setVariable("loki", "Some test value");
String htmlTemplate = myTemplateEngine.process("plans/test.html", ctx);
Map<String,String> result = new HashMap<>();
result.put("html", htmlTemplate );
result.put("result", "success" );
return result;
}
}
but as a result I am getting content of plans/test.html so:
<!doctype html>
<html lang="pl">
<div th:text="${loki}"></div>
</html>
I am working with spring boot 3.0.0 and regarding to pom I am using thymeleaf:
<artifactId>thymeleaf-spring6</artifactId>
<version>3.1.0.RELEASE</version>
Can anyone help me in finding what I am doing wrong?
my thymeleaf configuration:
#Configuration
public class ThymeleafConfiguration implements WebMvcConfigurer, ApplicationContextAware {
private ApplicationContext applicationContext;
#Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
#Bean
public TemplateEngine myTemplateEngine() {
SpringTemplateEngine engine = new SpringTemplateEngine();
engine.setEnableSpringELCompiler(true);
engine.setTemplateResolver(templateResolver());
engine.setDialect(new LayoutDialect());
return engine;
}
private ITemplateResolver templateResolver() {
SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
resolver.setApplicationContext(applicationContext);
resolver.setPrefix("classpath:/templates/");
resolver.setTemplateMode(TemplateMode.HTML);
resolver.setCacheable(false);
resolver.setCacheTTLMs(0L);
resolver.setCharacterEncoding("UTF-8");
return resolver;
}
}
The reason your standard Thymeleaf expression is not being evaluated is because you have replaced the Thymeleaf "standard" dialect with the layout dialect:
engine.setDialect(new LayoutDialect());
(I should say "the Spring dialect", given you are using Spring-Thymeleaf.)
If you need to use the layout dialect, then you can add it to the engine - and still keep the standard dialect as well:
engine.addDialect(new LayoutDialect());
Or, you may not need the layout dialect at all (you do not use it in the sample HTML file in the question, but maybe you use it elsewhere). If that is the case, you can remove this line of code.
Just to add: The default Spring Boot settings should work without you needing to define any ThymeleafConfiguration class. But, again, there may be other places where you need to use a custom configuration (e.g. the UTF-8 encoding).

Thymeleaf cannot get Spring #ApplicationScope Bean

According to Spring document, #ApplicationScope Beans are visible as ServletContext attributes if Spring IOC container is web-aware.
I know i can access to #ApplicationScope Beans using ${#beanName} in thymeleaf template, but why can't I access to them using ${#servletContext.getAttribute('myAttribute')} as thymeleaf document show?
Below is my code snippet.
#SpringBootApplication
public class Application {
#Autowired
private BranchService branchService;
public static void main(String[] args) {
SpringApplication.run(RetailStoreApplication.class, args);
}
#ApplicationScope
#Bean(value = "branches")
public List<Branch> branches() {
return branchService.queryAllBranches();
}
}
#Controller
public class HomeController {
#GetMapping(value = { "/", "/home" })
public String home() {
return "home.html";
}
}
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Test</title>
</head>
<body>
Below are all the branch, please choose one for this branch.
<span th:if="${#servletContext.getAttribute('branches')} == null">NULL</span>
<ul th:each="branch : ${#servletContext.getAttribute('branches')}">
<li th:text="${branch.name}" />
</ul>
</body>
</html>
The returning 'branches' result is null. I'm using spring-boot2 with web-starter and thymeleaf-starter.
Have already try this, but not work in my case.
Any response is welcome, thanks!

unable to load static file in spring 4

Hi I am trying to load the jquery file in jsp but getting 404
Find below the project structure
I have configured the following in configuration too
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = { "common.spring.controller" })
public class WebConfig {
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
//viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("classpath:/resources/");
}
}
below is how i include file in jsp
<script type="text/javascript" src="/resources/jsFiles/jquery-3.3.1.min.js"></script>
Dono why its not working.
UPDATE: I am able to see the resources folder under target/project snapshot/resources but getting 404 for url
http://localhost:8080/resources/jsfiles/jquery-3.3.1.min.js
directly hitting below Url didnt work either
http://localhost:8080/Sample/resources/jsfiles/jquery-3.3.1.min.js
Finally was able to resolve the issue
removing addResourceHandlers method and including the below code did the trick
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configure) {
configure.enable();
}
in jsp i used the include like below
<script type="text/javascript" src="resources/jsFiles/jquery-3.3.1.min.js"></script>

Starting a Spring web app and can't get JSP content routed to localhost

I've got what is probably an embarassing issue trying to get started with Spring shown below is the code I have.
HelloController.java
package hello;
import java.util.Date;
import java.util.Map;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;
#RestController
public class HelloController {
#RequestMapping("/zz")
public String index() {
return "Greetings from Spring Boot!";
}
#RequestMapping("/")
public String welcome(Map<String, Object> model) {
return "welcome";
}
}
Application.java
#Configuration
#EnableAutoConfiguration
#ComponentScan
public class Application {
#Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(Application.class, args);
System.out.println("started");
}
}
welcome.jsp
<html>
<head>
<title>Sample Application JSP Page</title>
</head>
<body bgcolor=white>
<table border="0" cellpadding="10">
<tr>
<td align=center>
<img src="images/springsource.png">
</td>
<td>
<h1>Sample Application JSP Page</h1>
</td>
</tr>
</table>
<br />
<p>This is the output of a JSP page that is part of the HelloWorld application.</p>
<%= new String("Hello!") %>
</body>
</html>
When I visit localhost:8080 I get simply a white screen with the string "welcome" printed. It seems Spring isn't able to find the jsp with my mappings.
My welcome.jsp file is under projectroot->WEB-INF->welcome.jsp. Apologies if this could be resolved with a search but it seems most other issues with this have a setup using a web.xml to define the routing to the server. I do not think this is true in my case.. but I'd be glad if someone could prove me wrong.
-----Edit----
as kamoor has been suggesting the directory structure was off. I updated the structure and placed the jsp and it is now been routed correctly. Thanks!
change #RestController to #Controller
There are multiple things you need to do with JSP in spring boot application.
First of all fix the code as below
#Controller
public class HelloController {
#RequestMapping("/")
public ModelAndView welcome(Map<String, Object> model) {
return new ModelAndView("welcome");
}
}
Next, if you are creating final runnable "jar" there are restrictions around how Servlet container try to find resources in embedded jar. See this documentation to start with.
One work around is keep JSP files in resource folder (public folder for example) and create a runnable war artifact instead of jar artifact.
Or you can create jar file but create directory structure as META-INF/resources/jsp/
See sample project

Why jsp cannot reach its css file in SpringMVC?

I have a SpringMVC project. Upon running the project in tomcat7 I get the following message:
No mapping found for HTTP request with URI [/myproject/resources/css/welcome.css] in DispatcherServlet with name 'DispatcherServlet'
CSS does not get applied:
I've tried available solutions but none of them worked and none of them actually explained what was going on.
I have a simple welcome.jsp in /WEB-INF/jsp. Here it is:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link type="text/css"
href="${pageContext.request.contextPath}/resources/css/welcome.css"
rel="stylesheet">
<title>Welcome!</title>
</head>
<body>
<div id="font-HarabaraHand">
<p class="centrify">Poem Collection</p>
</div>
<div id="font-Goodfoot">
<p class="centrify2">What would you like to do?</p>
</div>
</body>
</html>
My welcome.css file lies in src/main/webapp/resources/css/.
My Spring configuration is java based, DispatcherServlet class is in AppInit.java file:
public class AppInit implements WebApplicationInitializer {
// this method is automatically invoked on application startup
public void onStartup(ServletContext container) throws ServletException {
WebApplicationContext webcntx = getWebCntx();
container.addListener(new ContextLoaderListener(webcntx));
ServletRegistration.Dynamic dispatcher = container.addServlet(
"DispatcherServlet", new DispatcherServlet(webcntx));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
private AnnotationConfigWebApplicationContext getWebCntx() {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.register(WebAppConfiguration.class);
return context;
}
}
And finally in WebAppConfig.java file:
#Bean
public InternalResourceViewResolver getInternalResourceViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/jsp/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
super.addResourceHandlers(registry);
if (!registry.hasMappingForPattern("/resources/**")) {
registry.addResourceHandler("/resources/**").addResourceLocations(
"/resources/").setCachePeriod(CACHE_PERIOD);;
}
}
My welcome page controller:
#Controller
public class WelcomeController {
#RequestMapping(value="/")
public ModelAndView welcomePage() {
return new ModelAndView("welcome");
}
}
Here is my project structure:
1. Why my welcome.css file cannot be reached?
2. How I can correct my mappings configuration?
I would really appreciate an explanation or a link about Spring url mappings config.
By using Java Config:
Create the following subdirectory structure: src/main/webapp/public/css
Put your css files in src/main/webapp/public/css (e.g. src/main/webapp/public/css/welcome.css)
Define an handler for public resources:
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
super.addResourceHandlers(registry);
if (!registry.hasMappingForPattern("/public/**")) {
registry.addResourceHandler("/public/**")
.addResourceLocations("/public/")
.setCachePeriod(CACHE_PERIOD); // You have to define a cache period.
}
}
Add a security exception:
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/public/**");
}
Link you css files (by defining a relative path):
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
...
<head>
<c:set var="url">${pageContext.request.requestURL}</c:set>
<base href="${fn:substring(url, 0, fn:length(url) - fn:length(pageContext.request.requestURI))}${pageContext.request.contextPath}/" />
<link rel="stylesheet" href="public/css/welcome.css" />
</head>
#vdenotaris answer is correct
My configuration didn't work because of my pom.xml file setup.
maven-war-plugin had <warSourceDirectory>WebContent</warSourceDirectory> and my /src/main/webapp/resources/css has never been detected by maven. Once I moved my jsp files to /src/main/webapp/ all was ok.
So, either you leave everything (css resources and other stuff) in WebContent\WEB-INF\ folder or move everything to /src/main/webapp

Resources