Creating Jar for SpringBoot Application with JSP pages using Gradle - spring-boot

I have an SpringBoot Application which has few JSP pages within it. When I boot the main class from my eclipse it is working perfectly. But at the same time, when I package it as jar, the WEB-INF/jsp folder is not configured properly. I am stuck here. Request your help
Below is my Gradle script
buildscript {
ext {
springBootVersion = '1.5.4.RELEASE'
}
repositories {
maven {
url "https://plugins.gradle.org/m2/"
}
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
group = 'com.arun'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
task packSSO(type: Jar) {
manifest {
attributes(
'Implementation-Title': 'Arun Spring Boot Application',
'Implementation-Version': version,
'Built-By': System.getProperty('user.name'),
'Built-Date': new Date(),
'Main-Class': 'com.arun.MainGate',
'Built-JDK': System.getProperty('java.version')
)
}
sourceSets {
main {
resources {
srcDirs "src/main/resources"
}
}
}
baseName = project.name + '-all'
from {
configurations.compile.collect {
it.isDirectory() ? it : zipTree(it)
}
}
with jar
}
repositories {
maven {
url "https://plugins.gradle.org/m2/"
}
}
dependencies {
compile('org.springframework.boot:spring-boot-starter-web')
compile('org.springframework.boot:spring-boot-starter-tomcat')
compile('org.apache.tomcat.embed:tomcat-embed-jasper')
compile ('javax.servlet:jstl:1.2')
testCompile('org.springframework.boot:spring-boot-starter-test')
testImplementation 'junit:junit:4.12'
}
I exploded the created Jar and the structure looks like below.
so when i run java -jar SSOPage-0.0.1-SNAPSHOT.jar it couldn't find the JSP pages. What exact folder structure should i need to follow and how to package the WEB-INF in gradle ?

I think you must use WAR packaging for a Spring Boot application that uses JSPs. However, you can still use it like a self-contained executable JAR file, as in $ java -jar ./build/libs/hcro-pdi-1.0.0.war.
Here's my build.gradle file from a Spring Boot 2.0.1 project that uses JSPs.
plugins {
id 'org.springframework.boot' version '2.0.1.RELEASE'
id "io.spring.dependency-management" version "1.0.4.RELEASE"
}
apply plugin: 'org.springframework.boot'
apply plugin: 'war'
bootWar {
baseName = 'hcro-pdi'
version = '1.0.0'
}
gradle.projectsEvaluated {
tasks.withType(JavaCompile) {
options.compilerArgs << "-Xlint:unchecked" << "-Xlint:deprecation"
}
}
repositories {
mavenCentral()
}
dependencies {
compile('org.springframework.boot:spring-boot-starter-web')
providedRuntime("org.springframework.boot:spring-boot-starter-tomcat")
compile('org.springframework.boot:spring-boot-starter-jdbc')
compile('javax.servlet:jstl')
compile('org.apache.tomcat.embed:tomcat-embed-jasper')
// Devtools enable hot-reloading of JSP and static content
compile("org.springframework.boot:spring-boot-devtools")
compile(group: 'org.mariadb.jdbc', name: 'mariadb-java-client', version: '2.2.0')
compile(group: 'org.apache.commons', name: 'commons-lang3', version: '3.7')
compile(group: 'org.apache.httpcomponents', name: 'httpclient', version: '4.5.5')
compile(group: 'joda-time', name: 'joda-time')
compile(group: 'com.fasterxml.jackson.datatype', name: 'jackson-datatype-joda')
compileOnly('org.projectlombok:lombok')
testCompile('org.springframework.boot:spring-boot-starter-test')
}
// When running in bootRun task, automatically reload static resources when changed
// https://docs.spring.io/spring-boot/docs/current/reference/html/build-tool-plugins-gradle-plugin.html#build-tool-plugins-gradle-running-applications
bootRun {
jvmArgs "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005"
sourceResources sourceSets.main
}
And, you do have to add the two properties to application.properties shared by #Yogi.
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp

You need to create application.properties under resources folder in your application and define below properties:
spring.mvc.view.prefix: /WEB-INF/jsp/ (your path for JSP files)
spring.mvc.view.suffix: .jsp
Sample MVC examples:
http://www.springboottutorial.com/creating-web-application-with-spring-boot

Related

Spring Boot Gradle application "Error: Could not find or load main class"

I have Spring boot Gradle project that runs perfectly local by Gradle, but not throw the jar file created.
The project has two targets: update data at Postgres DB from another api by scheduling, and let users get the data.
Application class:
I tried to deploy my project on Heroku, Google cloud and via java -jar command, I'm getting the same behavior.
I don't know if it's the problem but on the cloud the build runs successfuly, and after that I get the error: Error: Could not find or load main class com.Application . and ofcourse all the get requests gets denied and server is not accepts any requests.
my build.gradle
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:2.0.5.RELEASE")
}
}
plugins {
id 'java'
id 'idea'
id 'application'
id 'java-library'
id 'java-gradle-plugin'
id "com.heroku.sdk.heroku-gradle" version "2.0.0"
id 'org.springframework.boot' version '2.7.2'
id "io.spring.dependency-management" version "1.0.4.RELEASE"
}
apply plugin: 'java'
apply plugin: 'io.spring.dependency-management'
apply plugin: 'application'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
mainClassName = 'com.Application'
sourceSets.main.java.srcDirs = ['src/main/java']
springBoot{
mainClass = "com.Application"
}
repositories {
mavenCentral()
}
configurations {
all*.exclude module: "spring-boot-starter-logging"
all*.exclude group: "ch.qos.logback"
all*.exclude module: "log4j-over-slf4j" // allow using log4j 2.x
all*.exclude module: "slf4j-simple" // log4j is the configured backend
}
dependencies {
implementation group: 'org.jsoup', name: 'jsoup', version: '1.14.3'
implementation('org.springframework.boot:spring-boot-starter-data-jpa')
implementation('org.apache.maven.plugins:maven-shade-plugin:3.0.0')
implementation('com.google.code.geocoder-java:geocoder-java:0.16')
implementation('org.springframework.boot:spring-boot-starter-web')
implementation 'com.fasterxml.jackson.core:jackson-databind:2.11.0'
runtimeOnly('org.postgresql:postgresql')
implementation ( 'org.projectlombok:lombok:1.18.20')
annotationProcessor ( 'org.projectlombok:lombok:1.18.20')
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.2'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.2'
}
task cleanBuildPublish{
build.mustRunAfter clean
}
group 'com'
version '1.0-SNAPSHOT'
jar {
enabled =false
manifest {
attributes(
'Main-Class': 'com.Application',
)
}
}
bootJar {
manifest {
attributes(
'Main-Class': 'com.Application',
)
}
}
test {
useJUnitPlatform()
}
and my project structure :
the error I get on google cloud:

Gradle Spring Boot: Add folder at root to jar

So I have a folder .ebextensions at the root of my spring boot project,and those files are not being included in my jar when I use "bootpackage" in my gradle plugin for intellij.I am deploying the jar On Amazon Web Services
How do I include these files in my jar?
My build.gradle
buildscript {
ext {
springBootVersion = '1.5.9.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
group = 'haughton.daniel'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
ext {
springCloudVersion = 'Edgware.SR1'
}
dependencies {
//compile 'org.springframework.cloud:spring-cloud-starter-aws'
compile('org.springframework.boot:spring-boot-starter-data-jpa')
// https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-mail
compile group: 'org.springframework.boot', name: 'spring-boot-starter-mail', version: '2.0.0.RELEASE'
compile('org.springframework.boot:spring-boot-starter-jdbc')
compile('org.springframework.boot:spring-boot-starter-security')
compile('org.springframework.boot:spring-boot-starter-thymeleaf')
// https://mvnrepository.com/artifact/org.thymeleaf.extras/thymeleaf-extras-springsecurity4
compile group: 'org.thymeleaf.extras', name: 'thymeleaf-extras-springsecurity4', version: '2.1.2.RELEASE'
// https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-aws-autoconfigure
//compile group: 'org.springframework.cloud', name: 'spring-cloud-aws-autoconfigure', version: '1.2.2.RELEASE'
// https://mvnrepository.com/artifact/mysql/mysql-connector-java
// https://mvnrepository.com/artifact/mysql/mysql-connector-java
compile group: 'mysql', name: 'mysql-connector-java', version: '6.0.6'
compile('org.springframework.boot:spring-boot-starter-web')
compile ('org.apache.tomcat:tomcat-dbcp:8.0.30')
runtime('mysql:mysql-connector-java')
testCompile('org.springframework.boot:spring-boot-starter-test')
testCompile('org.springframework.security:spring-security-test')
}
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
}
}
Solution:
Added this to my build.gradle
processResources {
from ('.ebextensions/') {
into '.ebextensions'
}
}
I added an ebextensions folder into source of my project, this contains the .ebextensions folder with nginx config:
Folder structure
I extended bootJar task:
bootJar {
baseName = 'project'
version = '1.0.0'
from('ebextensions')
//...
When I run ./gradlew cle ass bootJar, then the unzipped project-1.0.0.jar contains:
.ebextensions
BOOT-INF
META-INF
org
I used Gradle 4.10.
The root cause was 413 Request Entity Too Large with ElasticBeanstalk.
Full content of proxy.conf:
client_max_body_size 20M;

Gradle Eclipse Classpath Exception: FAILURE: Build failed with an exception

I am getting the error as attached in the image above whenever I am trying to run gradle eclipse.
I keep on getting this eclipseClassPath exception.
The Gradle Version, I am using is 3.1
Someone suggested me to use gradle version 2.14 because it won't work with the latest version of gradle.
My build.gradle file is below:
buildscript {
ext {
springBootVersion = '1.2.3.RELEASE'
springCloudConnectorsVersion = '1.2.3.RELEASE'
jarName = 'comOrderAudit'
jarVersion = ' -jar build/libs/app-0.0.1-SNAPSHOT.jar'
}
repositories {
mavenCentral()
mavenLocal()
jcenter()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
classpath("io.spring.gradle:dependency-management-plugin:0.5.0.RELEASE")
}
}
repositories {
mavenCentral()
mavenLocal()
jcenter()
}
apply plugin: 'spring-boot'
apply plugin: 'java'
apply plugin: 'application'
apply plugin: 'eclipse'
apply plugin: 'war'
apply plugin: 'jacoco'
dependencies {
compile("org.springframework.boot:spring-boot-starter-actuator") {
exclude module: "spring-boot-starter-logging"
exclude module: "logback-classic"
}
compile "org.springframework.boot:spring-boot-starter-test"
compile("org.springframework.boot:spring-boot-starter-web") {
exclude module: "spring-boot-starter-logging"
exclude module: "logback-classic"
}
compile("org.springframework.boot:spring-boot-starter-aop") {
exclude module: "spring-boot-starter-logging"
exclude module: "logback-classic"
}
"org.springframework.cloud:Spring-cloud-core:${springCloudConnectorsVersion}"
compile "org.springframework.cloud:spring-cloud-spring-service-connector:${springCloudConnectorsVersion}"
compile "org.springframework.cloud:spring-cloud-cloudfoundry-connector:${springCloudConnectorsVersion}"
compile 'org.codehaus.jettison:jettison:1.3.8'
compile 'com.datastax.cassandra:cassandra-driver-core:2.1.8'
compile 'com.google.code.gson:gson:2.3.1'
compile 'org.springframework.boot:spring-boot-starter-log4j2'
compile 'org.springframework:spring-oxm'
compile 'org.simpleframework:simple-xml:2.7.1'
compile 'io.springfox:springfox-swagger2:2.0.0'
compile 'io.springfox:springfox-swagger-ui:2.0.0'
compile 'com.wordnik:swagger-jersey2-jaxrs_2.10:1.3.8'
compile 'com.mangofactory:swagger-springmvc:1.0.2'
compile 'com.datastax.cassandra:cassandra-driver-core:2.1.8'
compile 'com.google.code.gson:gson:2.3.1'
testCompile "junit:junit:4.12"
testCompile "org.springframework.boot:spring-boot-starter-test"
testCompile 'commons-dbcp:commons-dbcp:1.4'
}
task updateVersion{
Properties props = new Properties()
File propsFile = new File("src/main/resources/application.properties")
props.load(propsFile.newDataInputStream())
println(props.getProperty("buildNumber")+"v")
Integer nextbuildnum = (((props.getProperty("buildNumber")) as Integer) + 1)
props.setProperty('buildNumber', nextbuildnum.toString())
def date = new Date()
def formattedDate = date.format('yyyyMMddHHmmss')
props.setProperty("buildTimeStamp", formattedDate)
props.store(propsFile.newWriter(), null)
props.load(propsFile.newDataInputStream())
}
test {
testLogging {
events 'started', 'passed'
}
jacocoTestReport{
group = "Reporting"
description = "Generate Jacoco coverage reports."
additionalSourceDirs = files(sourceSets.main.java)
reports {
xml.enabled = false
html.enabled = true
}
afterEvaluate {
classDirectories = files(classDirectories.files.collect {
fileTree(dir: it,
exclude: ['**/model/**'])
})
}
}
}
I found the answer through extensive search.
Looks like the issue was with Spring boot version used in the gradle.
With Gradle version 3.1, the recommended spring boot version is 1.4.x releases.
If I am to use spring boot version 1.2.3 the gradle version I should be using is 2.14.
just changed the spring boot version and the build was success.
For more answers you can take a look at this page here.

Gradle - Exclude provided scope jars from War file

Gradle seems to claim that it doesnt include the providedCompile and providedRuntime scopes when building the war file.
But, when i do the build with below war config, a folder named "lib-provided" seems to be containing all the provided scoped jars. How do I limit this functionality to NOT include the provided scoped jars.
configure(rootProject) {
apply plugin: 'idea'
apply plugin: 'spring-boot'
apply plugin: 'io.spring.dependency-management'
apply plugin: 'java'
targetCompatibility = 1.8
sourceCompatibility = 1.8
repositories {
mavenCentral()
mavenLocal()
maven { url "https://repository.jboss.org/nexus/content/groups/public-jboss/" }
}
// Import Spring Boot's bom, spring-boot-dependencies
dependencyManagement {
imports {
mavenBom 'org.springframework.boot:spring-boot-dependencies:1.2.5.RELEASE'
}
}
// Override the spring-data-releasetrain.version property
ext['spring-data-releasetrain.version'] = 'Fowler-SR1'
dependencies {
compile("org.springframework.boot:spring-boot-starter-actuator")
compile("org.springframework.boot:spring-boot-starter-security")
............ Other Spring Boot based projects
testCompile("org.springframework.boot:spring-boot-starter-test")
compile("com.fasterxml.jackson.datatype:jackson-datatype-hibernate4:2.4.6")
......... Below are the "Provided" Scoped packages
providedRuntime("org.springframework.boot:spring-boot-starter-tomcat")
providedCompile("org.apache.tomcat.embed:tomcat-embed-jasper:8.0.23")
providedCompile("org.hibernate:hibernate-core:4.3.7.Final")
providedCompile("org.hibernate:hibernate-infinispan:4.3.7.Final")
providedCompile("org.hibernate:hibernate-entitymanager:4.3.7.Final")
providedCompile("org.hibernate:hibernate-validator:5.1.3.Final")
providedCompile("org.hibernate:hibernate-search-orm:5.0.1.Final")
providedCompile("org.hibernate.common:hibernate-commons-annotations:4.0.4.Final")
providedCompile("org.infinispan:infinispan-core:7.1.1.Final")
providedCompile("org.infinispan:infinispan-query:7.1.1.Final")
testCompile("com.microsoft.sqlserver:sqljdbc41:4.1")
}
configurations {
providedCompile
// replaced with jcl-over-slf4j
all*.exclude group: 'commons-logging', module: 'commons-logging'
// replaced with log4j-over-slf4j
all*.exclude group: 'log4j', module: 'log4j'
}
}
war {
baseName = 'abc'
version = '5.0.0-SNAPSHOT-' + + System.currentTimeMillis();
doFirst {
manifest {
attributes("Implementation-Title": project.name, "Implementation-Version": version, "Implementation-Timestamp": new Date())
}
}
webAppDirName = 'web'
includeEmptyDirs false
archiveName 'abc.war'
}
Thanks!
In the below configuration, Gradle 4.6
None of the below depndnecies will be in the War/WEB-INF lib.
If you have an Ear build.gradle can contain entry like below , which will ensure all depndence jar in the Ear/lib folder.
if the below entry is made, The generated Ear file will have .war file and the War/lib folder will not be having the specified dependent files.
apply plugin: 'war'
earlib project(path: ':MyWebProject', configuration: 'compile')
deploy project(path: ':MyWebProject', configuration: 'archives')
apply plugin: 'war'
dependencies {
providedCompile('org.apache.logging.log4j:log4j-web')
providedCompile('org.springframework.boot:spring-boot-starter-web') {
exclude module: "spring-boot-starter-tomcat"
}
}

GORM not bootstrapping from JAR

Replacing a persistence layer in legacy app with a JAR file using Spring, Hibernate and GORM. Methods like person.save() work fine when running agains project with Gradle etc. in project. However, after I build the fat jar and reference it with -cp my-big-fat-gorm.jar I get:
java.lang.IllegalStateException: Method on class [blah.Person] was
used outside of a Grails application. If running in the context of a
test using the mocking API or bootstrap Grails correctly.
Using Spring boot for Spring, Hibernate4 and GORM and build.gradle file show below...
apply plugin: 'java'
apply plugin: 'groovy'
apply plugin: 'application'
mainClassName = "blah.App"
jar {
baseName = 'blah-gorm'
version = '1.0-SNAPSHOT'
from {
configurations.compile.collect {
it.isDirectory() ? it : zipTree(it)
}
configurations.runtime.collect {
it.isDirectory() ? it : zipTree(it)
}
}
}
repositories {
mavenLocal()
mavenCentral()
}
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.8.2'
compile 'org.grails:gorm-hibernate4-spring-boot:1.1.0.RELEASE'
compile 'org.slf4j:slf4j-simple:1.7.7'
runtime 'com.h2database:h2:1.4.181'
}
Am I missing something in the JAR file creation that causes Spring boot to honor #Entity etc.?
Here is a GitHub project that illustrates this and should allow you to execute and see the same stuff I'm seeing.
https://github.com/twcrone/spring-gorm-jar
You don't have the Spring Boot Gradle plugin installed so you're not actually creating a fat JAR you need to add the following to your build.gradle file:
apply plugin: 'spring-boot'
buildscript {
ext {
springBootVersion = '1.1.0.M2'
groovyVersion = '2.3.2'
}
repositories {
mavenCentral()
maven {
url 'http://repo.spring.io/milestone'
}
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
With this in place doing gradle assemble and then java -jar ... results in bootstrapping GORM correctly

Resources