405 error code on static html spring boot - java

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

Related

Facing SpringBoot Security module login error

I am creating spring boot basic application with login feature.
My login feature is not working and generating below debug log.
2019-09-26 14:50:01.262 DEBUG 3720 --- [nio-8080-exec-4] o.s.b.w.f.OrderedRequestContextFilter : Bound request context to thread: org.apache.catalina.connector.RequestFacade#6deb15fd
2019-09-26 14:50:01.277 DEBUG 3720 --- [nio-8080-exec-4] o.s.b.w.f.OrderedRequestContextFilter : Cleared thread-bound request context: org.apache.catalina.connector.RequestFacade#6deb15fd
Below is my controller class code.
package com.sourabh.app.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.sourabh.app.repository.SpringJava4sDAO;
import com.sourabh.model.Customer;
#RestController
public class MainAppController {
#Autowired
public SpringJava4sDAO dao;
#RequestMapping("/")
public String welcome() {
return "Welcome to Sring boot application";
}
#RequestMapping("/userlogin")
public String userValidation() {
return "User: Successfully logged in!";
}
#RequestMapping("/adminlogin")
public String adminValidation() {
return "Admin: Successfully logged in!";
}
}
Below is my SpringSecurityConfig class code
package com.sourabh.app.configs;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
// Authentication : set user/password details and mention the role
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().passwordEncoder(org.springframework.security.crypto.password.NoOpPasswordEncoder.getInstance())
.withUser("user").password("pass").roles("USER")
.and()
.withUser("admin").password("pass").roles("USER", "ADMIN");
}
// Authorization : mention which role can access which URL
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic().and().authorizeRequests()
.antMatchers("/userlogin").hasRole("USER")
.antMatchers("/adminlogin").hasRole("ADMIN")
.and()
.csrf().disable().headers().frameOptions().disable();
}
}
Added dependency is pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
Boot Driver Class code
package com.sourabh.app;
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 MainApp extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(MainApp.class, args);
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(MainApp.class);
}
}
Am i missing anything, or made any mistake?
Note:- dao and model are not included in question as they are not part of login process. Login pop-up is coming but its authorizing user.
You are missing #Configuration. your configuration class should be annotated as given below.
#Configuration
#EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter
{
...
}

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.

Java Spring Boot - routing for access to static folder

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

Spring boot not displaying first view

I'm building a spring boot application. My problem is that when I run the project, my login page is not shown. This is my code:
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class RestLogin {
#RequestMapping("/")
public String login() {
return "login";
}
}
I get only a white page and "login" is written in it. When I try to change the #RestController with #Controller I get this GET http://localhost:8080/ 404 (). My login.html page is located under the webapp>tpl>login.html
How can I display my login page?
Edit
This is my application class
#SpringBootApplication
public class ExampleApplication extends SpringBootServletInitializer {
private static Logger logger = LoggerFactory.getLogger(ExampleApplication.class);
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(ExampleApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(ExampleApplication.class, args);
}
}
I dont know your configuration but:
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic().and().authorizeRequests()
.antMatchers("/**").permitAll();
http.authorizeRequests().antMatchers("/**").permitAll();
}
}
In the Application.properties file add:
spring.mvc.view.suffix: .html
Change #RestController to #Controller for RestLogin class. Also put your html file inside the static folder inside resources folder.
You need an application class with a main method. See this tutorial.
Here's a snippet:
package 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;
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
#Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
return args -> {
System.out.println("Let's inspect the beans provided by Spring Boot:");
String[] beanNames = ctx.getBeanDefinitionNames();
Arrays.sort(beanNames);
for (String beanName : beanNames) {
System.out.println(beanName);
}
};
}
}
This is the normal behavior.
New version of Spring web comes with #RestController annotation which nothing but #Controller + #ResponseBody. So when you have a return statement in a method you must use #RestController or annotate your method with #ResponseBody.
Here the problem is that Spring don't know a lot about the http method type, can you please try to use #GetMapping("/") to combinbe path and method at the same time.
According to your posted code and your description, you're getting an expected behavior.
When you annotate your controller with #RestController, that means that your methods on that controller will try to return their result as JSON.
According to your code:
#RestController
public class RestLogin {
#RequestMapping("/")
public String login() {
return "login";
}
}
You're returning the String "login", that's why you're getting empty white page with the word login as JSON
If you will change the #RestController to #Controller then it no longer will return your string as JSON,
but Spring will try to figure out from the that "login" string a view, and for that you'll need to add a view resolver bean to your project.

Spring on Wildfly not rendering index.html when root URL hit

Due to project requirements I have to deploy a Spring application to a server incapable of running Tomcat and only capable of running WildFly. When I had a very simple project running on Tomcat and the root URL was hit (localhost:8080) it rendered my index.html. Since migrating to WildFly and refactoring the structure of my project, localhost:8080 no longer renders the index.html but I can still reach other URLs.
I've tried to implement a jboss-web.xml file under BrassDucks/src/main/webapp/WEB-INF/jboss-web.xml like this:
<jboss-web>
<context-root>Brass-Ducks</context-root>
</jboss-web>
Where Brass-Ducks is the artifactID but to no avail.
Consider my ApplicationConfig.java
package brass.ducks;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#Configuration
#ComponentScan
#EnableAutoConfiguration
public class ApplicationConfig extends SpringBootServletInitializer{
public static void main(String[] args) {
SpringApplication.run(ApplicationConfig.class, args);
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(applicationClass);
}
private static Class<ApplicationConfig> applicationClass = ApplicationConfig.class;
}
#RestController
class GreetingController {
#RequestMapping("/hello/{name}")
String hello(#PathVariable String name) {
return "Hello, " + name + "!";
}
}
and consider my Controller.java
package brass.ducks.application;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
#RestController
#RequestMapping("/")
public class Controller {
#RequestMapping("/greet")
#ResponseBody
public String greeting() {
return "Hello, there.";
}
}
And finally should it be relevant, my folder structure:
localhost:8080/greet returns "Hello, there" and localhost:8080/hello/name returns "Hello name". How can I fix this?
Depending on your exact configuration something along the lines of this should work:
#Controller
public class LandingPageController {
#RequestMapping({"/","/home"})
public String showHomePage(Map<String, Object> model) {
return "/WEB-INF/index.html";
}
}
This is going to explicitly map / to index.html.

Categories