Simple Spring Web App isn't working in Tomcat - java

I'm currently learning Spring MVC and making a simple Hello World web application with it. However, I have no idea why its not working (The WebApplicationInitializer doesn't get invoked).
Here's the 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>springmvctest</artifactId>
<version>1.0</version>
<packaging>war</packaging>
<name>springmvctest Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>18</maven.compiler.source>
<maven.compiler.target>18</maven.compiler.target>
<java.version>18</java.version>
<lombok.version>1.18.24</lombok.version>
<log4jdbc.log4j2.version>1.16</log4jdbc.log4j2.version>
<rest.assured.version>2.3.3</rest.assured.version>
<start-class>java.WebInit</start-class>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.4</version>
</parent>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>5.0.1.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.12</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.bgee.log4jdbc-log4j2</groupId>
<artifactId>log4jdbc-log4j2-jdbc4.1</artifactId>
<version>${log4jdbc.log4j2.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jayway.restassured</groupId>
<artifactId>rest-assured</artifactId>
<version>${rest.assured.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>springmvctest</finalName>
<sourceDirectory> src/main/ </sourceDirectory>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>springloaded</artifactId>
<version>${spring-loaded.version}</version>
</dependency>
</dependencies>
</plugin>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>18</source>
<target>18</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
Here's the WebApplicationInitializer implementation:
package java;
import javax.servlet.ServletContext;
import javax.servlet.ServletRegistration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class WebInit implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext servletContext) {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.register(WebConfig.class);
context.setServletContext(servletContext);
System.out.println("hi");
// Create and register the DispatcherServlet
DispatcherServlet servlet = new DispatcherServlet(context);
ServletRegistration.Dynamic registration = servletContext.addServlet("app", servlet);
registration.setLoadOnStartup(1);
registration.addMapping("/");
}
}
Here's the WebConfig:
package java;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
#Configuration
#EnableWebMvc
#ComponentScan("java")
public class WebConfig {
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
And finally here's the Controller implementation:
package java;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
#RequestMapping("/")
public class TestController {
#RequestMapping(value = "/test", method = RequestMethod.GET)
public String testMethod (Model model) {
model.addAttribute("greeting", "Hello World 2");
return "welcome";
}
}
I have used clean install and run the .war on the Tomcat server
I tried entering 'http://localhost:8080/springmvctest/test' but it gave me a 404 error on the web, and no error in the output.
There are also no mentions of Spring in the output whatsoever, so I assume that Tomcat doesn't detect Spring ?
I'm using Tomcat 10.0.27 and VSCode as the text editor.

Using the Spring Boot framework will be written as follows
Spring Boot 3
Project Structure
├── pom.xml
└── src
└── main
├── java
│   └── com
│   └── example
│   └── springmvctest
│   ├── DemoSpringbootJspApplication.java
│   └── TestController.java
├── resources
│   └── application.properties
└── webapp
├── index.jsp
└── WEB-INF
└── views
└── welcome.jsp
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.0.1</version>
<!--<version>2.7.6</version>-->
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>springmvctest</artifactId>
<packaging>war</packaging>
<version>1.0</version>
<name>springmvctest</name>
<description>springmvctest</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
DemoSpringbootJspApplication.java
package com.example.springmvctest;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
#SpringBootApplication
public class DemoSpringbootJspApplication extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(DemoSpringbootJspApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(DemoSpringbootJspApplication.class, args);
}
}
TestController.java
package com.example.springmvctest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import java.util.Map;
#Controller
#RequestMapping("/")
public class TestController {
#RequestMapping(value = "/test", method = RequestMethod.GET)
public String testMethod (Model model) {
model.addAttribute("greeting", "Hello World 2");
return "welcome";
}
}
application.properties
spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp
welcome.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Welcome</title>
</head>
<%
// debug
System.out.println("webapp / WEB-INF / views / welcome.jsp ");
%>
<body>
<h1 class="color-red">Wecome! ${greeting} </h1>
</body>
</html>
Package
mvn clean package
Deploy and start
Put traget/springmvctest.war to apache-tomcat-10.1.4/webapps/
Startup tomcat
Test
Run Command
curl http://localhost:8080/springmvctest/test
Result
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Welcome</title>
</head>
<body>
<h1 class="color-red">Wecome! Hello World 2 </h1>
</body>
</html>

Spring 2 / Spring 5 will not work on Tomcat 10, because Tomcat 10 is working with jakarta packages that are not present in Spring 2 / Spring 5, they are using javax packages. Either downgrade to Tomcat 9 or upgrade to Spring 3 / Spring 6 if you want to use Tomcat 10.

Related

How to fix 404 Error when deploying SpringBoot App to AWS Elastic Beanstalk?

I'm trying to deploy a very basic Spring Boot web app to AWS Elastic Beanstalk, It works fine locally, but each time I try to run it on elastic beanstalk I get a 404 error.
Here is my Controller:
package com.example.springhelloworld;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class HelloWorldController {
#RequestMapping("/")
public String returnHello(){
return "helloworld";
}
}
Here is my main class:
package com.example.springhelloworld;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
#SpringBootApplication
public class SpringHelloWorldApplication extends SpringBootServletInitializer{
public static void main(String[] args) {
SpringApplication.run(SpringHelloWorldApplication.class, args);
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(SpringHelloWorldApplication.class);
}
}
Here is my html template:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Spring App</title>
</head>
<body>
<h3>Welcome to Spring Hello World!</h3>
</body>
</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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.0.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>SpringHelloWorld</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>SpringHelloWorld</name>
<description>SpringHelloWorld</description>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<version>3.0.2</version>
</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.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>
</project>
This is my project structure:
I also set server port to 5000 in application.properties file.
I generated the war file using maven and uploaded to Elastic Beantalk using a Tomcat 8.5 platform with Corretto 11. However when I try to access my application I get a 404 error. I'm trying to figure out why this is happening.

Thymeleaf: org.thymeleaf.exceptions.TemplateInputException

i am trying to use thymeleaf with spring mvc java based configuration.Then use JPA to connect to H2DB.
When I boot spring boot and connect to "http: // localhost: 8080 /", I get the following error.
I can't get to "index.html".
template "index": An error happened during template parsing (template: "class path resource [templates/index.html]")
org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "class path resource [templates/index.html]")
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'Book' available as request attribute
Controller Class
package com.example.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import com.example.demo.model.Book;
import com.example.demo.repository.Repository;
import lombok.RequiredArgsConstructor;
#RequiredArgsConstructor
#Controller
public class BookController{
private final Repository repository;
#GetMapping("/")
public String index(Model model) {
return "index";
}
#PostMapping("/add")
public String addBook(#ModelAttribute Book book) {
repository.save(book);
return "redirect:/";
}
}
model class
package com.example.demo.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import lombok.Getter;
import lombok.Setter;
#Getter
#Setter
#Entity
public class Book {
#Id
#GeneratedValue
private Long id;
private String title;
private String detail;
}
□repository interface
package com.example.demo.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.example.demo.model.Book;
public interface Repository extends JpaRepository <Book, Long>{
}
index.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>H2DB</title>
</head>
<body>
<form th:action="#{/add}" th:object="${Book}" method="post">
<label for="title">title:</label> <input type="text" th:field="*{itle}">
<label for="detail">detail:</label> <input type="text"
th:field="*{detail}">
<button>登録する</button>
</form>
</body>
</html>
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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>H2DB</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>H2DB</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</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-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</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>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
I use Eclipse Version: 2021-09 (4.21.0)
Try to pass an empty book object in the index method by the Model. I think then you can fill it with data.

Unable to configure a simple Controller in Spring boot project

All i am trying to do is print a simple Hello world message , using a JSP page but when i try to do it,i get a 404 not found error as shown below
this is my project structure, shown in the above diagram
package com.example.MailSender;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication(scanBasePackages = {"com.example.MailSender","com.example.MailSender.Controller"})
public class MailSenderApplication {
public static void main(String[] args) {
SpringApplication.run(MailSenderApplication.class, args);
}
}
the main application class is as shown above
package com.example.MailSender.Controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
#RequestMapping("/hello")
public class SimpleController {
#GetMapping("/world")
public String sample()
{
return "sample";
}
}
A very simple controller that i coded is shown above
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Hello world</title>
</head>
<body>
<h1>Basic config successful!!!</h1>
<h2>Hello World</h2>
</body>
</html>
A very simple JSP page to show the message
server.port=9090
spring.mvc.view.prefix=/src/main/resources/static
spring.mvc.view.suffix=.jsp
this is the application.properties 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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>MailSender</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>MailSender</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
the pom.xml file
i am unable to understand where i am going wrong, please help me out, why am i getting a 404 error ??
i belive http://localhost:9090/hello/world is a valid url
I see two issues.
You need to add this dependency to your pom file
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
/src/main/resources/static is meant to hold static files such as html and css
Create directory src/webapp/WEB-INF/jsp
Move your jsp into the above directory
Update prefix spring.mvc.view.prefix=/WEB-INF/jsp/
https://hellokoding.com/spring-boot-hello-world-example-with-jsp/
Put samples.jsp in "resources/templates"
You muste enable the mvc configuration. Create a class config :
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
#EnableWebMvc
#Configuration
public class Config {
}
https://www.logicbig.com/tutorials/spring-framework/spring-web-mvc/spring-enablewebmvc-annotation.html

Repeatedly getting WhiteLabel error page w/ Mapping specification

I'm new to Spring. I am currently following a tutorial to the T and ran into the "Whitelabel error page". I've done my research, checking Spring boot - Whitelabel Error Page and Spring Boot Remove Whitelabel Error Page with no luck.
I am trying to reach the page by simply using : http://localhost:8080/hello
Obviously Spring cannot find the page, but I cannot figure out why that is.
My html file:
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Thymeleaf demo</title>
</head>
<body>
<p th:text="'time on the server is: ' + ${theDate}" />
</body>
</html>
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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.cat.otsGrief</groupId>
<artifactId>GriefReconcile</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>GriefReconcile</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Java class:
package com.cat.ots.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
#Controller
public class DemoController {
#GetMapping("/hello")
public String sayHello(Model theModel) {
theModel.addAttribute("theDate", new java.util.Date());
return "helloworld";
}
}
File Structure:
Any help is appreciated
EDIT:
answer I was looking is found here - Issue With Spring: There was an unexpected error (type=Not Found, status=404)
Add component scanning for packages that are not in the same package, or in sub-packages, of the main class.
you have to configure viewResolver and internalResourceView Resolvers to serve jsp/html files find the below code snippet go through the link
package com.howtodoinjava.app.controller;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
#Configuration
#EnableWebMvc
#ComponentScan
public class MvcConfiguration extends WebMvcConfigurerAdapter
{
#Override
public void configureViewResolvers(ViewResolverRegistry registry) {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/view/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
registry.viewResolver(resolver);
}
}

Spring with maven, jar packaging, not displaying welcome.jsp page

Hi I am using Spring boot with maven jar packaging. My project structure looks like this
I am starting my project from command promt with this command:
mvn package && java -jar target/ProjekatNekretnine-0.0.1.jar, and it starts perfect. Than I go to http://127.0.0.1:8080/api/users/home and I do not get my welcome.jsp page. My controller class looks like this:
UserController class:
package com.projekat.nekretnine.controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.projekat.nekretnine.Model.Korisnik;
#RestController
#RequestMapping(value="api/users")
public class UserController {
#RequestMapping(value = "/home")
public String welcome(Model model) {
return "welcome";
}
}
I think that my welcome method should return my welcome.jsp file, but instead it writes "welcome" to the page. Why is that so? What am I doing wrong?
My welcome.jsp file looks like this:
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Getting Started: Serving Web Content</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>This is working.</h1>
</body>
</html>
So you see that it shouldn't write welcome.
Here is my pom.xml for you to take a look:
<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.projekat.nekretnine</groupId>
<artifactId>ProjekatNekretnine</artifactId>
<version>0.0.1</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.2.RELEASE</version>
</parent>
<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-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<!-- <version>5.1.30</version> -->
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
One more thing, when I created maven project, I selected that the packaging should be JAR, not WAR. I don't know if I need now web.xml or other xml files, I think not. Maybe the mistake is where I put my static files, if that's the problem, can you tell me where to put tham?
And I tried to use #Controller, instead of #RestController in my UserController class, and still the same problem.
Thank you in advance.
The behaviour your are experiencing is normal.
This happens because you instructed your controller( specifically your rest-controller ) to return a String object when it hits /api/users/home endpoint.
If you however want to expose a page(view) in this endpoint you should configure your spring-boot to use a InternalResourceViewResolver.
You could take a look at a similar question Configure ViewResolver with Spring Boot and annotations gives No mapping found for HTTP request with URI error. and apply the changes for your controller to return the welcome page.

Categories

Resources