I've tried to configure controllers for thymeleaf views resolver, but it doesn't work. I made controller test and they passed so i think it is servlets configuration problem.
My WebConfig looks like this:
#Configuration
#EnableWebMvc
#ComponentScan("springmvccommerce.web")
public class WebConfig implements WebMvcConfigurer{
#Bean
ViewResolver viewResolver() {
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(templateEngine());
return viewResolver;
}
#Bean
public SpringResourceTemplateResolver templateResolver() {
SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
templateResolver.setPrefix("/WEB-INF/templates/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode(TemplateMode.HTML);
templateResolver.setCacheable(true);
return templateResolver;
}
#Bean
public SpringTemplateEngine templateEngine() {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
templateEngine.setEnableSpringELCompiler(true);
return templateEngine;
}
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
Edit:
HomeController:
#Controller
public class HomeController {
#GetMapping("/")
public String home() {
return "home";
}
}
And productController:
#Controller
public class ProductController {
#Autowired
private ProductRepository productRepository;
#GetMapping("/products")
public String products(Model model) {
model.addAttribute("productList", productRepository.findProduct(Long.MAX_VALUE, 20));
return "products";
}
}
If it is not enough, I've added link to repo in comment.
It seems spring boot haven't support for tomcat 10 due to the jakarta namespace, switch to tomcat 9 and retry.
Here are some links related:
https://github.com/spring-projects/spring-framework/issues/25354
Deploying Spring 5.x on Tomcat 10.x with jakarta.* package
Related
I'm using springboot + thymeleaf and have just started setting up the project.
At first this worked fine, showing my home page and account page, but I must've changed something somewhere because now it will only show home.
weird stuff 1: It takes the template home from the resources/templates folder, although I've configured it to not do that. My guess is it doesn't use the configuration.
weird stuff 2: It only finds the home template, not the account template.
What do I need to change to get this working again?
Configuration class:
#SpringBootApplication
#RestController
#Configuration
#ComponentScan("applikaasie.domein")
public class startApp {
public static void main(String[] args) {
SpringApplication.run(startApp.class, args);
}
#Bean
public ViewResolver viewResolver(SpringTemplateEngine templateEngine) {
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(templateEngine);
return viewResolver;
}
#Bean
public TemplateEngine templateEngine(TemplateResolver templateResolver) {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver);
return templateEngine;
}
#Bean
public TemplateResolver templateResolver() {
TemplateResolver templateResolver = new ServletContextTemplateResolver();
templateResolver.setPrefix("/WEB-INF/templates");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode("HTML5");
System.out.println("templateResolver");
return templateResolver;
}
}
Account class:
#Controller
#RequestMapping(value="account")
public class AccountController {
#RequestMapping(value="/", method=GET)
public String greeting() {
return "home";
}
#RequestMapping(value="/accounts", method=RequestMethod.GET)
public String accountList(Model model) {
model.addAttribute(accountRepository.getAllAccounts());
return "accounts";
}
}
Directory structure:
/resources
/templates
account.html
home.html
/webapp
/WEB-INF
/templates
account.html
home.html
UPDATE
Resetting the computer fixed this. I guess something in memory was wrong.
I've tried a lot of solutions but it just doesn't work. I'm using Intellij 2016.1.
I can't force the app to resolve templates.
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateInputException: Error resolving template "/login/login", template might not exist or might not be accessible by any of the configured Template Resolvers
config
#Configuration
#ComponentScan(basePackages = "com.unibooker")
#EnableWebMvc
public class Config extends WebMvcConfigurerAdapter{
#Bean
public TemplateResolver templateResolver() {
ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver();
templateResolver.setPrefix("classpath:/WEB-INF/templates/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode("HTML5");
return templateResolver;
}
#Bean(name = "templateEngine")
public SpringTemplateEngine getTemplateEngine()
{
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(this.templateResolver());
templateEngine.setMessageSource(this.messageSource());
templateEngine.addDialect(new LayoutDialect());
return templateEngine;
}
#Bean
public ViewResolver setupViewResolver()
{
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(this.getTemplateEngine());
viewResolver.setOrder(1);
return viewResolver;
}
#Bean
public MessageSource messageSource()
{
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("messages");
messageSource.setDefaultEncoding("UTF-8");
messageSource.setCacheSeconds(3600);
return messageSource;
}
#Bean
public LocaleResolver localeResolver()
{
CookieLocaleResolver resolver = new CookieLocaleResolver();
resolver.setDefaultLocale(new Locale("pl"));
resolver.setCookieName("locale");
resolver.setCookieMaxAge(86400);
return resolver;
}
#Override
public void addInterceptors(InterceptorRegistry registry)
{
LocaleChangeInterceptor interceptor = new LocaleChangeInterceptor();
interceptor.setParamName("locale");
registry.addInterceptor(interceptor);
}
#Override
public void addResourceHandlers(final ResourceHandlerRegistry registry)
{
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
}
Project structure - IMAGE
I have tried to move templates to resources but still nothing. Please help. I have no more ideas how to fix this ... It worked earlier and then stopped.
Thymeleaf Resolver will look under templates/login/ for a login.html page. Based on your project structure and configuration, you rightly have a login folder inside template but you don't have a login.html inside the directory which is why the reason for the error.
Either create a login.html inside the login folder or use the index.html page which is already there. In your spring controller you should return the appropriate page.
For example,
Assuming that you need to show the login page your controller method should return,
return "login/login" // to display login.html under `templates/login`
or
return "login/index" // to display index.html under `templates/login`
I encounter this problem while I am trying to duplicate a simple spring OAuth project, sparklr2. source code here
https://github.com/spring-projects/spring-security-oauth/tree/master/samples/oauth2/sparklr
the source code runs perfectly, when I debug it with tomcat, it initialize all #Bean inside WebMvcConfigurerAdapter, including controllers. but noted that #ComponentScan() is not being used.
then I create my own MVC project, copy almost 100% of code, but I am using WebApplicationInitializer instead of AbstractDispatcherServletInitializer. I use WebApllicationInitializer because I have only learned this way to code MVC.
then I run the project, #Bean initialized. then I check /login with my browser, get 404. this could be caused by spring not knowing I have controllers, then I add #ComponentScan to my configuration class, /login now shows up.
but the weird thing is, all #Bean related to Controller, are not initialized. so, when I call any method to those controller, since their attributes are not initialized, gives me no object or null exception.
So, my point is, how does that sample works, I mean controller and jsp correctly handle and response without using #ComponentScan?
and look at it from different angle, why does #ComponentScan stop #Bean from being initialize in my project?
my WebApplicationInitializer
#Configuration
#EnableWebMvc
#ComponentScan("umedia.test.oauth.controller")
public class MvcConfig extends WebMvcConfigurerAdapter {
#Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
#Bean
public ContentNegotiatingViewResolver contentViewResolver()
throws Exception {
ContentNegotiationManagerFactoryBean contentNegotiationManager = new ContentNegotiationManagerFactoryBean();
contentNegotiationManager.addMediaType("json",
MediaType.APPLICATION_JSON);
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
MappingJackson2JsonView defaultView = new MappingJackson2JsonView();
defaultView.setExtractValueFromSingleKeyModel(true);
ContentNegotiatingViewResolver contentViewResolver = new ContentNegotiatingViewResolver();
contentViewResolver
.setContentNegotiationManager(contentNegotiationManager
.getObject());
contentViewResolver.setViewResolvers(Arrays
.<ViewResolver> asList(viewResolver));
contentViewResolver.setDefaultViews(Arrays.<View> asList(defaultView));
return contentViewResolver;
}
#Bean
public PhotoServiceImpl photoServices() {
List<PhotoInfo> photos = new ArrayList<PhotoInfo>();
photos.add(createPhoto("1", "marissa"));
photos.add(createPhoto("2", "paul"));
photos.add(createPhoto("3", "marissa"));
photos.add(createPhoto("4", "paul"));
photos.add(createPhoto("5", "marissa"));
photos.add(createPhoto("6", "paul"));
PhotoServiceImpl photoServices = new PhotoServiceImpl();
photoServices.setPhotos(photos);
return photoServices;
}
// N.B. the #Qualifier here should not be necessary (gh-298) but lots of
// users report needing it.
#Bean
public AdminController adminController(
TokenStore tokenStore,
#Qualifier("consumerTokenServices") ConsumerTokenServices tokenServices,
SparklrUserApprovalHandler userApprovalHandler) {
AdminController adminController = new AdminController();
adminController.setTokenStore(tokenStore);
adminController.setTokenServices(tokenServices);
adminController.setUserApprovalHandler(userApprovalHandler);
return adminController;
}
// this url, do I need to change it?
private PhotoInfo createPhoto(String id, String userId) {
PhotoInfo photo = new PhotoInfo();
photo.setId(id);
photo.setName("photo" + id + ".jpg");
photo.setUserId(userId);
photo.setResourceURL("/org/springframework/security/oauth/examples/sparklr/impl/resources/"
+ photo.getName());
return photo;
}
#Override
public void configureDefaultServletHandling(
DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Bean
public PhotoServiceUserController photoServiceUserController(
PhotoService photoService) {
PhotoServiceUserController photoServiceUserController = new PhotoServiceUserController();
return photoServiceUserController;
}
#Bean
public PhotoController photoController(PhotoService photoService) {
PhotoController photoController = new PhotoController();
photoController.setPhotoService(photoService);
return photoController;
}
#Bean
public AccessConfirmationController accessConfirmationController(
ClientDetailsService clientDetailsService,
ApprovalStore approvalStore) {
AccessConfirmationController accessConfirmationController = new AccessConfirmationController();
accessConfirmationController
.setClientDetailsService(clientDetailsService);
accessConfirmationController.setApprovalStore(approvalStore);
return accessConfirmationController;
}
/* #Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}*/
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations(
"/resources/");
}
}
so, you have #ComponentScan which interacts with #Controller on your controllers + still create #Bean's with those?
As a first step try to remove #Beans and try to inject dependencies using #Autowired on controllers' constructors. Then #ComponentScan should recognize #Controller, inject dependencies and use #RequestMapping without issues.
I have a Spring MVC application with Thymeleaf configured to use fragments (NO tiles!) and all files have .html extension. Everything is working fine.
Now i'm trying to setup Webflow but, when i call my webflow url, i get 404 error as he tries to load a JSP view instead of html (outside flow, everything is fine):
HTTP Status 404 - /app/WEB-INF/views/contest/contest-step1.jsp
I know that put kilometers of line of code isn't good, but honestly i don't know which pieces are interesting and which no.
ThymeleafConfig:
#Configuration
public class ThymeleafConfig {
#Bean
public TemplateResolver templateResolver() {
ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver();
templateResolver.setPrefix("/WEB-INF/views/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode("HTML5");
/**
* only on development machine
*/
templateResolver.setCacheable(false);
return templateResolver;
}
#Bean
public SpringTemplateEngine templateEngine() {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
Set<IDialect> dialects = new HashSet<IDialect>();
dialects.add(springSecurityDialect());
templateEngine.setAdditionalDialects(dialects);
templateEngine.setTemplateResolver(templateResolver());
return templateEngine;
}
#Bean
public ThymeleafViewResolver thymeleafViewResolver() {
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
resolver.setTemplateEngine(templateEngine());
return resolver;
}
#Bean
public SpringSecurityDialect springSecurityDialect(){
SpringSecurityDialect dialect = new SpringSecurityDialect();
return dialect;
}
}
WebAppConfig:
#Configuration
#EnableWebMvc
#ComponentScan("com.myapp")
public class WebAppConfig extends WebMvcConfigurerAdapter {
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/login").setViewName("login");
registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
}
#Bean
public UrlBasedViewResolver setupViewResolver() {
UrlBasedViewResolver resolver = new UrlBasedViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
// Maps resources path to webapp/resources
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
/**************************************************
*
* Web Flow: wizard contest
*
*/
#Autowired
private WebFlowConfig webFlowConfig;
/**
* Maps request paths to flows in the flowRegistry;
* e.g. a path of /hotels/booking looks for a flow with id "hotels/booking"
*
* Configuring this mapping allows the Dispatcher to map application resource paths
* to flows in a flow registry.
* For example, accessing the resource path /hotels/booking would result in a
* registry query for the flow with id hotels/booking.
* If a flow is found with that id,
* that flow will handle the request. If no flow is found, the next handler mapping in the
* Dispatcher's ordered chain will be queried or a "noHandlerFound" response will be returned.
*/
#Bean
public FlowHandlerMapping flowHandlerMapping() {
FlowHandlerMapping handlerMapping = new FlowHandlerMapping();
handlerMapping.setOrder(-1); //0 ?
handlerMapping.setFlowRegistry(this.webFlowConfig.flowRegistry());
return handlerMapping;
}
#Bean
public FlowHandlerAdapter flowHandlerAdapter() {
FlowHandlerAdapter handlerAdapter = new FlowHandlerAdapter();
handlerAdapter.setFlowExecutor(this.webFlowConfig.flowExecutor());
handlerAdapter.setSaveOutputToFlashScopeOnRedirect(true);
return handlerAdapter;
}
#Bean(name="contest/add") //defined in in WebFlowConfig
public ContestFlowHandler ContestFlowHandler() {
return new ContestFlowHandler();
}
/* TODO
#Bean
public AjaxThymeleafViewResolver tilesViewResolver() {
AjaxThymeleafViewResolver viewResolver = new AjaxThymeleafViewResolver();
viewResolver.setViewClass(FlowAjaxThymeleafTilesView.class);
viewResolver.setTemplateEngine(templateEngine());
return viewResolver;
} */
}
WebFlowConfig:
#Configuration
public class WebFlowConfig extends AbstractFlowConfiguration {
#Autowired
private ThymeleafConfig thymeleafConfig;
//private WebFlowConfig WebAppConfig;
#Bean
public FlowDefinitionRegistry flowRegistry() {
return getFlowDefinitionRegistryBuilder()
.addFlowLocation("/WEB-INF/views/gare/gare-add-flow.xml", "gare/add")
.build();
}
#Bean
public FlowExecutor flowExecutor() {
return getFlowExecutorBuilder(flowRegistry())
.setMaxFlowExecutions(5)
.setMaxFlowExecutionSnapshots(30)
.build();
}
#Bean
public FlowBuilderServices flowBuilderServices() {
return getFlowBuilderServicesBuilder()
.setViewFactoryCreator(mvcViewFactoryCreator())
.build();
}
#Bean
public MvcViewFactoryCreator mvcViewFactoryCreator() {
MvcViewFactoryCreator factoryCreator = new MvcViewFactoryCreator();
factoryCreator.setViewResolvers(Arrays.<ViewResolver>asList(this.thymeleafConfig.thymeleafViewResolver()));
factoryCreator.setUseSpringBeanBinding(true);
return factoryCreator;
}
}
I found a trick that gives me a quick solution, but honestly i would like don't do this, but correctly configure the resolver. The trick is to set the view file in flow xml file:
<view-state id="contest-step1" model="contest" view="/WEB-INF/views/contest/contest-step1.html"></view-state>
thanks
Try the following in flowRegistry method.
return getFlowDefinitionRegistryBuilder(flowBuilderServices())
instead of
return getFlowDefinitionRegistryBuilder()
Hope this helps.
I am not sure but kindly look into the following part of your code
#Bean
public UrlBasedViewResolver setupViewResolver() {
UrlBasedViewResolver resolver = new UrlBasedViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
it is pointing to .jsp whatever you call in controller it will append .jsp
Also your controller code is not here url mapping should be like /login.html
I am not much familier with thymeleaf and spring-webflow-2
I'm trying to override the ValidationMessages.properties from default hibernate-validation (5.0.2 version) in a Spring MVC application.
But it keeps using the internal ValidationMessages.properties from jar.
UPDATE: it works (but it should be another way) when I copy the *.properties files to org\hibernate\validator ...
This is my configuration:
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = {"com.blueliv.search.*"} )
public class WebConfig extends WebMvcConfigurerAdapter {
static Logger log =LoggerFactory.getLogger(WebMvcConfigurerAdapter.class);
#Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(new GsonHttpMessageConverter());
//converters.add(new MappingJackson2HttpMessageConverter());
}
#Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
return new MethodValidationPostProcessor();
}
#Bean
public ExceptionHandlerExceptionResolver exceptionResolver() {
return new ExceptionHandlerExceptionResolver();
}
#Bean
public LocalValidatorFactoryBean validator() {
LocalValidatorFactoryBean validatorFactoryBean = new LocalValidatorFactoryBean();
validatorFactoryBean.setValidationMessageSource(getBundle());
return validatorFactoryBean;
}
public ReloadableResourceBundleMessageSource getBundle(){
log.debug("get bundle!");
ReloadableResourceBundleMessageSource bundle = new ReloadableResourceBundleMessageSource();
bundle.setBasenames("classpath:/i18n/validation/ValidatonMessages");
return bundle;
}
#Override
public Validator getValidator() {
return validator();
}