Spring Boot & Thymeleaf - Localized text does not appear - java

I am currently working on the localization of my (second) Spring Boot project. However, I have come to a halt after several hours of struggling: I am unable to get a user-editable Session localization.
The problem appears to occur as soon as the user sends a GET request with the lang parameter. (travel down below to see the results I am getting)
Details
Spring Boot version:(3.0.0-M3)
Expected localized content
i18n/messages.properties is empty
i18n/messages_en_US.properties:
morning=good morning
afternoon=bye
i18n/messages_fr_FR.properties:
morning=salut
afternoon=a+
i18n/messages_ja_JP.properties:
morning=ohayou
afternoon=jane
Configuration
application.properties (section related to this issue):
spring.messages.always-use-message-format=true
spring.messages.basename=i18n.messages
spring.messages.fallback-to-system-locale=false
spring.messages.use-code-as-default-message=false
LocalizationConfiguration file:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
#Configuration
public class LocalizationConfiguration implements WebMvcConfigurer {
#Bean
public LocaleResolver localeResolver() {
SessionLocaleResolver localeResolver = new SessionLocaleResolver();
// localeResolver.setDefaultLocale(Locale.US);
return localeResolver;
}
#Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
localeChangeInterceptor.setParamName("lang");
return localeChangeInterceptor;
}
#Override
public void addInterceptors(InterceptorRegistry interceptorRegistry) {
interceptorRegistry.addInterceptor(localeChangeInterceptor());
}
}
Display
Page Controller:
#GetMapping
#RequestMapping(value = "/international")
public String getInternationalView(Model model) {
return "international";
}
Template loaded (international.html):
<!DOCTYPE html>
<html xmlns:th="https://www.thymeleaf.org" th:with="lang=${#locale.language}" th:lang="${lang}">
<head>
<script src="https://kit.fontawesome.com/2f4c03ee9b.js" crossorigin="anonymous"></script>
<script th:src="#{/webjars/jquery/3.0.0/jquery.min.js}"></script>
<script th:src="#{/webjars/popper.js/2.9.3/umd/popper.min.js}"></script>
<script th:src="#{/webjars/bootstrap/5.1.3/js/bootstrap.min.js}"></script>
<link th:rel="stylesheet" th:href="#{/webjars/bootstrap/5.1.3/css/bootstrap.min.css} "/>
<meta charset="UTF-8"/>
<title>Localization tests</title>
</head>
<body>
<p th:text="${#locale}"></p>
<p th:text="#{morning}"></p>
<p th:text="#{afternoon}"></p>
<div class="dropdown">
<button class="btn btn-primary dropdown-toggle" type="button" id="dropdownMenuButton1" data-bs-toggle="dropdown" aria-expanded="false">
<i class="fa-solid fa-language fa-4x"></i>
</button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenuButton1">
<li><a class="dropdown-item" th:href="#{''(lang=en)}">English</a></li>
<li><a class="dropdown-item" th:href="#{''(lang=fr)}">Français</a></li>
<li><a class="dropdown-item" th:href="#{''(lang=jp)}">日本語</a></li>
</ul>
</div>
</body>
</html>
What is being displayed
Found result
As you can see in the above gif, the first display of the page shows the messages in the browser's language. However, as soon as an other language is selected the page breaks apart, with the exception of the #locale parameter.

Try it.
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import java.util.Locale;
#Configuration
public class ApplicationConfig implements WebMvcConfigurer {
#Bean
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasenames("classpath:/i18n/messages");
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
}
#Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
localeChangeInterceptor.setParamName("lang");
return localeChangeInterceptor;
}
#Bean(name = "localeResolver")
public SessionLocaleResolver sessionLocaleResolver() {
SessionLocaleResolver localeResolver = new SessionLocaleResolver();
localeResolver.setDefaultLocale(new Locale("en"));
return localeResolver;
}
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(localeChangeInterceptor());
}
}

Related

How to invoke CommandLineRunner after input data in Spring Boot Application

I have a Spring Boot app in which I created a POST method, that expects some input from the user via HTML Thymeleaf. Once the input gets fetched, I am producing a string that represents a final URL. Then I want to pass this string URL in my Configuration Class that contains a CommandLineRunner.
The problem is that CommandLineRunner gets executed upon the application start which means that my input has null values thus throwing Null Pointer Exception. Is it possible to add data for my CommandLineRunner after application's start-up and somehow the execution of the latter goes smoothy???
REST CONTROLLER CLASS
package com.andrekreou.covid.gov.controller;
import com.andrekreou.covid.gov.model.Covid;
import com.andrekreou.covid.gov.model.Date;
import com.andrekreou.covid.gov.service.Service;
import org.springframework.beans.factory.annotation.Autowired;
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 java.util.List;
#RestController
public class Controller {
private final Service service;
#Autowired
public Controller(Service service) {
this.service = service;
}
#GetMapping(path = "/covid")
public List<List<Covid>> getData(){
return service.getData();
}
#PostMapping(value = "/insert/date")
public String insertDate(#ModelAttribute("date") Date date) {
String inserted_date = date.getDate();
return "https://data.gov.gr/api/v1/query/mdg_emvolio?date_from=" + inserted_date + "&date_to=" + inserted_date;
}
}
CONFIG CLASS
package com.andrekreou.covid.gov.configuration;
import com.andrekreou.covid.gov.controller.Controller;
import com.andrekreou.covid.gov.model.Covid;
import com.andrekreou.covid.gov.model.Date;
import com.andrekreou.covid.gov.repository.CovidRepo;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;
import java.util.Collections;
import java.util.List;
#Configuration
public class CovidConfig {
Controller controller;
Date date;
#Bean
CommandLineRunner commandLineRunner(CovidRepo covidRepo){
return args -> {
String url = controller.insertDate(date);
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
headers.set("Authorization","Token 8329eb4fa30e567d9e3f6bfed266c8cb4c9c94ad");
HttpEntity<Object> request = new HttpEntity<>(headers);
ResponseEntity<List<Covid>> postEntity = restTemplate.exchange(
url,
HttpMethod.GET,
request,
new ParameterizedTypeReference<>() {
});
List<Covid> covidList = postEntity.getBody();
assert covidList != null;
covidRepo.saveAll(covidList);
System.out.println(covidList);
};
}
}
POJO CLASS
package com.andrekreou.covid.gov.model;
public class Date {
private String date;
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
HTML THYMELEAF
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>login</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
<link href="https://getbootstrap.com/docs/4.0/examples/signin/signin.css" rel="stylesheet" crossorigin="anonymous">
<style>
body {
background-color: #3e3e3e;
color: white;
}
h2 {
text-align: center;
}
</style>
</head>
<body>
<div class="container">
<form class="date" name="date" method="post" action="/insert/date" enctype="application/x-www-form-urlencoded">
<h2 class="form-register-heading">Please Enter Date</h2>
<p>
<label for="date" class="sr-only">Date</label>
<input type="text" id="date" name="date" class="date" placeholder="date" required=""
autofocus="">
</p>
<button class="btn btn-lg btn-primary btn-block" type="submit">Insert Date</button>
</form>
</div>
</body>
</html>
The question is a little bit strange. As you say that this functional interface is called when we run our applications with command-line(So it is called CommandLineRunner) and at that time we may give some params from command prompt like that java -jar MyApp "param1" "param2". param1 and param2 are passed to main method as params. So it is called only one time.
CommandLineRunner is a simple Spring Boot interface with a run method.
Spring Boot will automatically call the run method of all beans
implementing this interface after the application context has been
loaded.
PS: if you want to call your business logic after the completion of the method, You can you Spring AOP. if you have another scenario like performing a method in a different thread, may use ExecutorServices class in order to reach it or you can implement it by yourself.

Spring keeps returning String as Response instead of Html

I am neither using ResponseBody nor I am using RestController annotation Still my Spring Application is returning String instead of jsp/html pages.
Here are my files of Application Configuration and Controller.
Where am I going wrong?
The GIT link to my code
Web Configuration File:
package com.springimplant.mvc.config;
import java.io.IOException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
import org.springframework.web.servlet.view.ResourceBundleViewResolver;
import org.springframework.web.servlet.view.UrlBasedViewResolver;
import org.springframework.web.servlet.view.XmlViewResolver;
#Configuration
#EnableWebMvc
#ComponentScan(basePackages="com.springimplant.mvc.controllers")
public class SimpleWebConfiguration implements WebMvcConfigurer {
#Bean
public ViewResolver internalResourceViewResolver() {
// UrlBasedViewResolver bean = new UrlBasedViewResolver();
InternalResourceViewResolver bean = new InternalResourceViewResolver();
bean.setViewClass(JstlView.class);
bean.setPrefix("/WEB-INF/views/");
bean.setSuffix(".jsp");
bean.setOrder(0);
return bean;
}
#Bean
public ViewResolver resourceBundleViewResolver() {
ResourceBundleViewResolver bean = new ResourceBundleViewResolver();
bean.setBasename("views");
bean.setOrder(1);
return bean;
}
#Bean
public ViewResolver xmlViewResolver(){
XmlViewResolver bean = new XmlViewResolver();
bean.setLocation(new ClassPathResource("views.xml"));
bean.setOrder(2);
return bean;
}
#Override
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.jsp("/WEB-INF/views/", ".jsp");
}
#Override
public void addViewControllers(ViewControllerRegistry registry) {
// registry.addViewController("/").setViewName("forward:/welcome");
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
HomeController:
package com.springimplant.mvc.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
#Controller
#RequestMapping("/")
public class HomeController {
#RequestMapping(value="welcome",method=RequestMethod.GET)
public ModelAndView welcome()
{
return new ModelAndView("welcome");
}
}
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Welcome Home</title>
</head>
<body>
Welcome Home
</body>
</html>
So I Had these page tag over my jsp file which I removed and now it runs fine but why?
I didn't had to do this for my earlier projects.

HTTP Status 404 – Not Found : The origin server did not find a current representation for the target resource

I am getting error while trying to access service in spring framework.
Controller class :-
package com.spring.mvc.tutorial;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
#RequestMapping("/")
public class HelloWorldController {
#RequestMapping(method = RequestMethod.GET)
public String sayHello(ModelMap model) {
model.addAttribute("message", "Hello World from Spring 4 MVC");
return "welcome";
}
#RequestMapping(value = "/hello", method = RequestMethod.GET)
public String sayHelloAgain(ModelMap model) {
model.addAttribute("message", "Hello World Again, from Spring 4 MVC");
return "welcome";
}
}
Configuration class :-
package com.spring.mvc.tutorial;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "com.spring.mvc.tutorial")
public class HelloWorldConfiguration {
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
Initialization class :-
package com.spring.mvc.tutorial;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class HelloWorldInitializer implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext container) throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(HelloWorldConfiguration.class);
ctx.setServletContext(container);
ServletRegistration.Dynamic servlet = container.addServlet("dispatcher", new DispatcherServlet(ctx));
servlet.setLoadOnStartup(1);
servlet.addMapping("/");
}
}
View :-
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>HelloWorld page</title>
</head>
<body>
<h2>${message}</h2>
</body>
</html>
NOTE :-
Request : http://localhost:8080/SpringMvcHelloWorld/
This is developed in Eclipse Photon and deployed to Tomcat 8.5.
Try redirecting to the main html page in your controller class :
#RequestMapping(method = RequestMethod.GET)
public String sayHello(ModelMap model) {
model.addAttribute("message", "Hello World from Spring 4 MVC");
return "redirect:/main.html";
}
Replace main.html with the path of your home page
I have got the same problem and resolved it by checking where the attributes like #controller and #RequestMapping were binded to the mvc packages
To check whether the sources are binded:
Go to the controller page and press control and left button on #Controller together.
If source is not binded then it will appear as shown in the figure.
If the source is not binded then attach the source by clicking the attach source button and point towards the spring-webmvc-5.1.3.RELEASE-sources.
Check the other jars by following the above two steps.
I can't comment yet hence this is in form of an answer.
I had similar issue when tomcat was not initializing the web app. Can you please add as System.out.println on your initialiser to see if it is initializing the webapp in the first place.
And share your server logs on here.

Spring Boot i18n issue

I am learning spring Boot framework right now, I am trying to apply i18n concept on my simple application. But whenever I run the application, the following error returned: "No message found under code 'label.welcomeMessage' for locale 'en_US'.". I have read about this issue and tried a lot before I getting here to ask but noting have worked with me.
Here is my AppClass configuration:
package com.abed.main.configuration;
import java.util.Locale;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
#Configuration
public class AppConfig 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());
}
#Bean
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource msgSrc = new ReloadableResourceBundleMessageSource();
msgSrc.setBasename("classpath:messages/ticket");
msgSrc.setDefaultEncoding("UTF-8");
return msgSrc;
}
}
Here is the welcome JSP:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix = "spring" uri="http://www.springframework.org/tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title><spring:message code="label.welcomePageTitle"></spring:message></title>
</head>
<body>
<h1><spring:message code="label.welcomeMessage"></spring:message></h1>
<form action="ticket" method="GET">
<spring:message code="label.ticketId"></spring:message><input type="text" name="Student_Id">
<input type="submit" value="<spring:message code="label.search"></spring:message>">
</form>
<spring:message code="label.createTicketSubmit"></spring:message>
</body>
</html>
and here is the hierarchy of my application:
Any Help Please , Thanks in advance
You need to configuration a bean named messageSource
here is the code, add it to a java code file, make sure #Configuration can be scan:
#Configuration
public class MessageSourceConfig {
#Bean(name = "messageSource")
public ResourceBundleMessageSource getMessageSource() throws Exception {
ResourceBundleMessageSource resourceBundleMessageSource = new ResourceBundleMessageSource();
resourceBundleMessageSource.setDefaultEncoding("UTF-8");
resourceBundleMessageSource.setBasenames("i18n/messages");
return resourceBundleMessageSource;
}
}
The point is : resourceBundleMessageSource.setBasenames("i18n/messages");
remember the base path is classpath, so the i18n properties resource should set in i18n/messages. In order not to crash problem, I suggest you create the properties by using IDEA.
Quote Spring official doc:
Strategy interface for resolving messages, with support for the parameterization and internationalization of such messages.
Spring provides two out-of-the-box implementations for production:
ResourceBundleMessageSource, built on top of the standard ResourceBundle
ReloadableResourceBundleMessageSource, being able to reload message definitions without restarting the VM.
This is the reason we need to configure a bean named messageSource.

Place the Index.html To Run

I am beginning to study AngularJS with Spring MVC and I wanted when I entered the system in the case http: // localhost: 8080 / he entered a home page that is called index.html, walked snooping on the Internet, most could not succeed in time to call the page.
This is my controller that just created to call the page as in the examples I've seen too.
package br.com.escconsultoria.standard.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
#RestController
#RequestMapping(value = "/")
public class IndexController {
#RequestMapping(method = RequestMethod.GET)
public ModelAndView getIndexPage() {
return new ModelAndView("/index");
}
}
Beauty of this fine examples simply doing: it returns index, worked over my could not for nothing there I saw talking about using Template: Thymeleaf only that I could not even now he does not think where's the page.
package br.com.escconsultoria.standard.configuration;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ViewResolver;
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 org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = {"br.com.escconsultoria.standard.configuration",
"br.com.escconsultoria.standard.controller",
"br.com.escconsultoria.standard.repository",
"br.com.escconsultoria.standard.service",
"br.com.escconsultoria.imobiliario.controller",
"br.com.escconsultoria.imobiliario.repository",
"br.com.escconsultoria.imobiliario.service"})
public class AppConfiguration extends WebMvcConfigurerAdapter{
/*#Bean
public ServletContextTemplateResolver templateResolver() {
ServletContextTemplateResolver resolver = new ServletContextTemplateResolver();
resolver.setPrefix("/resources/");
resolver.setSuffix(".html");
resolver.setTemplateMode("HTML5");
resolver.setOrder(1);
return resolver;
}*/
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/templates/");
viewResolver.setSuffix(".html");
viewResolver.setCache(false);
return viewResolver;
}
#Bean
public CommonsMultipartResolver multipartResolver() {
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
multipartResolver.setMaxUploadSize(100000l);
return multipartResolver;
}
#Bean
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("messages");
return messageSource;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/app/**").addResourceLocations("/app/");
registry.addResourceHandler("/assets/**").addResourceLocations("/assets/");
registry.addResourceHandler("/static/**").addResourceLocations("/static/");
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
registry.addResourceHandler("/templates/**").addResourceLocations("/templates/");
}
}
Does anyone have an idea how to implement it?
My index page is in the scr/main/resources/templates/index.html
Solution:
Good I managed to solve my problem and I am putting the solution here, first the first thing that kept me from work was the Controller noted with RestController and needed to be only Controller.
#Controller
#RequestMapping(value = "/")
public class IndexController {
#RequestMapping(method = RequestMethod.GET)
public String getIndexPage() {
return "index3";
}
}
And according to my App Configuration it looked like this.
package br.com.escconsultoria.standard.configuration;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ViewResolver;
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 org.springframework.web.servlet.view.InternalResourceViewResolver;
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = {"br.com.escconsultoria.standard.configuration",
"br.com.escconsultoria.standard.controller",
"br.com.escconsultoria.standard.repository",
"br.com.escconsultoria.standard.service",
"br.com.escconsultoria.imobiliario.controller",
"br.com.escconsultoria.imobiliario.repository",
"br.com.escconsultoria.imobiliario.service"})
public class AppConfiguration extends WebMvcConfigurerAdapter{
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/templates/");
viewResolver.setSuffix(".html");
viewResolver.setCache(false);
return viewResolver;
}
#Bean
public CommonsMultipartResolver multipartResolver() {
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
multipartResolver.setMaxUploadSize(100000l);
return multipartResolver;
}
#Bean
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("messages");
return messageSource;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/app/**").addResourceLocations("/app/");
registry.addResourceHandler("/assets/**").addResourceLocations("/assets/");
registry.addResourceHandler("/static/**").addResourceLocations("/static/");
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
registry.addResourceHandler("/templates/**").addResourceLocations("/templates/");
}
}
Then I had a little problem in the index that I was trying to do more was because they were generating in Pingendo and he did not close the tag in the case of the target, input and some other was not close at hand and it worked. My Test HTML below.
<html>
<head>
<meta charset="utf-8"></meta>
<meta name="viewport" content="width=device-width, initial-scale=1"></meta>
<script type="text/javascript"
src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script type="text/javascript"
src="http://netdna.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<link
href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css"
rel="stylesheet" type="text/css"></link>
<link
href="http://pingendo.github.io/pingendo-bootstrap/themes/default/bootstrap.css"
rel="stylesheet" type="text/css"></link>
</head>
<body>
<div class="navbar navbar-default navbar-static-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse"
data-target="#navbar-ex-collapse">
<span class="sr-only">Toggle navigation</span><span
class="icon-bar"></span><span class="icon-bar"></span><span
class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#"><span>Brand</span></a>
</div>
<div class="collapse navbar-collapse" id="navbar-ex-collapse">
<ul class="nav navbar-nav navbar-right">
<li class="active">Home</li>
<li>Contacts</li>
</ul>
</div>
</div>
</div>
<div class="section">
<div class="container">
<div class="row">
<div class="col-md-12">
<form class="form-horizontal" role="form">
<div class="form-group">
<div class="col-sm-2">
<label for="inputEmail3" class="control-label">Email</label>
</div>
<div class="col-sm-10">
<input type="email" class="form-control" id="inputEmail3"
placeholder="Email"></input>
</div>
</div>
<div class="form-group">
<div class="col-sm-2">
<label for="inputPassword3" class="control-label">Password</label>
</div>
<div class="col-sm-10">
<input type="password" class="form-control" id="inputPassword3"
placeholder="Password"></input>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<div class="checkbox">
<label><input type="checkbox"> Remember me </input></label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">Sign in</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</body>
</html>

Categories