Why doesn't it show the 'greetings' template? - java

I'm starting to develop in 'Spring-boot' and I did the 'getting started' as it is and it doesn't show me what it should
so are the routes
this is the console
here is the code of application.properties
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html # ;charset=<encoding> is added
spring.thymeleaf.cache=false
template 'greeting'
<!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>
<p th:text="'Hello, ' + ${name} + '!'" />
</body>
</html>
This is the controller code.
package com.arbaAppWebC.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
#Controller
public class GreetingController {
#GetMapping("/greeting")
public String greeting(#RequestParam(name="name", required=false, defaultValue="World") String name, Model model) {
model.addAttribute("name", name);
return "greeting";
}
}
package com.ArbaAppWeb.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
And this is the dependencies
<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>
</dependency>
</dependencies>
this appears on the web
I am using java 17 as a compiler although I have java 19 installed even so I do not understand what is wrong because I followed the same steps indicated in the spring-boot doc.
I have the same problem since yesterday.
If you need any other information I am at your disposal to give it and be able to obtain the desired solution.

Related

Spring boot controller not returning the jsp page

EDIT : Below is the LatherupApplication Application class:
package latherup.com.latherup;
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(scanBasePackages = "latherup.com")
public class LatherupApplication extends SpringBootServletInitializer{
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(LatherupApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(LatherupApplication.class, args);
}
}
Below is my home controller :
package latherup.com.latherup;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
#RequestMapping("/home")
public class HomeController {
#GetMapping("/home")
public String navigateToHomePage() {
return "home.jsp";
}
}
Below is the pom.xml 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.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>latherup.com</groupId>
<artifactId>latherup</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>latherup</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.release>13</maven.compiler.release>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-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>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>5.0.0</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap-datepicker</artifactId>
<version>1.0.1</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.6.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<scope>provided</scope>
</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-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-jasper -->
</dependencies>
<build>
<!--plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins-->
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
Below is the home.jsp :
<html>
<head>
<title>Welcome</title>
<link href="webjars/bootstrap/3.3.6/css/bootstrap.min.css"
rel="stylesheet">
</head>
<body>
<div class="container">
<table class="table table-striped">
<caption>Your todos are</caption>
<thead>
<tr>
<th>Description</th>
<th>Target Date</th>
<th>Is it Done?</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<tr>
<td>Todo 1</td>
<td>10/12/2017</td>
<td>No</td>
<td><a class="btn btn-warning" href="/edit-todo">Edit Todo</a></td>
<td><a class="btn btn-warning" href="/delete-todo">Delete Todo</a></td>
</tr>
</tbody>
</table>
<div>
<a class="btn btn-default" href="/add-todo">Add a Todo</a>
</div>
<script src="webjars/jquery/1.9.1/jquery.min.js"></script>
<script src="webjars/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</div>
</body>
</html>
The controller is returning String "home.jsp" instead of the page. I have added all the dependencies but not sure what is the problem. Is the problem with the versions of dependencies? If Yes, how can I decide on how to choose the versions that are compatible with each other. I keep facing this problem. Sometimes it works and sometimes it doesn't. Please guide me on this as I am a beginner.
EDIT :
Below is the image of project structure :
Application.properties :
spring.mvc.view.prefix=/LATHER-UP/jsp/
spring.mvc.view.suffix=.jsp
logging.level.org.springframework.web=INFO
You have defined spring.mvc.view.suffix = .jsp
So your controller should return home not home.jsp
#Controller
#RequestMapping("/home")
public class HomeController {
#GetMapping("/home")
public String navigateToHomePage() {
return "home";
}
}
You are using RestController for returning the JSP. Use Controller annotations for working on view part.
Read more about it here Controllers
I think you deploy in a web container, to do this you should use SpringBootServletInitializer in your main class, This binds your application's Servlet, Filter, and ServletContextInitializer to the runtime server, which is necessary for our application to run:
#SpringBootApplication(scanBasePackages = "com.baeldung.boot.jsp")
public class SpringBootJspApplication extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(SpringBootJspApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(SpringBootJspApplication.class);
}
}
And you should not use #RestController in the controller for jsp view, It should be #Controller, like this:
#Controller
#RequestMapping("/book")
public class BookController {
private final BookService bookService;
public BookController(BookService bookService) {
this.bookService = bookService;
}
#GetMapping("/viewBooks")
public String viewBooks(Model model) {
model.addAttribute("books", bookService.getBooks());
return "view-books";
}
}
Please see this spring boot with jsp section here
try this out
#RestController
public class HomeController {
#RequestMapping("/home")
public ModelAndView navigateToHomePage() {
ModelAndView mv = new ModelAndView("home.jsp");
return mv;
}
}
and while using this remove the suffix and prefix from application.properties

Thymeleaf not able to display the value of Model object attribute

I am newbie to Spring boot and Thymeleaf. I have created a mock setup for learning Thymeleaf with Spring boot.
Here I am not able to see the value of the Model attribute in the index.html page.
I am unable to read the value of the Model attribute in html page.
Below is my code I written until now.
HelloWorldSpringBoot.java
package com.test.app;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class HelloWorldSpringBoot {
public static void main(String[] args) {
SpringApplication.run(HelloWorldSpringBoot.class, args);
}
}
HelloWorldController
package com.test.app.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class HelloWorldController {
#RequestMapping(value="/index")
public String hello(Model model){
model.addAttribute("test","value1");
return "index";
}
}
index.html
<!DOCTYPE HTML>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
</head>
<body>
<h1 th:text="${test}"></h1>
</body>
</html>
application.properties
spring.thymeleaf.template-loader-path: classpath:/static/
spring.thymeleaf.suffix: .html
spring.thymeleaf.cache: false
Maven pm.xml
<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.test.app</groupId>
<artifactId>HelloWorldSpringBoot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<java.version>1.8</java.version>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.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-thymeleaf</artifactId>
</dependency>
</dependencies>
</project>
Could any one help me in displaying the value in index.html page.

Need help setting up a simple Spring Boot jsp app with Maven in IntelliJ IDEA

I'm having trouble setting up a very simple spring boot app. I have tried multiple tutorials, Spring MVC, but none will open my jsp.
I'm currently able to setup a project with Initializr, and I understand the concept of #RequestMapping. I'm able to run my Tomcat server with Spring Boot, but when I open my http://localhost:8080/home/ I get the default error page with 404 error.
Thanks for your help.
My project structure:
https://imgur.com/pPhngNS
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.shaddox</groupId>
<artifactId>spring-boot-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>spring-boot-demo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.7.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>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
HelloController.java:
package springbootdemo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class HelloController {
#RequestMapping("/")
public String showPage () {
return "home";
}
}
SpringBootDemoApplication.java:
package springbootdemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
#SpringBootApplication
public class SpringBootDemoApplication extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(SpringBootDemoApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(SpringBootDemoApplication.class, args);
}
}
application.properties:
spring.mvc.view.prefix=/WEB-INF/
spring.mvc.view.suffix=.jsp
home.jsp:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello</title>
</head>
<body>
<h2> Welcome to Spring Boot from JSP!</h2>
</body>
</html>
First change your pom file like this :
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
Then add configuration class :
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 WebConfig extends WebMvcConfigurerAdapter {
#Override
public void configureViewResolvers(ViewResolverRegistry registry) {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
registry.viewResolver(resolver);
}
}

Whitelabel Error Page There was an unexpected error (type=Not Found, status=404). /WEB-INF/views/home.jsp

I am following Spring in Action (part 2) and trying to create the Spittr application as the book shows.
(with Spring Tool Suite 7.3.7. and Maven.)
The problem is that I am getting the following error:
Whitelabel Error Page.
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Thu Apr 07 16:21:23 CEST 2016
There was an unexpected error (type=Not Found, status=404). /WEB-INF/views/home.jsp
The package structure is:
As you see I tried to place the /WEB-INF/views/home.jsp in several places in, case there was a problem with the path.
DispatcherServlet Configuration Class:
package com.spittr.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class SpittrWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer
{
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] { RootConfig.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] { WebConfig.class };
}
}
WebConfig.java class:
package com.spittr.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ErrorAttributes;
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.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
#Configuration
#EnableWebMvc
#ComponentScan("com.spitter.web")
public class WebConfig extends WebMvcConfigurerAdapter
{
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
resolver.setExposeContextBeansAsAttributes(true);
return resolver;
}
#Override
public void configureDefaultServletHandling(
DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
RootConfig.java class:
package com.spittr.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
#Configuration
#ComponentScan(basePackages={"spitter"},
excludeFilters={
#Filter(type=FilterType.ANNOTATION, value=EnableWebMvc.class)})
public class RootConfig {
}
The #Controller class.
package com.spittr.web;
import static org.springframework.web.bind.annotation.RequestMethod.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
public class HomeController
{
#RequestMapping(value="/", method=GET)
public String home()
{
return "home";
}
}
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</groupId>
<artifactId>spittr</artifactId>
<version>1.2.0</version>
<packaging>jar</packaging>
<name>Spittr</name>
<description>Test 1</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.7</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.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
home.jsp:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# page session="false" %>
<html>
<head>
<title>Spittr</title>
<link rel="stylesheet"
type="text/css"
href="<c:url value="/resources/style.css" />" >
</head>
<body>
<h1>Welcome to Spittr</h1>
Spittles |
Register
</body>
</html>
Basically is the same that you can find in the book.
I simply don't know what else to do.
Thanks.
The Problem is with your Project Structure, the WEB-INF should be under src/main/webapp and Not src/main.
That is, as per your ViewResolver your JSP file should be under src/main/webapp/WEB-INF/views/home.jsp.
More info on Maven Standard Directory Layout.
Here is a Spring Boot Sample App.
PS: If you are planning to deploy this app in Tomcat then you'll face this Issue, the above sample app resolves this issue.
Also you need to make sure to add appropriate dependencies, by adding the eclipse compiler for JDT to pick the jsp file placed in src/main/WEB-INF/*/, and tomcat starter also.
As you already know you need to declare the jsp files location in the application.properties
<dependency>
<groupId>org.eclipse.jdt.core.compiler</groupId>
<artifactId>ecj</artifactId>
<version>4.6.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>

SpringMVC with annotated controllers: requested resource is not available

I am working on a Spring 4.0.1 mvc application and my browser cannot render any resource of my app.
I am configuring my application via annotations, rather than xml files. This is why I am asking this question and not reusing any already given answer. Searching for my problem only led me to people who don't use annotations. I did follow this tutorial. Maven is my build tool and Eclipse kepler my IDE.
Can anyone please help me? I would appreciate any tips and resources.
Here is my system setup:
I try to reach the webapp on http://localhost:8080/Spring4MVCHelloWorld/hello.
The tomcat catalina log does not show any error.
mvn clean package are my executed maven goals.
Here you can find the project on GitHub: https://github.com/Husterknupp/spring-octo-lana
In This is the tomcat error report:
HTTP Status 404 - /Spring4MVCHelloWorld/
type Status report
message /Spring4MVCHelloWorld/
description The requested resource is not available.
This is my pom.xml:
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>de.bschandera.jeetutorials</groupId>
<artifactId>Spring4MVCHelloWorld</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>Spring4MVCHelloWorld Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<spring.version>4.0.1.RELEASE</spring.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- Spring dependencies START -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Spring dependencies END -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope> <!-- provided because servlet api jar file must not be embedded inside the
webapp since, obviously, the container already has these classes in its classpath:
it implements the interfaces contained in this jar -->
</dependency>
</dependencies>
<build>
<finalName>Spring4MVCHelloWorld</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
Under src/main/java there are these three classes:
Config.java:
package de.bschandera.jeetutorials.config;
import org.springframework.context.annotation.Bean;
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.view.JstlView;
import org.springframework.web.servlet.view.UrlBasedViewResolver;
#Configuration
// Marks this class as configuration
// Specifies which package to scan
#ComponentScan("de.bschandera.jeetutorials.config")
// Enables Spring's annotations
#EnableWebMvc
public class Config {
#Bean
public UrlBasedViewResolver setupViewResolver() {
UrlBasedViewResolver resolver = new UrlBasedViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
}
HelloWorldController.java:
package de.bschandera.jeetutorials.config;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
#Controller
public class HelloWorldController {
#RequestMapping("/hello")
public String hello(#RequestParam(value = "name", required = false, defaultValue = "World") String name, Model model) {
model.addAttribute("name", name);
return "helloworld";
}
}
WebInitializer.java:
package de.bschandera.jeetutorials.config;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration.Dynamic;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class WebInitializer implements WebApplicationInitializer {
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(Config.class);
ctx.setServletContext(servletContext);
Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
servlet.addMapping("/");
servlet.setLoadOnStartup(1);
}
}
Under src/main/webapp/WEB-INF/views there is helloworld.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Spring4 MVC -HelloWorld</title>
</head>
<body>
<h1>Hello : ${name}</h1>
</body>
</html>
Under src/main/webapp/WEB-INF there is the index.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Spring4 MVC -HelloWorld INDEX</title>
</head>
<body>
<h1>Index page - welcome!</h1>
</body>
</html>
After having the first three answers not solving the problem, I would imagine that the problem has to do with any tomcat configuration or anything else but the code itself. But I dont know where to look for asides the suggested solutions.
Unless there's something you aren't showing us, you have no welcome-file and no handler for /.
Assuming /Spring4MVCHelloWorld is your context path, there is nothing in your configuration to handle a request to
http://localhost:8080/Spring4MVCHelloWorld/
Perhaps you meant to send the request to
http://localhost:8080/Spring4MVCHelloWorld/hello
which can be handled by your HelloWorldController.
Your class should extend WebMvcConfigurerAdapter class, see how your class should look like now
#Configuration
// Marks this class as configuration
// Specifies which package to scan
#ComponentScan("de.bschandera.jeetutorials.config")
// Enables Spring's annotations
#EnableWebMvc
public class Config extends WebMvcConfigurerAdapter {
#Bean
public UrlBasedViewResolver setupViewResolver() {
UrlBasedViewResolver resolver = new UrlBasedViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
}
I checked out your code and deployed it to Tomcat 7.0.27 (using Java 7) with only one change, and everything worked correctly.
The change I made was to add the jstl dependency to the pom.
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>

Categories