Java Spring Boot - routing for access to static folder - java

I am working on a reactjs project and I just did a yarn build and moved the contents into the Java project.
my-project\complete\src\main\resources\static
but when I view the project from the Java site -- localhost:8080 -- I get a ton of 404 errors
logo.a67f8998.png:1 GET http://localhost:8080/static/media/logo.a67f8998.png
registerServiceWorker.js:77 GET http://localhost:8080/service-worker.js 404
-beefeater.78e4414b.jpg:1 GET http://localhost:8080/static/media/-beefeater.78e4414b.jpg 404 ()
For this project I am mostly acting as a frontend dev - Where do I make the required changes to get the routing correct for these files?
my Application.java file looks like this - when I uncomment the code I get told to remove the #overide?
//import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
/**
* Hello world!
*
*/
#SpringBootApplication
public class Application implements CommandLineRunner {
//#Autowired
//private AccountRepository accountRepository;
/**
* #param args
*/
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
#Override
public void run(String... arg0) throws Exception {
}
/*
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**")
.addResourceLocations("classpath:/static/");
}*/
}
I've tried to add a config file to sort this out.. do I need to import it in the application.java?
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
//#Configuration
#EnableWebMvc
#WebAppConfiguration
public class Configuration extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/static/**")
.addResourceLocations("classpath:/static/");
}
}

You're missing #WebMvcAutoConfiguration annotation I think

Related

Deploying springboot war to tomcat throws 404

I am able to run this as spring boot war that uses embeded tc.
In another thread it said use tomcat 9. I am using 10. Still getting the error.
My Spring boot App class:
package pra.learn.tcjardemo;
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;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
#SpringBootApplication
#RestController
public class TcjardemoApplication extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(TcjardemoApplication.class);
}
#GetMapping("/show")
public static String getShow(){
return "Show is the problem";
}
// public static void main(String[] args) {
// SpringApplication.run(TcjardemoApplication.class, args);
// }
}
Not sure what am i missing.
So, I deployed it on tc9 and it worked. Why isn't the same war working on tc10?

NoSuchBeanDefinitionException: No bean named 'authService' available

When trying to use the api, I get this error:
"org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'authService' available".
How do I make the authservice be found by the app? I've gotten a similar error before, which I tried to fix by adding all the packages you see below in the Main class.
The Main class:
package com.lvwangbeta.poplar.api;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import com.lvwangbeta.poplar.action.PoplarActionServiceApplication;
import com.lvwangbeta.poplar.feed.PoplarFeedServiceApplication;
import com.lvwangbeta.poplar.tag.PoplarTagServiceApplication;
import com.lvwangbeta.poplar.user.PoplarUserServiceApplication;
import java.util.List;
#SpringBootApplication(scanBasePackages= {"com.lvwangbeta.poplar.common","com.lvwangbeta.poplar.common.intr","com.lvwangbeta.poplar.action",
"com.lvwangbeta.poplar.api.service",
"com.lvwangbeta.poplar.feed","com.lvwangbeta.poplar.tag",
"com.lvwangbeta.poplar.user", "com.lvwangbeta.poplar.api"})
//#ComponentScan({"com.lvwangbeta.poplar.common","com.lvwangbeta.poplar.user","com.lvwangbeta.poplar.feed.dao", "com.lvwangbeta.poplar.api"})
#ComponentScan({"com.lvwangbeta.poplar.action.dao.impl","com.lvwangbeta.poplar.feed.dao.impl"})
#MapperScan({"com.lvwangbeta.poplar.action.dao","com.lvwangbeta.poplar.feed.dao","com.lvwangbeta.poplar.tag.dao"})
public class PoplarApiApplication extends WebMvcConfigurerAdapter {
public static void main(String[] args) {
//Object[] sources = {PoplarApiApplication.class,PoplarTagServiceApplication.class};
//SpringApplication.run(sources, args);
System.out.println("Started");
SpringApplication.run(PoplarApiApplication.class, args);
//SpringApplication.run(PoplarTagServiceApplication.class, args);//I hope this works
//SpringApplication.run(PoplarActionServiceApplication.class, args);
//SpringApplication.run(PoplarFeedServiceApplication.class, args);
//SpringApplication.run(PoplarUserServiceApplication.class, args);
}
#Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
super.addArgumentResolvers(argumentResolvers);
argumentResolvers.add(new RequestAttributeArgumentResolver());
}
#Override
public void addInterceptors(InterceptorRegistry registry) {
super.addInterceptors(registry);
registry.addInterceptor(new APIAccessAuthRequiredInterceptor())
.addPathPatterns("/api/v1/**")
.excludePathPatterns("/api/v1/user/login/**")
.excludePathPatterns("/api/v1/user/check/email/*")
.excludePathPatterns("/api/v1/user/register/**")
.excludePathPatterns("/api/v1/feed/of/user/**");
}
}
The AuthService class:
package com.lvwangbeta.poplar.api.service;
import com.lvwangbeta.poplar.common.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
#Service("authService")
public class AuthService {
#Autowired
private RedisTemplate<String, String> redisTemplate;
#Resource(name="redisTemplate")
private HashOperations<String, String, Object> mapOps;
public User getUserByToken(String token) {
return (User) mapOps.get("tokens:", token);
}
}
What am I missing? It's not registering even though the api link is there. I'm trying to combine many microservices to one, and so there's alot of packages.
include com.lvwangbeta.poplar.api.service in #ComponentScan
Like this :
#ComponentScan({"com.lvwangbeta.poplar.action.dao.impl","com.lvwangbeta.poplar.feed.dao.impl", "com.lvwangbeta.poplar.api.service"})
Suggestion :For simple applications avoid configuring the way above.
Keep your project structure as explained in this reference and #SpringBootApplication is enough.
https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#using-boot-locating-the-main-class

How to resolve the problem related to "Whitelabel Error Page" in a Spring Boot application

I am trying to execute my new Spring Boot application.
The first two classes are:
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class UbbioneApplication {
public static void main(String[] args) {
SpringApplication.run(UbbioneApplication.class, args);
}
}
then the servlet Initializer class
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
public class ServletInitializer extends SpringBootServletInitializer {
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(UbbioneApplication.class);
}
}
But when I am used to run my application by writing mvn spring-boot:run in the console, I have this message appearing:
Whitelabel Error Page
Could you help me please how to resolve this issue?
Thanks in advance.
I think I have an answer:
I created a controller to my application and I updated my code as following:
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
#Configuration
#EnableAutoConfiguration
#ComponentScan(basePackages = {"Name_controller_path"})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Then my controller will look like this:
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class Appcontroller {
#RequestMapping(value = "/home", method = RequestMethod.GET)
String home() {
return "home";
}
}
Then use this path to view your execution: http://localhost:8080/home.

405 error code on static html spring boot

I am trying to return a static html(index.html) page using spring boot but I am alway getting a 405 error whem I trying (http://localhost:8080/). Strange fact is that debugger enters index() method.
HomeController:
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 = RequestMethod.GET)
public String index() {
return "index.html";
}
}
I have tried to return "index.html" and "index" strings.
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
#SpringBootApplication
public class Application {
public static void main(String[] args) throws InterruptedException {
ConfigurableApplicationContext applicationContext
= SpringApplication.run(Application.class, args);
}
}
location of html file is:
src\main\resources\public\index.html
here goes a part of startup logger output:
INFO 8284 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/],methods=[GET]}" onto public java.lang.String com.acs.map.controller.HomeController.index()
Screanshot of an error
and i am running project with gradle: gradle bootRun
Logger message after request:
WARN 3988 --- [nio-8080-exec-6] o.s.web.servlet.PageNotFound : Request method 'GET' not supported
Also I have tried with and without this configuration:
import org.springframework.context.annotation.Bean;
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.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceView;
import org.springframework.web.servlet.view.UrlBasedViewResolver;
#Configuration
#EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/public/**").addResourceLocations("classpath:/public/");
registry.addResourceHandler("/resources/public/**").addResourceLocations("classpath:/resources/public/");
super.addResourceHandlers(registry);
}
#Bean
public ViewResolver viewResolver() {
UrlBasedViewResolver viewResolver = new UrlBasedViewResolver();
viewResolver.setViewClass(InternalResourceView.class);
return viewResolver;
}
}
By default Spring Boot will serve static content from a directory called /static (or /public or /resources or /META-INF/resources). I did a quick check by following the below structure and was successful.
So I believe by extending WebMvcConfigurerAdapter class like below and it should return static content using your current controller code (without the WebConfig class).You can use viewResolver as well to map between view names and actual views as well by further modifying your code.
#SpringBootApplication
public class Application extends WebMvcConfigurerAdapter{
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Here are my project dependencies

Multiple SpringBoot apps, want to run only one

I'm currently working with SpringBootApplications, I have two differets #SpringBootApplication , one for Web Application, and a CommandLineRunner .
The problem is, no matter which of them I execute, it tries to run both of the applications.
package com.ws;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.context.annotation.Configuration;
#EnableAutoConfiguration
public class Init extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Init.class);
}
/**
* Main method.
*
* #param args String[].
* #throws Exception Exception.
*/
public static void main(String[] args) throws Exception {
SpringApplication.run(Init.class, args);
}
And this is my other InitBatch.java :
package com.batch;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class InitBatch implements CommandLineRunner {
#Autowired
private Batch batch;
#Override
public void run(String... args) throws Exception {
batch.processFiles();
}
public static void main(String[] args) throws Exception {
SpringApplication.run(InitBatch.class, args);
}
}
If I run the CommandLineRunner app, after it is executed, continues to load the Web App.
I need to be able to run each of them separately from each one. But I don't know how to configure this.
Thanks!
the spring docs say:
SpringBootApplication: This is a convenience annotation that is equivalent to declaring #Configuration, #EnableAutoConfiguration and #ComponentScan.
You should only ever add one #EnableAutoConfiguration annotation. We generally recommend that you add it to your primary #Configuration class.
so effectively you're adding 2 EnableAutoConfiguration annotations which just isn't allowed by spring boot. I would suggest using spring Profiles to achieve what you need.

Categories