Secure spring boot with mysql - entityMangerFactory not found - spring

I try to secure my spring boot application using security and mysql as provider.
When I debug application I get this error:
Field sysUserRepository in SysUserService required a bean named 'entityManagerFactory' that could not be found.
I already read this question
How to use Spring Boot with MySQL database and JPA?
This is SysUserService
package com.cm.sb.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.cm.sb.model.SysUser;
import com.cm.sb.repository.SysUserRepository;
#Service
public class SysUserService {
#Autowired
SysUserRepository sysUserRepository;
public SysUser findByusername(String username) {
return sysUserRepository.findByUsername(username);
}
}
This is my spring boot initializer
package com.cm.sb;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#SpringBootApplication(scanBasePackages={"com.cm.sb"},exclude = { SecurityAutoConfiguration.class })
#EnableJpaRepositories(basePackages = "com.cm.sb")
public class SbApplication extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(SbApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(SbApplication.class, args);
}
}
application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/sb?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect
spring.jpa.show-sql=false
spring.jpa.hibernate.ddl-auto=none
spring.mvc.view.prefix: /WEB-INF/jsp/
spring.mvc.view.suffix: .jsp
security.user.password=ciro
security.user.username=ciro
This is my secure config class
package com.cm.sb.config;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Resource(name = "userDetailService")
private UserDetailsService userDetailsService;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().requireCsrfProtectionMatcher(new AntPathRequestMatcher("**/login"))
.and().authorizeRequests().antMatchers("/dashboard").hasRole("USER")
.and().authorizeRequests().antMatchers("/home").permitAll()
.and().formLogin().defaultSuccessUrl("/dashboard").loginPage("/login")
.and().logout().permitAll();
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/*.css");
web.ignoring().antMatchers("/*.js");
}
}
This is My repository class
package com.cm.sb.repository;
import com.cm.sb.model.SysUser;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository("sysUserRepository")
public interface SysUserRepository extends JpaRepository<SysUser, Integer> {
SysUser findByUsername(String username);
}
edit: my pom
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.cm</groupId>
<artifactId>sb</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>sb</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<hibernate.version>4.3.11.Final</hibernate.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<!-- necessaria per le jsp -->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

I tried to use the same code that you have posted before and i can start the service boot.
Here is all what i change :
package com.cm.sb.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.cm.sb.entity.SysUser;
public interface SysUserRepository extends JpaRepository<SysUser, Integer> {
SysUser findByUsername(String username);
}
The main class :
package com.cm.sb;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#SpringBootApplication(exclude = { SecurityAutoConfiguration.class })
#EnableJpaRepositories(basePackages = "com.cm.sb.repository")
#ComponentScan("com.cm.sb.service")
#EntityScan("com.cm.sb.entity")
public class SbExampleApplication extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(SbExampleApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(SbExampleApplication.class, args);
}
}
The properties file:
spring.datasource.url=jdbc:mysql://localhost:3306/sb
spring.datasource.username=root
spring.datasource.password=
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect
spring.jpa.show-sql=false
spring.jpa.hibernate.ddl-auto=create // because i want to generate the db from entities
spring.mvc.view.prefix: /WEB-INF/jsp/
spring.mvc.view.suffix: .jsp
security.user.password=ciro
security.user.username=ciro
The stack trace :
2018-11-29 18:19:17.746 INFO 6340 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-11-29 18:19:17.802 INFO 6340 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-11-29 18:19:17.802 INFO 6340 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-11-29 18:19:17.862 INFO 6340 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-11-29 18:19:18.161 INFO 6340 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2018-11-29 18:19:18.163 INFO 6340 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Bean with name 'dataSource' has been autodetected for JMX exposure
2018-11-29 18:19:18.171 INFO 6340 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Located MBean 'dataSource': registering with JMX server as MBean [com.zaxxer.hikari:name=dataSource,type=HikariDataSource]
2018-11-29 18:19:18.257 INFO 6340 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2018-11-29 18:19:18.260 INFO 6340 --- [ main] com.cm.sb.SbExampleApplication : Started SbExampleApplication in 5.051 seconds (JVM running for 5.991)

Related

Spring Boot #DataJpaTest stuck at HHH000400: Using dialect: org.hibernate.dialect.Oracle12cDialect

I have a JUnit 5 test that isn't working, it gets stuck as shown below:
2020-04-03 16:53:23.207 INFO 2788 --- [ main] .i.p.d.r.CustomerReferenceRepositoryTest :
No active profile set, falling back to default profiles: default
2020-04-03 16:53:24.153 INFO 2788 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate :
Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2020-04-03 16:53:24.590 INFO 2788 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate :
Finished Spring Data repository scanning in 372ms. Found 8 JPA repository interfaces.
2020-04-03 16:53:26.078 INFO 2788 --- [ main] com.zaxxer.hikari.HikariDataSource :
HikariPool-1 - Starting...
2020-04-03 16:53:27.667 INFO 2788 --- [ main] com.zaxxer.hikari.HikariDataSource :
HikariPool-1 - Start completed.
2020-04-03 16:53:27.997 INFO 2788 --- [ main] o.hibernate.jpa.internal.util.LogHelper :
HHH000204: Processing PersistenceUnitInfo [name: default]
2020-04-03 16:53:28.392 INFO 2788 --- [ main] org.hibernate.Version :
HHH000412: Hibernate ORM core version 5.4.12.Final
2020-04-03 16:53:28.866 INFO 2788 --- [ main] o.hibernate.annotations.common.Version :
HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
2020-04-03 16:53:29.180 INFO 2788 --- [ main] org.hibernate.dialect.Dialect :
HHH000400: Using dialect: org.hibernate.dialect.Oracle12cDialect
The test is annotated like this:
#DataJpaTest
#AutoConfigureTestDatabase(replace = Replace.NONE)
#ContextConfiguration(classes = TestDALConfig.class)
class CustomerReferenceRepositoryTest {
The test gets stuck and when I stop it manually I get this error messsage:
No tests found with test runner 'JUnit 5'
The test it self is very simple:
#Test
public void notNull() {
assertThat(customerReferenceRepository).isNotNull();
}
The complete unit test
package <removed>.payment.dal.repository;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.ContextConfiguration;
import aero.sita.pts.ir.payment.config.TestDALConfig;
#DataJpaTest
#AutoConfigureTestDatabase(replace = Replace.NONE)
#ContextConfiguration(classes = TestDALConfig.class)
class CustomerReferenceRepositoryTest {
#Autowired
private CustomerReferenceRepository customerReferenceRepository;
public CustomerReferenceRepositoryTest() {
super();
}
#Test
public void notNull() {
assertThat(customerReferenceRepository).isNotNull();
}
}
The maven pom
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.6.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<artifactId>payment-dal-api</artifactId>
<name>payment-dal-api</name>
<description>payment-dal-api</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
<ojdbc7.version>12.1.0.2</ojdbc7.version>
</properties>
<dependencies>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc7</artifactId>
<version>${ojdbc7.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
</project>
TestDALConfig
#Configuration
#EnableJpaRepositories(basePackageClasses=ConfigRepository.class)
public class TestDALConfig {
public TestDALConfig() {
super();
}
}
CustomerReferenceRepository
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import aero.sita.pts.ir.payment.dal.dto.CustomerReferenceDTO;
#Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
#Repository
public interface CustomerReferenceRepository extends PagingAndSortingRepository<CustomerReferenceDTO, Long> {
}
Can anyone shed some light on this?
Thanks
In your application yaml or properties file , try updating below !
spring.jpa.ddl-auto: none
Please verify the import in the entity class. For example for Date, the correct import is:
java.util.Date
Not:
java.sql.Date

Unable to proceed with debugging

I am working with a spring boot project , which deals with redirect attributes . I want to debug my application and its getting stuck at this point .
2020-03-25 20:28:47.785 INFO 13073 --- [ main] .e.d.SpringRedirectattributesApplication : Starting SpringRedirectattributesApplication on rajgopal with PID 13073 (/home/rajgopal/Spring-Boot/spring-redirectattributes/target/classes started by rajgopal in /home/rajgopal/Spring-Boot/spring-redirectattributes)
2020-03-25 20:28:47.792 INFO 13073 --- [ main] .e.d.SpringRedirectattributesApplication : No active profile set, falling back to default profiles: default
Here is my project structure
I am also providing the remaining code
SpringRedirectattributesApplication.java
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class SpringRedirectattributesApplication {
public static void main(String[] args) {
SpringApplication.run(SpringRedirectattributesApplication.class, args);
}
}
WebConfig.java
import org.springframework.context.annotation.Bean;
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.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
#EnableWebMvc
#ComponentScan(basePackages = { "com.example.demo.controller" })
#Configuration
public class WebConfig implements WebMvcConfigurer {
#Bean
public ViewResolver viewResolver() {
final InternalResourceViewResolver bean = new InternalResourceViewResolver();
bean.setViewClass(JstlView.class);
bean.setPrefix("/WEB-INF/view/");
bean.setSuffix(".jsp");
return bean;
}
}
RedirectAttributesExample.java
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.support.RequestContextUtils;
import org.springframework.web.servlet.view.RedirectView;
#Controller
public class RedirectAttributesExample {
#GetMapping("/redirect")
public RedirectView redirectWithRedirectAttributes(RedirectAttributes attributes) {
attributes.addFlashAttribute("flashAttribute", "redirectWithRedirectAttributes");
attributes.addAttribute("attribute", "redirectWithRedirectAttributes");
return new RedirectView("redirectedUrl");
}
#GetMapping("/redirectedUrl")
public ModelAndView redirection(ModelMap model, HttpServletRequest request) {
String some = null, some1 = null;
Map<String, ?> inputFlashMap = RequestContextUtils.getInputFlashMap(request);
if (inputFlashMap != null) {
some = (String) inputFlashMap.get("flashAttribute");
}
some1 = (String) ((Model) model).asMap().get("attribute");
model.addAttribute("redirectionAttribute", some);
model.addAttribute("redirectionAttribute1", some1);
return new ModelAndView("redirection", model);
}
}
redirection.jsp
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>Submitted Information</h2>
<h3></h3>
<table>
<tr>
<td>1. ${redirectionAttribute}</td>
</tr>
<tr>
<td>2. ${redirectionAttribute1}</td>
</tr>
</table>
</body>
</html>
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.5.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.baeldung.redirectattributes</groupId>
<artifactId>spring-redirectattributes</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-redirectattributes</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Can any one help me to continue debugging the application . I get connection refused error
when I hit this endpoint while debugging .
I was debugging the application to check the contents of some1 variable
http://localhost:8081/redirect

There was an unexpected error (type=Not Found, status=404). No message available

I am getting below error:
There was an unexpected error (type=Not Found, status=404). No message available
While using Spring Boot + Thymeleaf
Code:
Application class:
package com.mycom.extract;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
#SpringBootApplication(scanBasePackages = "com.mycom.extract")
public class MyAppExtractionWebApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(MyAppExtractionWebApplication.class, args);
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(MyAppExtractionWebApplication.class);
}
}
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mycom.extract</groupId>
<artifactId>MyApp-extraction</artifactId>
<version>1</version>
<packaging>war</packaging>
<name>MyAppExtractionWeb</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-integration</artifactId>
</dependency>
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.54</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
SecurityConfig
package com.mycom.extract.config.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private MyAppAuthenticationProvider authProvider;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authProvider);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/css/**", "/login").permitAll()
.antMatchers("/*").fullyAuthenticated()
.and()
.formLogin().loginPage("/login")
.loginProcessingUrl("/j_spring_security_check")
.usernameParameter("ipn").passwordParameter("password")
.defaultSuccessUrl("/home").failureUrl("/login?error")
.and()
.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/login");
http.csrf().disable();
}
}
WebMvcConfiguration
package com.mycom.extract.config;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
#EnableAutoConfiguration
#Configuration
#ComponentScan(basePackages = { "com.mycom.extract" })
public class MyAppConfiguration extends WebMvcConfigurerAdapter{
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addRedirectViewController("/", "/login");
registry.addViewController("/login").setViewName("index");
registry.addViewController("/home").setViewName("home");
}
}
Referring all same kind of post in Stackoverflow could find solution for myself.
Please suggest.
URL http://localhost:8080/MyAppExtractionWeb/
As I am setting up login, and authentication is handled at security config side, so once it is successful it shows home page. Hence no controller mentioned.
package com.mycom.config.security;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.login.LoginContext;
import org.springframework.beans.factory.annotation.Autowired;*/
import java.util.Collection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import com.mycom.entity.User;
import com.mycom.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
#Configuration
public class MyAppAuthenticationProvider implements AuthenticationProvider {
private static final String SECURITY_DOMAIN = "MyApp-ldapdomain";
#Autowired
private UserService userService;
#Override
public Authentication authenticate(Authentication authentication) {
String name = authentication.getName();
String password = authentication.getCredentials().toString();
try {
CallbackHandler handler = new UserPasswordHandler(name, password);
LoginContext lc = new LoginContext(SECURITY_DOMAIN, handler);
lc.login();
if(lc.getSubject() != null) {
User user = userService.loadUserByUsername(name);
Collection<? extends GrantedAuthority> roles = null;
if(!user.getAuthorities().isEmpty()) {
roles = user.getAuthorities();
}
return new UsernamePasswordAuthenticationToken(name, password,roles);
} catch (Exception e) {
return null;
}
}
#Override
public boolean supports(Class<?> authentication) {
return authentication.equals(UsernamePasswordAuthenticationToken.class);
}
}

JSF components are not rendered when running Spring Boot app on Eclipse Tomcat

I have Spring Boot JSF application that runs fine on embedded Tomcat
but when trying to run it on Eclipse Tomcat, the jsf components are not getting rendered, here's my pom file:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework</groupId>
<artifactId>gs-accessing-data-jpa</artifactId>
<version>0.1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.4.RELEASE</version>
</parent>
<packaging>war</packaging>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.2.14</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.2.14</version>
</dependency>
<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>6.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<!--
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
-->
</plugins>
</build>
<repositories>
<repository>
<id>spring-releases</id>
<name>Spring Releases</name>
<url>https://repo.spring.io/libs-release</url>
</repository>
<repository>
<id>org.jboss.repository.releases</id>
<name>JBoss Maven Release Repository</name>
<url>https://repository.jboss.org/nexus/content/repositories/releases</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-releases</id>
<name>Spring Releases</name>
<url>https://repo.spring.io/libs-release</url>
</pluginRepository>
</pluginRepositories>
</project>
The main class:
package hello;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import javax.faces.application.ProjectStage;
import javax.servlet.ServletContainerInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.HandlesTypes;
import org.apache.catalina.Context;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.CustomScopeConfigurer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory;
import org.springframework.boot.context.embedded.tomcat.TomcatContextCustomizer;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.boot.web.servlet.ServletContextInitializer;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import com.sun.faces.config.FacesInitializer;
#SpringBootApplication
public class Application extends SpringBootServletInitializer {
private static final Logger log = LoggerFactory.getLogger(Application.class);
public static void main(String[] args) {
SpringApplication.run(Application.class);
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
#Bean
public ServletContextInitializer servletContextCustomizer() {
return new ServletContextInitializer() {
#Override
public void onStartup(ServletContext sc) throws ServletException {
sc.setInitParameter(ProjectStage.PROJECT_STAGE_PARAM_NAME, ProjectStage.Development.name());
}
};
}
#Bean
public static CustomScopeConfigurer customScopeConfigurer() {
CustomScopeConfigurer configurer = new CustomScopeConfigurer();
configurer.setScopes(Collections.<String, Object>singletonMap(FacesViewScope.NAME, new FacesViewScope()));
return configurer;
}
#Bean
public EmbeddedServletContainerFactory embeddedServletContainerFactory() {
TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
tomcat.addContextCustomizers(new TomcatContextCustomizer() {
#Override
public void customize(Context context) {
context.addServletContainerInitializer(new FacesInitializer(),
getServletContainerInitializerHandlesTypes(FacesInitializer.class));
context.addWelcomeFile("index.xhtml");
context.addMimeMapping("eot", "application/vnd.ms-fontobject");
context.addMimeMapping("ttf", "application/x-font-ttf");
context.addMimeMapping("woff", "application/x-font-woff");
}
});
return tomcat;
}
#SuppressWarnings("rawtypes")
private Set<Class<?>> getServletContainerInitializerHandlesTypes(
Class<? extends ServletContainerInitializer> sciClass) {
HandlesTypes annotation = sciClass.getAnnotation(HandlesTypes.class);
if (annotation == null) {
return Collections.emptySet();
}
Class[] classesArray = annotation.value();
Set<Class<?>> classesSet = new HashSet<Class<?>>(classesArray.length);
for (Class clazz : classesArray) {
classesSet.add(clazz);
}
return classesSet;
}
}
Other configuration:
JSF are added to project facets
Maven dependencies are added in deployment assembly
When running the application on server, I don't get any errors in fact I see logs meaning that JSF was started successfully:
2017-01-28 16:04:47.145 INFO 6880 --- [ost-startStop-1] hello.Application : Started Application in 13.522 seconds (JVM running for 19.312)
2017-01-28 16:04:47.231 INFO 6880 --- [ost-startStop-1] j.e.resource.webcontainer.jsf.config : Initializing Mojarra 2.2.14 ( 20161114-2153 unable to get svn info) for context '/spring-hibernate-jsf-web'
2017-01-28 16:04:47.539 INFO 6880 --- [ost-startStop-1] j.e.r.webcontainer.jsf.application : JSF1048: PostConstruct/PreDestroy annotations present. ManagedBeans methods marked with these annotations will have said annotations processed.
2017-01-28 16:04:48.557 INFO 6880 --- [ost-startStop-1] j.e.resource.webcontainer.jsf.config : Monitoring file:/C:/Users/lenovo/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/spring-hibernate-jsf-web/WEB-INF/faces-config.xml for modifications
2017-01-28 16:04:48.630 INFO 6880 --- [ost-startStop-1] .w.PostConstructApplicationEventListener : Running on PrimeFaces 6.0
2017-01-28 16:04:48.790 INFO 6880 --- [ main] org.apache.coyote.ajp.AjpNioProtocol : Starting ProtocolHandler [ajp-nio-8009]
2017-01-28 16:04:48.799 INFO 6880 --- [ main] org.apache.catalina.startup.Catalina : Server startup in 20021 ms
2017-01-28 16:04:49.463 INFO 6880 --- [nio-8080-exec-2] .a.c.c.C.[.[.[/spring-hibernate-jsf-web] : Initializing Spring FrameworkServlet 'dispatcherServlet'
2017-01-28 16:04:49.463 INFO 6880 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started
2017-01-28 16:04:49.511 INFO 6880 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 47 ms
When accessing the xhtml page, there are no errors but the jsf and Primefaces components doesn't get rendered. How can I fix this issue?
I found the issue, it's weird, while running the jar on embeded tomcat i was able to access the xhtml pages without the /faces/ prefix but on eclipse tomcat i have to add /faces/ prefix before the xhtml page in order to work properly.

Spring Boot with JSF2.2 : Error getting customize embedded tomcat

My Spring boot configuration for jsf is:
import java.util.Collections;
import javax.faces.webapp.FacesServlet;
import javax.servlet.DispatcherType;
import javax.servlet.ServletContext;
import org.primefaces.webapp.filter.FileUploadFilter;
import org.springframework.beans.factory.config.CustomScopeConfigurer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.context.embedded.FilterRegistrationBean;
import org.springframework.boot.context.embedded.MimeMappings;
import org.springframework.boot.context.embedded.ServletRegistrationBean;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.web.context.ServletContextAware;
#SpringBootApplication
public class Application extends SpringBootServletInitializer implements ServletContextAware, EmbeddedServletContainerCustomizer {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
#Bean
public ServletRegistrationBean facesServletRegistraiton() {
ServletRegistrationBean registration = new ServletRegistrationBean(new FacesServlet(), new String[] {"*.jsf", "*.xhtml"});
registration.setLoadOnStartup(1);
return registration;
}
#Override
public void setServletContext(ServletContext servletContext) {
servletContext.setInitParameter("com.sun.faces.forceLoadConfiguration", Boolean.TRUE.toString());
}
#Override
public void customize(ConfigurableEmbeddedServletContainer container) {
MimeMappings mappings = new MimeMappings(MimeMappings.DEFAULT);
mappings.add("xsd", "text/xml; charset=utf-8");
mappings.add("eof", "fa/fontawesome-webfont.eot");
mappings.add("woff", "fa/fontawesome-webfont.woff");
mappings.add("ttf", "fa/fontawesome-webfont.ttf");
container.setMimeMappings(mappings);
}
}
And my pom.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.sjf</groupId>
<artifactId>SpringJSF</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.5.RELEASE</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- SPRING BOOT -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- TOMCAT EMBEDDED -->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-logging-juli</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.jdt.core.compiler</groupId>
<artifactId>ecj</artifactId>
<version>4.4</version>
<scope>provided</scope>
</dependency>
<!-- JSF -->
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.faces</artifactId>
<version>2.2.10</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
When we use EmbeddedServletContainerCustomizer interface to set mime mapping we got the error:
2015-07-17 02:38:25.091 ERROR 8984 --- [ main] javax.faces : Unable to obtain InjectionProvider from init time FacesContext. Does this container implement the Mojarra Injection SPI?
2015-07-17 02:38:25.106 ERROR 8984 --- [ main] javax.faces : Application was not properly initialized at startup, could not find Factory: javax.faces.context.FacesContextFactory. Attempting to find backup.
2015-07-17 02:38:25.106 ERROR 8984 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/app] : StandardWrapper.Throwable
java.lang.IllegalStateException: Could not find backup for factory javax.faces.context.FacesContextFactory.
at javax.faces.FactoryFinderInstance.getFactory(FactoryFinderInstance.java:541)
at javax.faces.FactoryFinder.getFactory(FactoryFinder.java:275)
at javax.faces.webapp.FacesServlet.init(FacesServlet.java:350)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1231)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1034)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4914)
at org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedContext.deferredLoadOnStartup(TomcatEmbeddedContext.java:66)
at org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainer.startConnector(TomcatEmbeddedServletContainer.java:209)
at org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainer.start(TomcatEmbeddedServletContainer.java:152)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.startEmbeddedServletContainer(EmbeddedWebApplicationContext.java:288)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.finishRefresh(EmbeddedWebApplicationContext.java:141)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:525)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:667)
at org.springframework.boot.SpringApplication.doRun(SpringApplication.java:342)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:273)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:971)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:960)
at com.genu.SpringSecuredJSF.Application.main(Application.java:29)
Is it anything missing on Facescontext setting? please help.
Use an extra class:
#Configuration
public class ContainerCustomizer implements EmbeddedServletContainerCustomizer, Ordered {
#Override
public int getOrder() {
return 0;
}
#Override
public void customize(ConfigurableEmbeddedServletContainer container) {
...
}
}

Resources