I just started learning spring boot, and created a small spring mvc application. But I'm getting white label error when I try to access view, but application is working fine if i just return the string using responseBody annotation. I have also added thymeleaf to dependency.
Project Structure:
demo2
|-- src/main/java
| |-- example
| | `-- Demo2Application
| |-- controller
| | `-- Controller
| `-- model
| `-- Person
`-- src/main/resources
`-- templates
`-- personView.html
Here is my 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>org.demo</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>demo2</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.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>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</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-thymeleaf</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Application Config Main method:
#Configuration
#EnableAutoConfiguration
#ComponentScan({"com", "example", "controller"})
public class Demo2Application {
public static void main(String[] args) {
SpringApplication.run(Demo2Application.class, args);
}
}
Controller class:
#Controller
public class PersonController {
#RequestMapping("/person")
public String getPerson(Model model) {
Person person = new Person();
person.setFirstname("John");
person.setLastName("Carter");
person.setAge(25);
model.addAttribute(person);
return "personView";
}
#RequestMapping("/test")
public #ResponseBody String test() {
return "hello world";
}
#ResponseBody
#RequestMapping("/")
String entry() {
return "Welcome to Spring Boot Application";
}
}
View Page:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"></meta>
<title>Insert title here</title>
</head>
<body>
FirstName : <span th:text="${person.firstName}"></span>
LastName : <span th:text="${person.lastName}"></span>
Age : <span th:text="${person.age}"></span>
</body>
</html>
Error:
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Sun Sep 04 22:45:31 EDT 2016
There was an unexpected error (type=Not Found, status=404).
No message available
Log:
2016-09-04 22:43:10.330 INFO 11356 --- [ main] com.example.Demo2Application : Starting Demo2Application on Sais-MacBook-Pro.local with PID 11356 (/Users/sainishankbojja/Documents/workspace-sts-3.8.1.RELEASE/demo2/target/classes started by sainishankbojja in /Users/sainishankbojja/Documents/workspace-sts-3.8.1.RELEASE/demo2)
2016-09-04 22:43:10.334 INFO 11356 --- [ main] com.example.Demo2Application : No active profile set, falling back to default profiles: default
2016-09-04 22:43:10.370 INFO 11356 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#a9cd3b1: startup date [Sun Sep 04 22:43:10 EDT 2016]; root of context hierarchy
2016-09-04 22:43:11.353 INFO 11356 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2016-09-04 22:43:11.365 INFO 11356 --- [ main] o.apache.catalina.core.StandardService : Starting service Tomcat
2016-09-04 22:43:11.366 INFO 11356 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.4
2016-09-04 22:43:11.430 INFO 11356 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2016-09-04 22:43:11.430 INFO 11356 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1063 ms
2016-09-04 22:43:11.558 INFO 11356 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2016-09-04 22:43:11.561 INFO 11356 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2016-09-04 22:43:11.562 INFO 11356 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2016-09-04 22:43:11.562 INFO 11356 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2016-09-04 22:43:11.562 INFO 11356 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2016-09-04 22:43:11.786 INFO 11356 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for #ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#a9cd3b1: startup date [Sun Sep 04 22:43:10 EDT 2016]; root of context hierarchy
2016-09-04 22:43:11.834 INFO 11356 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/test]}" onto public java.lang.String controller.PersonController.test()
2016-09-04 22:43:11.835 INFO 11356 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/]}" onto java.lang.String controller.PersonController.entry()
2016-09-04 22:43:11.835 INFO 11356 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/person]}" onto public java.lang.String controller.PersonController.getPerson(org.springframework.ui.Model)
2016-09-04 22:43:11.837 INFO 11356 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2016-09-04 22:43:11.837 INFO 11356 --- [ 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.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2016-09-04 22:43:11.860 INFO 11356 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-09-04 22:43:11.860 INFO 11356 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-09-04 22:43:11.885 INFO 11356 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-09-04 22:43:11.990 INFO 11356 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2016-09-04 22:43:12.035 INFO 11356 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2016-09-04 22:43:12.038 INFO 11356 --- [ main] com.example.Demo2Application : Started Demo2Application in 12.204 seconds (JVM running for 12.492)
2016-09-04 22:43:15.931 INFO 11356 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring FrameworkServlet 'dispatcherServlet'
2016-09-04 22:43:15.931 INFO 11356 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started
2016-09-04 22:43:15.941 INFO 11356 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 10 ms
Related
I'm using Spring Boot with Kotlin . The rest controller returns 404 error for all endpoints. In the starting logs the endpoints in the controller are not present. Any endpoint returns the same 404 response.
These are the steps I have tried,
Tried clearing cache/target
Moved all classes into single directory
Tried adding ComponentScan annotation but it is not accepted.
I'm using cmd line to run the project
Same output seen when running java -jar $jarfile
Checked annotations Repository , Service , RestController
Controller:
package com.example.controller
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.http.HttpStatus
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.PutMapping
import org.springframework.web.bind.annotation.DeleteMapping
import org.springframework.web.bind.annotation.RequestBody
import Cricketer
import CricketerRepository
import CricketerService
import org.springframework.web.bind.annotation.RequestMapping
#RestController
#RequestMapping("/api")
class CricketerController(private val cricketerService: CricketerService , private val cricketerRepository: CricketerRepository){
#GetMapping("/cricketers/{id}")
fun getCricketer(#PathVariable("id") id: Long):ResponseEntity<Cricketer> {
val cricketer = cricketerService.findById(id)
return ResponseEntity<Cricketer>(cricketer as Cricketer, HttpStatus.OK);
}
#GetMapping("/cricketers/")
fun getAllCricketers() :ResponseEntity<List<Cricketer>> {
var cricketersList: ArrayList<Cricketer> = cricketerService.getAllPlayers() as (ArrayList<Cricketer>)
return ResponseEntity<List<Cricketer>>(cricketersList, HttpStatus.OK)
}
#PostMapping("/cricketer/")
fun addCricketer(#RequestBody cricketer:Cricketer):ResponseEntity<Cricketer> {
val cCricketer : Cricketer = Cricketer(name = cricketer.name
, country = cricketer.country
, highestScore = cricketer.highestScore)
cricketerRepository.save(cCricketer)
return ResponseEntity<Cricketer>(cricketer , HttpStatus.OK)
}
#PutMapping("/cricketer/{id}")
fun updateCricketer(#PathVariable("id") id: Long, #RequestBody cricketer: Cricketer ):ResponseEntity<Cricketer> {
val cCricketer = Cricketer(name = cricketer.name
, country = cricketer.country
, highestScore = cricketer.highestScore)
cricketerRepository.save(cCricketer)
return ResponseEntity<Cricketer>(cricketer, HttpStatus.OK)
}
#DeleteMapping("/cricketer/{id}")
fun deleteCricketer(#PathVariable("id") id:Long ):ResponseEntity<String> {
val cCricketer :Cricketer = cricketerService.findById(id) as Cricketer
cricketerRepository.delete(cCricketer)
return ResponseEntity<String>("cricketer removed", HttpStatus.OK)
}
}
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.example</groupId>
<artifactId>Spring-Kotlin-Rest-API</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>Spring-Kotlin-Rest-API</name>
<description>Spring Boot Kotlin REST API Example</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.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>
<kotlin.version>1.2.41</kotlin.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-web</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-kotlin</artifactId>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib-jdk8</artifactId>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-reflect</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>
</dependencies>
<build>
<sourceDirectory>${project.basedir}/src/main/kotlin</sourceDirectory>
<testSourceDirectory>${project.basedir}/src/test/kotlin</testSourceDirectory>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<artifactId>kotlin-maven-plugin</artifactId>
<groupId>org.jetbrains.kotlin</groupId>
<configuration>
<args>
<arg>-Xjsr305=strict</arg>
</args>
<compilerPlugins>
<plugin>spring</plugin>
</compilerPlugins>
<jvmTarget>1.8</jvmTarget>
</configuration>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-allopen</artifactId>
<version>${kotlin.version}</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</project>
Startup logs
2018-05-21 22:31:19.490 INFO 3061 --- [ main] c.e.d.SpringKotlinRestApiApplicationKt : Starting SpringKotlinRestApiApplicationKt on nirmal-desktop with PID 3061 (/home/nirmal/code/workspace-sts-3.9.1.RELEASE/Spring-Kotlin-Rest-API/target/classes started by root in /home/nirmal/code/workspace-sts-3.9.1.RELEASE/Spring-Kotlin-Rest-API)
2018-05-21 22:31:19.512 INFO 3061 --- [ main] c.e.d.SpringKotlinRestApiApplicationKt : No active profile set, falling back to default profiles: default
2018-05-21 22:31:19.592 INFO 3061 --- [ main] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext#5bab7c16: startup date [Mon May 21 22:31:19 IST 2018]; root of context hierarchy
2018-05-21 22:31:29.492 INFO 3061 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$28d3b505] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2018-05-21 22:31:33.847 INFO 3061 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2018-05-21 22:31:34.312 INFO 3061 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2018-05-21 22:31:34.313 INFO 3061 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.31
2018-05-21 22:31:34.389 INFO 3061 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [/usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib]
2018-05-21 22:31:36.190 INFO 3061 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2018-05-21 22:31:36.190 INFO 3061 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 16602 ms
2018-05-21 22:31:36.560 INFO 3061 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Servlet dispatcherServlet mapped to [/]
2018-05-21 22:31:36.564 INFO 3061 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-05-21 22:31:36.566 INFO 3061 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-05-21 22:31:36.566 INFO 3061 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-05-21 22:31:36.566 INFO 3061 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2018-05-21 22:31:37.743 INFO 3061 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2018-05-21 22:31:39.038 INFO 3061 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2018-05-21 22:31:39.222 INFO 3061 --- [ main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2018-05-21 22:31:39.480 INFO 3061 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2018-05-21 22:31:40.064 INFO 3061 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.2.17.Final}
2018-05-21 22:31:40.066 INFO 3061 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2018-05-21 22:31:40.302 INFO 3061 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2018-05-21 22:31:42.180 INFO 3061 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5InnoDBDialect
2018-05-21 22:31:44.235 INFO 3061 --- [ main] o.h.t.schema.internal.SchemaCreatorImpl : HHH000476: Executing import script 'org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl#7d95eb4a'
2018-05-21 22:31:44.237 INFO 3061 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2018-05-21 22:31:44.688 INFO 3061 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-05-21 22:31:46.829 INFO 3061 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for #ControllerAdvice: org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext#5bab7c16: startup date [Mon May 21 22:31:19 IST 2018]; root of context hierarchy
2018-05-21 22:31:46.894 WARN 3061 --- [ main] aWebConfiguration$JpaWebMvcConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2018-05-21 22:31:47.072 INFO 3061 --- [ 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-05-21 22:31:47.073 INFO 3061 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2018-05-21 22:31:47.121 INFO 3061 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-05-21 22:31:47.122 INFO 3061 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-05-21 22:31:49.030 INFO 3061 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2018-05-21 22:31:49.033 INFO 3061 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Bean with name 'dataSource' has been autodetected for JMX exposure
2018-05-21 22:31:49.047 INFO 3061 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Located MBean 'dataSource': registering with JMX server as MBean [com.zaxxer.hikari:name=dataSource,type=HikariDataSource]
2018-05-21 22:31:50.682 INFO 3061 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2018-05-21 22:31:50.695 INFO 3061 --- [ main] c.e.d.SpringKotlinRestApiApplicationKt : Started SpringKotlinRestApiApplicationKt in 34.697 seconds (JVM running for 49.043)
I guess your CricketerController is not in a subpackage relative to your main class. So you basically have two options:
Place your main class directly under the package com.example
Add the annotation at the bottom of this answer to your main class.
Using any of these two methods makes the controller class visible for Spring at startup and therefore should create your mappings.
#ComponentScan(basePackages = { "com.example.controller"} )
Have had to cut the first error message quite abit since it contained to many characters, but the full thing can be found here: https://github.com/kableiv/FullSpringError
Bit of backstory:
Completing an assignment and need to create a small website where 2 predefined users can login, one with user privileges and one with admin, the privileges are buttons that redirect you to pages where you edit, delete and register new info. At first I did it without spring security and no database, using arraylists and files. When I logged in with the user it only had the user privileges like it was supposed to, however when I logged in with the admin and then went onto any of the other html pages like the one used to edit something and then clicked on the return button, the admin privileges were gone. Im assuming this was because i, in my method to login, sat its admin value to true(so the html page knew what to display and what not to) and then when that method was done and a new one was starting like the editing method the value was back to null.
Because of this I decided to try and switch to using a MySQL database with spring security.
My IDE of choice is intellij ultimate and I used MySQL Workbench to setup the database and added it into intellij using the database feature.
Now when trying to run the project i get the following error:
2018-05-04 16:59:10.780 INFO 8364 --- [ main] com.rfboernehave.demo.DemoApplication : Starting DemoApplication on DESKTOP-QB8IIQF with PID 8364 (C:\Users\nerdi\SpringbootWebAppMiniproject1\target\classes started by nerdi in C:\Users\nerdi\SpringbootWebAppMiniproject1)
2018-05-04 16:59:10.783 INFO 8364 --- [ main] com.rfboernehave.demo.DemoApplication : No active profile set, falling back to default profiles: default
2018-05-04 16:59:11.390 INFO 8364 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#516be40f: startup date [Fri May 04 16:59:11 CEST 2018]; root of context hierarchy
2018-05-04 16:59:14.723 INFO 8364 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 5000 (http)
2018-05-04 16:59:14.747 INFO 8364 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2018-05-04 16:59:14.747 INFO 8364 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.16
2018-05-04 16:59:15.021 INFO 8364 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2018-05-04 16:59:15.021 INFO 8364 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 3638 ms
2018-05-04 16:59:15.343 INFO 8364 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-05-04 16:59:15.343 INFO 8364 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-05-04 16:59:15.343 INFO 8364 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-05-04 16:59:15.343 INFO 8364 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2018-05-04 16:59:15.343 INFO 8364 --- [ost-startStop-1] .s.DelegatingFilterProxyRegistrationBean : Mapping filter: 'springSecurityFilterChain' to: [/*]
2018-05-04 16:59:15.347 INFO 8364 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2018-05-04 16:59:18.235 ERROR 8364 --- [ main] o.a.tomcat.jdbc.pool.ConnectionPool : Unable to create initial connections of pool.
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
at com.mysql.jdbc.Util.handleNewInstance(Util.java:425) ~[mysql-connector-java-5.1.43.jar:5.1.43]
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:989) ~[mysql-connector-java-5.1.43.jar:5.1.43]
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:341) ~[mysql-connector-java-5.1.43.jar:5.1.43]
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2196) ~[mysql-connector-java-5.1.43.jar:5.1.43]
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2229) ~[mysql-connector-java-5.1.43.jar:5.1.43]
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2024) ~[mysql-connector-java-5.1.43.jar:5.1.43]
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:779) ~[mysql-connector-java-5.1.43.jar:5.1.43]
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47) ~[mysql-connector-java-5.1.43.jar:5.1.43]
at com.mysql.jdbc.Util.handleNewInstance(Util.java:425) ~[mysql-connector-java-5.1.43.jar:5.1.43]
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:389) ~[mysql-connector-java-5.1.43.jar:5.1.43]
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:330) ~[mysql-connector-java-5.1.43.jar:5.1.43]
at org.apache.tomcat.jdbc.pool.PooledConnection.connectUsingDriver(PooledConnection.java:310) ~[tomcat-jdbc-8.5.16.jar:na]
at org.apache.tomcat.jdbc.pool.PooledConnection.connect(PooledConnection.java:203) ~[tomcat-jdbc-8.5.16.jar:na]
at org.apache.tomcat.jdbc.pool.ConnectionPool.createConnection(ConnectionPool.java:735) [tomcat-jdbc-8.5.16.jar:na]
at org.apache.tomcat.jdbc.pool.ConnectionPool.borrowConnection(ConnectionPool.java:667) [tomcat-jdbc-8.5.16.jar:na]
at org.apache.tomcat.jdbc.pool.ConnectionPool.init(ConnectionPool.java:482) [tomcat-jdbc-8.5.16.jar:na]
at org.apache.tomcat.jdbc.pool.ConnectionPool.<init>(ConnectionPool.java:154) [tomcat-jdbc-8.5.16.jar:na]
at org.apache.tomcat.jdbc.pool.DataSourceProxy.pCreatePool(DataSourceProxy.java:118) [tomcat-jdbc-8.5.16.jar:na]
at org.apache.tomcat.jdbc.pool.DataSourceProxy.createPool(DataSourceProxy.java:107) [tomcat-jdbc-8.5.16.jar:na]
at org.apache.tomcat.jdbc.pool.DataSourceProxy.getConnection(DataSourceProxy.java:131) [tomcat-jdbc-8.5.16.jar:na]
at org.springframework.jdbc.datasource.DataSourceUtils.doGetConnection(DataSourceUtils.java:111) [spring-jdbc-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:77) [spring-jdbc-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.jdbc.support.JdbcUtils.extractDatabaseMetaData(JdbcUtils.java:326) [spring-jdbc-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.jdbc.support.JdbcUtils.extractDatabaseMetaData(JdbcUtils.java:366) [spring-jdbc-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.boot.autoconfigure.orm.jpa.DatabaseLookup.getDatabase(DatabaseLookup.java:72) [spring-boot-autoconfigure-1.5.6.RELEASE.jar:1.5.6.RELEASE]
at org.springframework.boot.autoconfigure.orm.jpa.JpaProperties.determineDatabase(JpaProperties.java:139) [spring-boot-autoconfigure-1.5.6.RELEASE.jar:1.5.6.RELEASE]
at org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration.jpaVendorAdapter(JpaBaseConfiguration.java:105) [spring-boot-autoconfigure-1.5.6.RELEASE.jar:1.5.6.RELEASE]
at org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration$$EnhancerBySpringCGLIB$$e4aac97b.CGLIB$jpaVendorAdapter$5(<generated>) [spring-boot-autoconfigure-1.5.6.RELEASE.jar:1.5.6.RELEASE]
at org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration$$EnhancerBySpringCGLIB$$e4aac97b$$FastClassBySpringCGLIB$$6844864e.invoke(<generated>) [spring-boot-autoconfigure-1.5.6.RELEASE.jar:1.5.6.RELEASE]
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228) [spring-core-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:358) [spring-context-4.3.10.RELEASE.jar:4.3.10.RELEASE]
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1078) ~[spring-context-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:857) ~[spring-context-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543) ~[spring-context-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693) [spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360) [spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) [spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118) [spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107) [spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE]
at com.rfboernehave.demo.DemoApplication.main(DemoApplication.java:10) [classes/:na]
Caused by: org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60) ~[spring-orm-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:353) ~[spring-orm-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:370) ~[spring-orm-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:359) ~[spring-orm-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE]
Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
NOW I have tried adding hibernating dependencies:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.1.4.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.2.3.Final</version>
</dependency>
Which gave me this other error instead:
:: Spring Boot :: (v1.5.6.RELEASE)
2018-05-04 16:36:20.358 INFO 19272 --- [ main] com.rfboernehave.demo.DemoApplication : Starting DemoApplication on DESKTOP-QB8IIQF with PID 19272 (C:\Users\nerdi\SpringbootWebAppMiniproject1\target\classes started by nerdi in C:\Users\nerdi\SpringbootWebAppMiniproject1)
2018-05-04 16:36:20.358 INFO 19272 --- [ main] com.rfboernehave.demo.DemoApplication : No active profile set, falling back to default profiles: default
2018-05-04 16:36:21.064 INFO 19272 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#77be656f: startup date [Fri May 04 16:36:21 CEST 2018]; root of context hierarchy
2018-05-04 16:36:23.488 INFO 19272 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 5000 (http)
2018-05-04 16:36:23.501 INFO 19272 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2018-05-04 16:36:23.501 INFO 19272 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.16
2018-05-04 16:36:23.722 INFO 19272 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2018-05-04 16:36:23.722 INFO 19272 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 2658 ms
2018-05-04 16:36:23.935 INFO 19272 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-05-04 16:36:23.935 INFO 19272 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-05-04 16:36:23.935 INFO 19272 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-05-04 16:36:23.935 INFO 19272 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2018-05-04 16:36:23.938 INFO 19272 --- [ost-startStop-1] .s.DelegatingFilterProxyRegistrationBean : Mapping filter: 'springSecurityFilterChain' to: [/*]
2018-05-04 16:36:23.939 INFO 19272 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2018-05-04 16:36:24.010 WARN 19272 --- [ main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'homeController' defined in file [C:\Users\nerdi\SpringbootWebAppMiniproject1\target\classes\com\rfboernehave\demo\controller\HomeController.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'brugerServiceImpl' defined in file [C:\Users\nerdi\SpringbootWebAppMiniproject1\target\classes\com\rfboernehave\demo\services\BrugerServiceImpl.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'brugerRepository': Cannot create inner bean '(inner bean)#703feacd' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#703feacd': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available
2018-05-04 16:36:24.012 INFO 19272 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2018-05-04 16:36:24.036 INFO 19272 --- [ main] utoConfigurationReportLoggingInitializer :
Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2018-05-04 16:36:24.114 ERROR 19272 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of constructor in com.rfboernehave.demo.services.BrugerServiceImpl required a bean named 'entityManagerFactory' that could not be found.
Action:
Consider defining a bean named 'entityManagerFactory' in your configuration.
NOW I also got rid of this thing(not sure if did it correctly though) but it gave me a similair error but asking me to define a bean of type package. I decided to remove the dependencies and are therefore currently sitting with the first error of the post.
Below is my current 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.rfboernhave</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.6.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>
<org.springframework.security.version>3.2.3.RELEASE</org.springframework.security.version>
<org.springframework.version>4.0.4.RELEASE</org.springframework.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<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.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>3.3.7</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.fasterxml</groupId>
<artifactId>oss-parent</artifactId>
<version>27</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
<version>2.0.1.RELEASE</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
My application.properties:
server.port=5000
spring.datasource.url=jdbc:mysql://localhost:5000/test_db
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
My Config.java class:
package com.rfboernehave.demo.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 javax.sql.DataSource;
#Configuration
#EnableWebSecurity
public class Config extends WebSecurityConfigurerAdapter {
#Autowired
DataSource dataSource;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception{
auth.jdbcAuthentication().dataSource(dataSource)
.usersByUsernameQuery("select username, password from user where username=?")
.authoritiesByUsernameQuery("select username, rolle from user where username=?");
}
#Override
protected void configure(HttpSecurity http) throws Exception{
http
.authorizeRequests()
.antMatchers("/login*").anonymous()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/home")
.and()
.logout().logoutSuccessUrl("/login");
}
}
My entity(MyUser) class : I apologize for the variables being in a foreign language quick translation:
MinBruger is (MyUser)
brugernavn is (username)
adgangskode is (password)
rolle is (role)
package com.rfboernehave.demo.domains;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class MinBruger {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private String brugernavn;
private String adgangskode;
private String rolle;
private int id;
public MinBruger() {
}
public MinBruger(int id, String brugernavn, String adgangskode, String rolle) {
this.id = id;
this.brugernavn = brugernavn;
this.adgangskode = adgangskode;
this.rolle = rolle;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getBrugernavn() {
return brugernavn;
}
public void setBrugernavn(String brugernavn) {
this.brugernavn = brugernavn;
}
public String getAdgangskode() {
return adgangskode;
}
public void setAdgangskode(String adgangskode) {
this.adgangskode = adgangskode;
}
public String getRolle(){return rolle;}
public void setRolle(String rolle) {
this.rolle = rolle;
}
#Override
public String toString() {
return "MinBruger{" +
"id=" + id +
", brugernavn='" + brugernavn + '\'' +
", adgangskode='" + adgangskode + '\'' +
", rolle=" + rolle + '\'' +
'}';
}
Below is my UserRepository:
Translation:
BrugerRepository is (UserRepository)
package com.rfboernehave.demo.repositories;
import com.rfboernehave.demo.domains.MinBruger;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface BrugerRepository extends CrudRepository<MinBruger, String> {
}
How can I fix this?
Thx in Advance.
UPDATE: Ok so I sat the property:
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
Aside from that I also changed the following:
spring.datasource.url=jdbc:mysql://localhost:3306/
TO:
spring.datasource.url=jdbc:mysql://localhost:3306/test_db?useSSL=false
This seemed to do part of the trick, my project now runs, however a new problem arisen, when trying to login it fails and sets the url from: http://localhost:5000/login
TO: http://localhost:5000/login?error
Below is my HomeController.java:
package com.rfboernehave.demo.controller;
import com.rfboernehave.demo.domains.Barn;
import com.rfboernehave.demo.domains.MinBruger;
import com.rfboernehave.demo.services.BarnServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.io.FileNotFoundException;
import java.util.ArrayList;
#Controller
public class HomeController {
private final Logger log = LoggerFactory.getLogger(this.getClass());
#Autowired
private BarnServiceImpl barnService;
public HomeController() {
}
#RequestMapping(value = {"", "/", "index"}, method = RequestMethod.GET)
public String index() {
log.info("index method called...");
return "login";
}
#RequestMapping(value = "/login", method = RequestMethod.GET)
public String login() {
log.info("login method called with: ");
if (SecurityContextHolder.getContext().getAuthentication().getAuthorities().contains(new SimpleGrantedAuthority("admin"))) {
return "redirect:/home";
}
return "login";
}
//
//
#RequestMapping(value = "/home", method = RequestMethod.GET)
public String home(Model model) {
log.info("home action called...");
model.addAttribute("boern", barnService.hentAlleBoern());
log.info("home action ended...");
return "home";
}
#GetMapping("/registrer")
public String registrer(Model model) {
log.info("registrer action called...");
model.addAttribute("barn", new Barn());
return "registrer";
}
#PostMapping("/registrer")
public String registrer(#ModelAttribute Barn barn, Model model) throws FileNotFoundException {
log.info("registrer post action called...");
String home = Integer.toString(barnService.hentAlleBoern().size());
barn.setId(Integer.parseInt(home));
barnService.hentAlleBoern().add(barn);
barnService.printToFile();
model.addAttribute("boern", barnService.hentAlleBoern());
return "/home";
}
#GetMapping("/detaljer/{id}")
public String detaljer(#PathVariable("id") int id, Model model) {
log.info("detaljer action called...");
Barn lille = null;
for (Barn barn : barnService.hentAlleBoern()) {
if (barn.getId() == id) {
lille = barn;
break;
}
}
model.addAttribute("barn", lille);
model.addAttribute("boern", barnService.hentAlleBoern());
return "detaljer";
}
#GetMapping("/afmeld/{id}")
public String afmeld(#PathVariable("id") int id, Model model) {
log.info("afmeld action called...");
model.addAttribute("barn",barnService.hentAlleBoern().get(id));
model.addAttribute("boern", barnService.hentAlleBoern());
return "afmeld";
}
#PostMapping("/afmeld")
public String afmeld(#ModelAttribute Barn barn, Model model) throws FileNotFoundException {
log.info("afmeld post action called...");
int id = barn.getId();
barnService.hentAlleBoern().remove(barn.getId());
leftShiftId(barnService.hentAlleBoern(), id);
barnService.printToFile();
model.addAttribute("boern", barnService.hentAlleBoern());
return "/home";
}
#GetMapping("/rediger/{id}")
public String rediger(#PathVariable("id") int id, Model model) {
log.info("rediger action called...");
model.addAttribute("barn", barnService.hentAlleBoern().get(id));
model.addAttribute("boern", barnService.hentAlleBoern());
return "rediger";
}
#PostMapping("/rediger")
public String rediger(#ModelAttribute Barn barn, Model model) throws FileNotFoundException {
log.info("rediger post action called...");
for (int i = 0; i < barnService.hentAlleBoern().size(); i++) {
if (barn.getId() == barnService.hentAlleBoern().get(i).getId()) {
barnService.hentAlleBoern().set(i, barn);
break;
}
}
barnService.printToFile();
model.addAttribute("boern", barnService.hentAlleBoern());
return "/home";
}
private void leftShiftId(ArrayList<Barn> list, int id) {
log.info("leftshift method called...");
for (int i = id; i < list.size(); i++) {
Barn barn = list.get(i);
barn.setId(barn.getId() - 1);
}
}
}
Below is the terminal output:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.5.6.RELEASE)
2018-05-08 13:18:32.979 INFO 1872 --- [ main] com.rfboernehave.demo.DemoApplication : Starting DemoApplication on DESKTOP-QB8IIQF with PID 1872 (C:\Users\nerdi\SpringbootWebAppMiniproject1\target\classes started by nerdi in C:\Users\nerdi\SpringbootWebAppMiniproject1)
2018-05-08 13:18:32.982 INFO 1872 --- [ main] com.rfboernehave.demo.DemoApplication : No active profile set, falling back to default profiles: default
2018-05-08 13:18:33.671 INFO 1872 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#516be40f: startup date [Tue May 08 13:18:33 CEST 2018]; root of context hierarchy
2018-05-08 13:18:36.652 INFO 1872 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 5000 (http)
2018-05-08 13:18:36.666 INFO 1872 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2018-05-08 13:18:36.667 INFO 1872 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.16
2018-05-08 13:18:36.878 INFO 1872 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2018-05-08 13:18:36.878 INFO 1872 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 3210 ms
2018-05-08 13:18:37.170 INFO 1872 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-05-08 13:18:37.170 INFO 1872 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-05-08 13:18:37.170 INFO 1872 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-05-08 13:18:37.170 INFO 1872 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2018-05-08 13:18:37.172 INFO 1872 --- [ost-startStop-1] .s.DelegatingFilterProxyRegistrationBean : Mapping filter: 'springSecurityFilterChain' to: [/*]
2018-05-08 13:18:37.172 INFO 1872 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2018-05-08 13:18:37.907 INFO 1872 --- [ main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2018-05-08 13:18:37.929 INFO 1872 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2018-05-08 13:18:38.204 INFO 1872 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.0.12.Final}
2018-05-08 13:18:38.205 INFO 1872 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2018-05-08 13:18:38.207 INFO 1872 --- [ main] org.hibernate.cfg.Environment : HHH000021: Bytecode provider name : javassist
2018-05-08 13:18:38.256 INFO 1872 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2018-05-08 13:18:38.425 INFO 1872 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2018-05-08 13:18:39.001 INFO 1872 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2018-05-08 13:18:39.571 INFO 1872 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: org.springframework.security.web.util.matcher.AnyRequestMatcher#1, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter#11b5f4e2, org.springframework.security.web.context.SecurityContextPersistenceFilter#33e0c716, org.springframework.security.web.header.HeaderWriterFilter#634ca3e7, org.springframework.security.web.csrf.CsrfFilter#6ee88e21, org.springframework.security.web.authentication.logout.LogoutFilter#d653e41, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#17222c11, org.springframework.security.web.savedrequest.RequestCacheAwareFilter#6274f21c, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter#12952aff, org.springframework.security.web.authentication.AnonymousAuthenticationFilter#6bcae9, org.springframework.security.web.session.SessionManagementFilter#b14b60a, org.springframework.security.web.access.ExceptionTranslationFilter#50b734c4, org.springframework.security.web.access.intercept.FilterSecurityInterceptor#67688110]
2018-05-08 13:18:40.196 INFO 1872 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for #ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#516be40f: startup date [Tue May 08 13:18:33 CEST 2018]; root of context hierarchy
2018-05-08 13:18:40.337 INFO 1872 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[ || / || /index],methods=[GET]}" onto public java.lang.String com.rfboernehave.demo.controller.HomeController.index()
2018-05-08 13:18:40.338 INFO 1872 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/home],methods=[GET]}" onto public java.lang.String com.rfboernehave.demo.controller.HomeController.home(org.springframework.ui.Model)
2018-05-08 13:18:40.339 INFO 1872 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/rediger],methods=[POST]}" onto public java.lang.String com.rfboernehave.demo.controller.HomeController.rediger(com.rfboernehave.demo.domains.Barn,org.springframework.ui.Model) throws java.io.FileNotFoundException
2018-05-08 13:18:40.339 INFO 1872 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/rediger/{id}],methods=[GET]}" onto public java.lang.String com.rfboernehave.demo.controller.HomeController.rediger(int,org.springframework.ui.Model)
2018-05-08 13:18:40.340 INFO 1872 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/detaljer/{id}],methods=[GET]}" onto public java.lang.String com.rfboernehave.demo.controller.HomeController.detaljer(int,org.springframework.ui.Model)
2018-05-08 13:18:40.341 INFO 1872 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/login],methods=[GET]}" onto public java.lang.String com.rfboernehave.demo.controller.HomeController.login()
2018-05-08 13:18:40.342 INFO 1872 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/registrer],methods=[POST]}" onto public java.lang.String com.rfboernehave.demo.controller.HomeController.registrer(com.rfboernehave.demo.domains.Barn,org.springframework.ui.Model) throws java.io.FileNotFoundException
2018-05-08 13:18:40.342 INFO 1872 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/registrer],methods=[GET]}" onto public java.lang.String com.rfboernehave.demo.controller.HomeController.registrer(org.springframework.ui.Model)
2018-05-08 13:18:40.343 INFO 1872 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/afmeld],methods=[POST]}" onto public java.lang.String com.rfboernehave.demo.controller.HomeController.afmeld(com.rfboernehave.demo.domains.Barn,org.springframework.ui.Model) throws java.io.FileNotFoundException
2018-05-08 13:18:40.344 INFO 1872 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/afmeld/{id}],methods=[GET]}" onto public java.lang.String com.rfboernehave.demo.controller.HomeController.afmeld(int,org.springframework.ui.Model)
2018-05-08 13:18:40.347 INFO 1872 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2018-05-08 13:18:40.348 INFO 1872 --- [ 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.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-05-08 13:18:40.398 INFO 1872 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-05-08 13:18:40.400 INFO 1872 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-05-08 13:18:40.477 INFO 1872 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-05-08 13:18:41.111 INFO 1872 --- [ main] b.a.s.AuthenticationManagerConfiguration :
Using default security password: 4f2b3afb-8328-4fa1-a16c-e16003f15618
2018-05-08 13:18:41.294 INFO 1872 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2018-05-08 13:18:41.396 INFO 1872 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 5000 (http)
2018-05-08 13:18:41.403 INFO 1872 --- [ main] com.rfboernehave.demo.DemoApplication : Started DemoApplication in 8.91 seconds (JVM running for 9.612)
I have initialed spring boot project using start.spring.io and added WEB,JPA,H2 dependencies.
Pom file
<?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.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.10.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-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>com.h2database</groupId>
<artifactId>h2</artifactId>
<!-- <scope>runtime</scope> -->
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
application.properties
spring.h2.console.enabled=true
security.basic.enabled=false
DemoApplication.java
#SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
UserController.java
#RestController
public class UserController {
#GetMapping("/hello")
public String hello() {
return "Hello";
}
Console Log
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.5.10.RELEASE)
2018-02-26 11:24:28.846 INFO 4792 --- [ main] com.example.demo.DemoApplication : Starting DemoApplication on RAJAT-PC with PID 4792 (C:\Users\devra\Downloads\Compressed\demo\target\classes started by rajat in C:\Users\devra\Downloads\Compressed\demo)
2018-02-26 11:24:28.855 INFO 4792 --- [ main] com.example.demo.DemoApplication : No active profile set, falling back to default profiles: default
2018-02-26 11:24:29.018 INFO 4792 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#6b67034: startup date [Mon Feb 26 11:24:29 IST 2018]; root of context hierarchy
2018-02-26 11:24:30.894 INFO 4792 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$fa7e8c5a] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2018-02-26 11:24:31.720 INFO 4792 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2018-02-26 11:24:31.737 INFO 4792 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2018-02-26 11:24:31.740 INFO 4792 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.27
2018-02-26 11:24:31.969 INFO 4792 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2018-02-26 11:24:31.970 INFO 4792 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 2957 ms
2018-02-26 11:24:32.307 INFO 4792 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-02-26 11:24:32.308 INFO 4792 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-02-26 11:24:32.309 INFO 4792 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-02-26 11:24:32.309 INFO 4792 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2018-02-26 11:24:32.310 INFO 4792 --- [ost-startStop-1] .s.DelegatingFilterProxyRegistrationBean : Mapping filter: 'springSecurityFilterChain' to: [/*]
2018-02-26 11:24:32.311 INFO 4792 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2018-02-26 11:24:32.313 INFO 4792 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'webServlet' to [/h2-console/*]
2018-02-26 11:24:33.004 INFO 4792 --- [ main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2018-02-26 11:24:33.038 INFO 4792 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2018-02-26 11:24:33.196 INFO 4792 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.0.12.Final}
2018-02-26 11:24:33.199 INFO 4792 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2018-02-26 11:24:33.202 INFO 4792 --- [ main] org.hibernate.cfg.Environment : HHH000021: Bytecode provider name : javassist
2018-02-26 11:24:33.266 INFO 4792 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2018-02-26 11:24:33.517 INFO 4792 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2018-02-26 11:24:33.807 INFO 4792 --- [ main] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000227: Running hbm2ddl schema export
2018-02-26 11:24:33.816 INFO 4792 --- [ main] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000230: Schema export complete
2018-02-26 11:24:33.859 INFO 4792 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2018-02-26 11:24:34.365 INFO 4792 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for #ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#6b67034: startup date [Mon Feb 26 11:24:29 IST 2018]; root of context hierarchy
2018-02-26 11:24:34.506 INFO 4792 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2018-02-26 11:24:34.508 INFO 4792 --- [ 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.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-02-26 11:24:34.568 INFO 4792 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-02-26 11:24:34.569 INFO 4792 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-02-26 11:24:34.663 INFO 4792 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-02-26 11:24:35.147 INFO 4792 --- [ main] b.a.s.AuthenticationManagerConfiguration :
Using default security password: dd5212d7-4de1-4fee-9f6b-f5cd888f2f17
2018-02-26 11:24:35.222 INFO 4792 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: OrRequestMatcher [requestMatchers=[Ant [pattern='/css/**'], Ant [pattern='/js/**'], Ant [pattern='/images/**'], Ant [pattern='/webjars/**'], Ant [pattern='/**/favicon.ico'], Ant [pattern='/error']]], []
2018-02-26 11:24:35.334 INFO 4792 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: org.springframework.boot.autoconfigure.security.SpringBootWebSecurityConfiguration$ApplicationNoWebSecurityConfigurerAdapter$1#11c713b7, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter#2251b3bc, org.springframework.security.web.context.SecurityContextPersistenceFilter#602f8f94, org.springframework.security.web.header.HeaderWriterFilter#2785db06, org.springframework.security.web.csrf.CsrfFilter#603cabc4, org.springframework.security.web.authentication.logout.LogoutFilter#7a9ceddf, org.springframework.security.web.savedrequest.RequestCacheAwareFilter#4dfe8b37, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter#7e64c1a9, org.springframework.security.web.authentication.AnonymousAuthenticationFilter#3fbe503c, org.springframework.security.web.session.SessionManagementFilter#715a70e9, org.springframework.security.web.access.ExceptionTranslationFilter#1cc8416a]
2018-02-26 11:24:35.552 INFO 4792 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2018-02-26 11:24:35.652 INFO 4792 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2018-02-26 11:24:35.670 INFO 4792 --- [ main] com.example.demo.DemoApplication : Started DemoApplication in 7.302 seconds (JVM running for 7.824)
as you can see spring didn't mapped the /hello url
Considering that the other answers don't explain why it doesn't work as expected, here's why.
Spring uses component scanning to find eligible beans (#Repository, #Service, #Component, #Controller, ...). This is usually done by using the #ComponentScan annotation.
This is explained in the core docs:
To autodetect these classes and register the corresponding beans, you need to add #ComponentScan to your #Configuration class, where the basePackages attribute is a common parent package for the two classes. (Alternatively, you can specify a comma/semicolon/space-separated list that includes the parent package of each class.)
Spring Boot, by default only scans components within the same package (and including subpackages) of the main class. This is because the #SpringBootApplication annotation includes a #ComponentScanby default, as mentioned in the Spring boot docs:
The #SpringBootApplication annotation is equivalent to using #Configuration, #EnableAutoConfiguration and #ComponentScan with their default attributes
If you want Spring to automatically detect your controller, you have three options:
Move the controller to the com.example.demo package. This is the recommended approach according to the Spring boot documentation.
Telling Spring to look at the controller package by adding a #ComponentScan annotation:
#SpringBootApplication
#ComponentScan({"com.example.demo", "controller"}) // Add this
public class DemoApplication {
// ...
}
Telling Spring to look at the controller package by configuring the scanBasePackages property of #SpringBootApplication:
#SpringBootApplication(scanBasePackages = {"com.example.demo", "controller"}) // Add this
public class DemoApplication {
// ...
}
Spring reference doc says - Generally recommend that you locate your main application class in a root package above other classes like
com
+- example
+- myproject
+- Application.java
|
+- domain
| +- Customer.java
| +- CustomerRepository.java
|
+- service
| +- CustomerService.java
|
+- web
+- CustomerController.java
For more refer this link :
https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-structuring-your-code.html
I'm trying to build a very simple Spring MVC application using Spring Boot. By now all my attempts have failed. Here is the configration:
WebConfig:
#SpringBootApplication
#ComponentScan("newTestProject")
public class WebConfig extends WebMvcConfigurerAdapter {
public static void main(String[] args) throws Exception {
SpringApplication.run(WebConfig.class, args);
}
#Bean
public ViewResolver jspViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
resolver.setExposeContextBeansAsAttributes(true);
return resolver;
}
}
WebAppInitializer:
#Configuration
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[]{};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[]{WebConfig.class};
}
}
Controller:
#Controller
public class IndexController {
#RequestMapping(value = "/")
public String index() {
return "index";
}
}
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>groupId</groupId>
<artifactId>messagesAppHiber</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
</parent>
<packaging>war</packaging>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>
There are no error messages in the console:
2017-03-15 21:25:49.631 INFO 1192 --- [ main] newTestProject.config.WebConfig : Starting WebConfig on Rafale-2-ПК with PID 1192 (D:\TEMP\untitled\target\classes started by Rafale-2 in D:\TEMP\untitled)
2017-03-15 21:25:49.633 INFO 1192 --- [ main] newTestProject.config.WebConfig : No active profile set, falling back to default profiles: default
2017-03-15 21:25:49.702 INFO 1192 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#1188e820: startup date [Wed Mar 15 21:25:49 EET 2017]; root of context hierarchy
2017-03-15 21:25:51.122 INFO 1192 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2017-03-15 21:25:51.136 INFO 1192 --- [ main] o.apache.catalina.core.StandardService : Starting service Tomcat
2017-03-15 21:25:51.137 INFO 1192 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.11
2017-03-15 21:25:51.248 INFO 1192 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2017-03-15 21:25:51.249 INFO 1192 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1549 ms
2017-03-15 21:25:51.393 INFO 1192 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2017-03-15 21:25:51.399 INFO 1192 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-03-15 21:25:51.399 INFO 1192 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-03-15 21:25:51.399 INFO 1192 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-03-15 21:25:51.399 INFO 1192 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2017-03-15 21:25:51.661 INFO 1192 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for #ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#1188e820: startup date [Wed Mar 15 21:25:49 EET 2017]; root of context hierarchy
2017-03-15 21:25:51.714 INFO 1192 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/]}" onto public java.lang.String newTestProject.controllers.IndexController.index()
2017-03-15 21:25:51.717 INFO 1192 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2017-03-15 21:25:51.717 INFO 1192 --- [ 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.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2017-03-15 21:25:51.741 INFO 1192 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-03-15 21:25:51.741 INFO 1192 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-03-15 21:25:51.769 INFO 1192 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-03-15 21:25:51.941 INFO 1192 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2017-03-15 21:25:51.989 INFO 1192 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2017-03-15 21:25:51.992 INFO 1192 --- [ main] newTestProject.config.WebConfig : Started WebConfig in 2.634 seconds (JVM running for 2.935)
2017-03-15 21:25:57.507 INFO 1192 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring FrameworkServlet 'dispatcherServlet'
2017-03-15 21:25:57.507 INFO 1192 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started
2017-03-15 21:25:57.519 INFO 1192 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 12 ms
The result should be index.jsp shown in my browser, but instead I get Whitelabel Error Page. What's wrong with this configuration?
1) Remove WebAppInitializer class - it is not needed since spring boot automatically configures it.
2) Remove web.xml. I don't know what you have there but it is not needed since you're using annotation configuration.
3) Enable the default servlet by overriding configureDefaultServletHandling in WebConfig.
#Override
public void configureDefaultServletHandling(
DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
4) Add the following maven dependencies:
<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>
5) Run the project using maven
$ mvn clean spring-boot:run
PS: I don't know what you have in your jsp file. But this approach will work for sure if you use plain html. If you're using some jstl stuff there you have to add jstl dependency as well
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
I'm currently working on this spring-boot application. The application was deployed on a tomcat server using eclipse, I can only access the content of index.html and when I try navigate from index.html to folder_A's index.html, it will throw the whitelabel error page.
In browser console, there is an error stating that folder_A was not found when navigating to folder_A's index.html.
The current structure of my project is:
Project
+-- src
| +--main
| | +--java (Contains source code)
| | +--resources
| | | +--application.properties
| | +--webapp
| | | +--folder_A
| | | | +--index.html
| | | +--WEB_INF
| | | | +--web.xml
| | | +--index.html
````
The web.xml contains all the servlet mapping from the previous project and the application.properties is currently empty.
Why is it happening? Is there any settings I need to configure?
EDIT
Added in the pom.xml
<groupId>com.sampleproject</groupId>
<artifactId>TestProject</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>SpringProject</name>
<description>SpringProject</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.1.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>
<tomcat.version>7.0.75</tomcat.version>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-juli</artifactId>
<version>${tomcat.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</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-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
2017-03-02 08:57:55.467 INFO 8400 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 2016 ms
2017-03-02 08:57:55.701 INFO 8400 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2017-03-02 08:57:55.713 INFO 8400 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-03-02 08:57:55.713 INFO 8400 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-03-02 08:57:55.713 INFO 8400 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-03-02 08:57:55.713 INFO 8400 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2017-03-02 08:57:56.135 INFO 8400 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for #ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#3901d134: startup date [Thu Mar 02 08:57:53 SGT 2017]; root of context hierarchy
2017-03-02 08:57:56.228 INFO 8400 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2017-03-02 08:57:56.228 INFO 8400 --- [ 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.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2017-03-02 08:57:56.275 INFO 8400 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-03-02 08:57:56.275 INFO 8400 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-03-02 08:57:56.353 INFO 8400 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-03-02 08:57:56.385 INFO 8400 --- [ main] oConfiguration$WelcomePageHandlerMapping : Adding welcome page: ServletContext resource [/index.html]
2017-03-02 08:57:56.572 INFO 8400 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2017-03-02 08:57:56.697 INFO 8400 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2017-03-02 08:57:56.853 INFO 8400 --- [ main] c.s.SpringProjectApplication : Started SpringProjectApplication in 3.883 seconds (JVM running for 4.904)
2017-03-02 08:57:59.355 INFO 8400 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/ProjectName] : Initializing Spring FrameworkServlet 'dispatcherServlet'
2017-03-02 08:57:59.355 INFO 8400 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started
2017-03-02 08:57:59.368 INFO 8400 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 13 ms
If you are using SpringBoot, then you do not need web.xml, and place static files to src/main/resources/static instead of src/main/webapp.
Use the mvn spring-boot:run command to start it, do not need to deploy to Tomcat.
This is a sample.