Issue with #EnableWebMvc and WebMvcConfigurationSupport - spring-boot

I have created a spring boot application and I am trying to get images from external folder on disk, here is my code:
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
#Configuration
#EnableWebMvc
#ComponentScan
public class WebConfigurer implements WebMvcConfigurer {
private static String UPLOAD_DIR = "D:\\upload";
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/images/**").addResourceLocations("file:" + UPLOAD_DIR+"/");
}
}
But when I launch the application, I got this error message:
> o.s.web.servlet.PageNotFound: No mapping for GET /myapp/index
> o.s.b.w.servlet.support.ErrorPageFilter : Cannot forward to error
> page for request [/] as the response has already been committed.
Even if I remove #EnableWebMvc and I extend WebMvcConfigurationSupport directly, I am getting the same issue.
Why am I getting this issue?
Is it possible to get images from external resources without using #EnableWebMvc or WebMvcConfigurationSupport?
Thanks

Ok I resolved the problem. Firstly I removed #EnableWebMvc and WebMvcConfigurationSupport, then I noted that there was an issue in the url. I put :
.addResourceLocations("file:/opt/files/");
Instead of:
.addResourceLocations("file:///C:/opt/files/");
As I am a Windows user.
Thanks

Related

Error 404 requestmapping and getmapping url doesn't work

Hi I m beginner and I have a simple problem, my url doesn't work. localhost:8080 work but not with /api. The project is built properly.
Localhost:8080
I put #ComponentScan("com.tutojwt.test.repository") because without it doesn't work.
Here my code
Controller :
package com.tutojwt.test.api;
import com.tutojwt.test.model.User;
import com.tutojwt.test.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
#RestController
#RequestMapping("/api")
#RequiredArgsConstructor
public class UserController {
private final UserService userService;
#GetMapping("/users")
public ResponseEntity<List<User>>getUsers(){
return ResponseEntity.ok().body(userService.getUsers());
}
Testapplication :
package com.tutojwt.test;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
#SpringBootApplication
#ComponentScan("com.tutojwt.test.repository")
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
Project structure
MAJ : Some of you say that is ComponentScan the prob but there are error if I dont put com.tutojwt.test.repository or just com.tutojwt.test
#ComponentScan("com.tutojwt.test") error
Without ComponentScan
You should call http://localhost:8080/api/users . #ComponentScan shouldn't be necessary and might actually cause problems (I don't think your controller class is scanned now, and some default hateoas endpoint is the one you're calling). #SpringBootApplication annotation has #EnableAutoConfiguration annotation by default and should scan all component annotated classes. If not, check your class structure again.

How to automatically add all Converters to a FormatterRegistry in Spring?

I have a Spring Boot 2.1.6 project that uses Spring's Converters a lot (24 of them). All are annotated as #Component. Now I've added a #EnableWebMvc and have to add them to the FormatterRegistry via registry.addConverter in a WebMvcConfigurer.addFormatters
Can I have Spring find all of them automatically (they are all in the same separate package) and add them or do I have to manually add all 24 of them and change my WebMvcConfigurer every time I add a converter?
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.Formatter;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.util.List;
#Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
#Autowired
List<Formatter> formatters;
#Override
public void addFormatters(FormatterRegistry registry) {
formatters.forEach(registry::addFormatter);
}
}
Since you have implemented the Converter interface and also annotated them with #Component, you can get them all by injecting them as a collection. #Autowired List<Converter> converters;

Using a custom error html file in spring boot

I have a url mapping for /error to go to my errorPage.html, but it is not redirecting to this, and I get the normal default spring boot error screen.
package coffee.web;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
#Configuration
public class WebConfig implements WebMvcConfigurer {
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("/index.html");
registry.addRedirectViewController("/admin", "admin/adminIndex.html");
registry.addViewController("/error").setViewName("/errorPage.html");
}
}
when I go to the url /error in the browser I get a status 999. when I go to an nonexistent address I get the default spring boot error page with a 404
ended up writing a explicit controller implement ErrorController

I cannot get a Restcontroller included in Spring Boot project - error 404

newbie pb on Spring Boot, I cannot get a RestController to be added to my application.
Here are the 2 files used to build this very simple app with maven:
1) Application.java
package com.learn.hello;
import java.util.Arrays;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
#Configuration
#ComponentScan(basePackages = "com.learn.hello.controller")
#RestController
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
#RequestMapping("/")
public String index() {
return "Greetings from Spring Boot!";
}
}
HelloController.java
package com.learn.hello.controller;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
#RestController
public class HelloController {
#RequestMapping("/titi")
public String index() {
return "Greetings from titi Boot!";
}
}
Structure of the project
/src/main/java/com/learn/hello/Application.java
/src/main/java/com/learn/hello/controller/HelloController.java
/target/*
/pom.xml
localhost:8080 works
but localhost:8080/titi does not (404 not found)
Any idea ?
Thx
You forgot to provide request method RequestMethod.GET :
#RequestMapping(value = "/students", method = RequestMethod.GET)
You can use #GetMapping("/titi") instead of #RequestMapping("/titi") :
#GetMapping("/titi")
To all, thanks a lot to all for your answers.
#Valerio,
you were right it was correct!!! In fact an invisible char got added at the end of the filename: HelloController.java (me probably messing-up with Sublime...), thus it was not processed as a java file by maven...
Sorry for the noise.My apologies.
BTW if anybody knows about any sort of options to actually warn that a file located in the /src/main/java/* directories was not processed as a "regular java project" file I'm interested to know about it even though I doubt that this is really feasible and thus existing...

WebMvcConfigurerAdapter does not work

This is WebConfig code I am working on:
package hello.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
#Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/greeting").setViewName("greeting");
}
}
And this is my Application.class
package hello;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
#SpringBootApplication
public class Application extends SpringBootServletInitializer{
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
}
It seems to be a spring-boot issue that these class methods don't get called in some systems. The corresponding issue is reported at:
https://github.com/spring-projects/spring-boot/issues/2870
My question is, can we map resources mapped in this class, outside this class as a temporary workaround?
If yes, how do we do this?
Update: Following Andy Wilkinson's suggestion I removed #EnableWebMvc and the demo app started working. Then I tried stripping down project files one by one to see at what point error disappears. I found that I had two classes in the project, one, extended from WebMvcConfigurationSupport and the second, from WebMvcConfigurerAdapter. removing the former class from the project fixed the error.
What I want to know is, why did this happen? Secondly, why doesnt this error appear on all systems?
The problem is that WebConfig is in the config package and Application is in the hello package. #SpringBootApplication on Application enables component scanning for the package in which it's declared and that package's sub-packages. In this case that means that hello is the base package for component scanning and, therefore, WebConfig in the config package is never found.
To solve the problem I'd move WebConfig into the hello package or a sub-package, for example hello.config.
Your latest update on GitHub changed WebConfig from extending WebMvcConfigurerAdapter to extending WebMvcConfigurationSupport. WebMvcConfigurationSupport is the class that is imported by #EnableWebMvc so annotating your class with #EnableWebMvc and extending WebMvcConfigurationSupport will be configuring things twice. You should go back to extending WebMvcConfigurerAdapter as you were before.

Resources