spring boot application running but endpoint throwing 404 - java

I was trying my hand at writing a sample Spring Boot application.
My initial thought was it's an easy example to follow and write but I am not able to print a simple statement upon hitting my endpoint.
I don't want to use any view (HTML,JSP etc) right now as I want to learn the backend first.
I have followed:
Getting Started
Spring Boot Guide
However, still stuck after a whole day of googling.
So let me reiterate the steps, I did.
Initialized a spring boot project from spring.io and downloaded zip.
Extracted the zip and imported it into Eclipse.
Configured a Rest Controller with an endpoint to just print a hello world statement.
Tomcat 9.0.56 is present on my system.
Running TodoApplication as Java application or Spring boot.
URL I am hitting is http://localhost:8080/greet
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class HelloWorldController {
#GetMapping("/greet")
public String sayHelloWorld() {
return "Hello World";
}
}
Spring Boot Application:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class TodoApplication {
public static void main(String[] args) {
SpringApplication.run(TodoApplication.class, args);
}
}
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.6.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.sample</groupId>
<artifactId>todo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>todo</name>
<description>Back-end for To DO App</description>
<properties>
<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>
After navigating greet URL:
Got the following exception at console:

So the solution as pointed out by xerx593 is below:
Make sure to select packaging as war/jar in https://start.spring.io/.
Import the zip file.
Add your controller class in same or child package of SpringBootApplication, refer this for more info https://docs.spring.io/spring-boot/docs/current/reference/html/using.html#using.structuring-your-code.
Open terminal and change directory to working folder.
Run mvn spring-boot:run if using maven.
Hit the endpoint for example http://localhost:8080/greet or curl request.
Also I have noticed that 8080 port is listening but spring boot fails to register on it, in this case set
server.port = port other than 8080
in application.properties.

Related

Getting 403 when one spring boot api is called from a java client although security dependencies are not added

I have created a simple spring boot application, with a get api which return "Hello world". The api works fine when called from postman or browser. However when I am trying to consume the api via JAX-RX(Jercy or RestEasy) or spring boots Rest Template in a different application, it gives 403 Forbidden (Authentication required) error.
Note: - My spring boot application have dependency only on spring-boot-starter-web and no other security dependency is added.
Following things I have tried but did not work
a. Adding dependency spring-boot-starter-security
b. Disabling csrf and cors.
c. authorizeRequests/authorizeHttpRequests anyRequests PermitAll.
Spring Boot Application
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.7.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>SpringServerApp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>SpringServerApp</name>
<description>A simple spring rest server</description>
<properties>
<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>
Controller class
package com.example.SpringServerApp.controller;
import org.springframework.web.bind.annotation.*;
#RestController
public class MainController {
#GetMapping("/helloGet")
String getHello() {
return "Hello World";
}
}
Client Code in a different application to call the api
package org.example.restClient;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Response;
public class JercyClient {
private static final String GET_HELLO = "http://localhost:8080/helloGet";
private static final String SAMPLE_API = "https://catfact.ninja/fact";
static WebTarget webTarget;
static {
Client client = ClientBuilder.newClient();
webTarget = client.target(GET_HELLO);
}
public static String getHello() {
Response response = webTarget.request().get();
return response.readEntity(String.class);
}
}

Spring-boot logo not loading on console, how to start application on tomcat server?

This is a Simple Microservice built using spring-boot. The application is working fine when I execute as Java Application. But when I run on Server i.e. Tomcat Server v8.5 the Server shows Started & Syncnorized but in console, the spring-boot logo doesn't appear and the application doesn't start. Other Projects on my IDE are working fine.
I tried following but didn't work:
1)Delete Server and add again.
2)Clean the Project using Maven.
3)Changed BuildPath Settings(JDK Version, Facets, etc).
Screenshot to refer
1) https://i.imgur.com/fVFLhNK.png
2)https://i.imgur.com/nTSWEGd.png
Main App
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
#SpringBootApplication
public class ShUsersApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(ShUsersApplication.class, args);
}
}
Controller
package com.logituit.sitehawk.Controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.lang.NonNull;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.google.gson.Gson;
import com.logituit.sitehawk.Model.Contract;
import com.logituit.sitehawk.Service.UserService;
#RestController
#RequestMapping("/sitehawk")
public class UserController {
private UserService userService;
private Gson gson;
#Autowired
public UserController(#NonNull final UserService userService, #NonNull Gson gson) {
this.userService = userService;
this.gson = gson;
}
#PostMapping("/save")
public String saveDetails(HttpEntity<String> httpEntity) {
final Contract contract = gson.fromJson(httpEntity.getBody(), Contract.class);
if (contract != null) {
userService.createTicketBySite(contract);
return "Success";
} else
return "Failed";
}
#GetMapping("/ticketsfromsite/{siteId}")
public List<Contract> getAllTicketsBySite(HttpEntity<String> httpEntity, #PathVariable("siteId") final int siteId) {
return userService.getTicketsBySite(siteId);
}
}
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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.7.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.logituit.sitehawk</groupId>
<artifactId>SH_Users</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>SH_Users</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-data-jpa</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.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</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>
application.properties
#Local Database
spring.datasource.url = jdbc:mysql://localhost:3306/site_hawk
spring.datasource.username = root
spring.datasource.password = admin123
server.port=8089
Please help me how can I run my spring-boot App.I'm want to see Spring boot running on the console. But the Big Logo of Spring Boot doesn't appear on the console.
The normal deployment format for application containers (Tomcat included) is .war however Spring Boot by default packages a runnable jar file.
You can change the packaging format in pom.xml file.
<packaging>war</packaging>
You may also need to add an additional dependency for Tomcat specific classes.
...
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
Such setup should yield a .war file to $project_dir/target/classes which most servlet containers can successfully run.
Server doesn't simple print everything in the console, since there will be a lot of applications running at the same time, the console is going to be a big confuse messy with so many "System.out", so the solution to the servers is put on log to each application. Try to find you application logs, maybe the spring logo will be there.
Be sure also that you are uploading a .war file. The jar package is for running is you pc. For Tomcat you need to send the .war file. You can simple change the packaging type in your pom.xml.
Usage - Apache Maven WAR Plugin
To run your application in tomcat server you should exclude the embedded one via :
<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>
And as käyrätorvi said package your application as war
Spring boot applications include an embedded web server and can be run in a number of ways. Tomcat is included by default which can be overridden by other servers. You can find the reference here and here.
Spring boot applications, unlike traditional java web applications, are simplified in terms of running and deploying. As a developer, you can focus on developing the core logic, exposing the endpoints etc. Once built, these applications are ready to run and do not need to be deployed on an explicit server as they run on an embedded server that comes from spring boot starter web dependency.

Index page doesn't work but api works on AWS beanstalk Sprint Boot

I am trying to deploy a spring boot application to aws.
I changed the port to 5000 via application.properties
Now, url/api/hello works fine but url/ doesn't work
I am getting a white label error.
package com.example.package-name;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
#EnableAutoConfiguration
#SpringBootApplication
#ComponentScan()
public class DemoApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
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>package-name</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.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>
Can anyone tell me how to fix this?
Is there anything wrong with the main Starter file?
Note: Everything works fine locally, the error page is loading instead
of index page only in AWS
I assume you deploy in aws elastic beanstalk tomcat server, please make sure access via beanstalk URL which will give you after uploading jar/war, generally whitespace error gives you whenever you try to access wrong URL/wrong parameters, if possible provide details with screenshots.

tomcat is not starting up when running app

this is pom xml
i have main class and one simple controller which returns string as json.
i am just running spring boot 2.x by adding below dependency.
in console it shows tomcat is started and application is started.but when i am hitting from postman or url in browser it will 404.
http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
<groupId>com.kd</groupId>
<artifactId>restdemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>restdemo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.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-jersey</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>
this is my controller:
package com.kd.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class ServiceControllerKd {
#RequestMapping("/")
public Hello greeting() {
System.out.println("hello");
return new Hello();
}
}
I have taken your code, built it, ran it and hit the endpoint and have successfully received a response. However, it is difficult to assess what may be causing your issue without the full project.
I have created an example project using the code you provided here that runs successfully. It may be best to compare this project against your own to attempt to find any inconsistencies.
https://github.com/michaelmcfadyen/spring-boot-example
double check that you have your controller in the same package as your SpringBootApplication or in a child package
package com.kd;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
In the log you have to see something similar to
2018-07-28 12:34:01.669 INFO 10425 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/]}" onto java.lang.String com.kd.controller.ServiceControllerKd.greeting()
I think the problem is that you must first try to return a single string
example:
return "Hello world!"
To make sure that the problem is not from your Hello object.
Another thing that you have to make sure is that you have the right port on the postman request example http://localhost:8000/ and that your method on post man get the right verb, in your case you can add
#RequestMapping(value = "/", method = RequestMethod.GET)
and it's gonna be a "get".

Getting 404 while hitting my REST application developed using Spring Boot on standalone tomcat

I am not able to hit my REST api developed using Spring Boot and Java 8 on a standalone tomcat. Getting 404 when I hit it through my browser. However, the same application when hit through embedded tomcat, works.
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.study.rest</groupId>
<artifactId>hello-world-rest-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>hello-world-rest-demo</name>
<description>Hello World REST API - Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.3.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>
<!--
To make the application both executable with embedded tc and also deployable on standalone tc.
Make sure to change the artifact packaging type from jar to war (see up)
-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<fork>true</fork>
</configuration>
</plugin>
</plugins>
</build>
</project>
META-INF/context.xml
<?xml version="1.0" encoding="UTF-8"?>
<Context path="/hello-world-rest-demo"/>
BasicRestApplication.java
#SpringBootApplication
public class BasicRestApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(BasicRestApplication.class, args);
}
/*
For starting the application in standalone TC
*/
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(BasicRestApplication.class);
}
}
HelloWorldController.java
#RestController
#RequestMapping("/api")
public class HelloWorldController {
//URI: http://localhost:8080/api/products
#RequestMapping(value = "/hello", method = RequestMethod.GET)
public ResponseEntity<String> get() {
return new ResponseEntity<>("Hello World", HttpStatus.OK);
}
}
Command:
mvn spring-boot:run
Runs the application and display "Hello World" when I hit http://localhost:8080/api/hello in the browser
mvn clean install -DskipTests
Manually deploy the war on local tomcat and start it.
http://localhost:8080/api/hello in the browser gives 404
path="/hello-world-rest-demo" in META-INF/content.xml might be getting ignored, try using the context path (specified in server.xml) in the URL or the name of the war file, something like:
http://localhost:8080/<appName>/api/hello
Remove the path property from context.xml, if not specific reason to maintain it. Rather remove the context.xml file altogether. Spring boot facilitates independence from any xml based configuration.
Refer this blog's Config goes away section.
You should see your REST api accessible from both the browser & embedded.

Categories

Resources