1

I am currently trying to create a simple Spring Boot application that I can send a request from my Postman application to a rest endpoint and the application will perform a basic operation on the data handed over and return the result in a Response.

Here is my RestService class with one endpoint that returns a message to say it was connected to:

package TestRestService.TestRestService;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

@Path("/testApplication")
@Consumes({ "application/json" })
@Produces({ "application/json" })
public class RestServiceTest {

    @GET
    @Path("/hitme")
    @Produces({ "application/json" })
    public Response getServerInfo(){
         String message = "Hit the end point";
         return Response.ok(message).build();
    }
 }

Here is my main class:

 @SpringBootApplication
 public class App {
      public static void main( String[] args ){
           SpringApplication.run(App.class, args);
      }
 }

I have an index.html containing a simple title and paragraph which shows when run the app on server. I originally had a web.xml but that stopped me from connecting to any pages within the service so i deleted it and now I can access the index.html pages but no other points that I know of.

When I connect to http://localhost:8080/TestRestService/testApplication/hitme via Postman or in STS I get:

hitme

Can anybody advise of what I should be doing to be able to connect to these rest endpoints?

Prags
  • 2,457
  • 2
  • 21
  • 38
shirafuno
  • 387
  • 3
  • 9
  • 24

4 Answers4

1

OK, found the issue. You are using JAX-RS Spec without any provider like Jersey, CXF. I modified your pom.xml and used Spring RestController to implement REST service. Please use below and then test hitting URI http://localhost:8080/testApplication/ from browser or postman and you will get the response. Here is pom.xml

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.8.RELEASE</version>
</parent>

<dependencies>
<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>3.8.1</version>
  <scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.ws.rs/javax.ws.rs-api 
<dependency>
    <groupId>javax.ws.rs</groupId>
    <artifactId>javax.ws.rs-api</artifactId>
    <version>2.1</version>
</dependency>
-->
<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>com.jayway.jsonpath</groupId>
        <artifactId>json-path</artifactId>
        <scope>test</scope>
    </dependency>

<build>
    <pluginManagement>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <!-- 
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat6-maven-plugin</artifactId>
                <version>2.2</version>
            </plugin>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
            </plugin>
             -->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </pluginManagement>
</build>

Here is RestController class:

package com.resources;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

    @RestController
    public class SpringRestController {

@RequestMapping(method = { RequestMethod.GET }, value = { "/testApplication" }, consumes = MediaType.ALL_VALUE, produces = MediaType.ALL_VALUE)
public String getServerInfo() {
    System.out.println("I got hit");
    String message = "Hit the end point";
    return message;
}

}

Har Krishan
  • 273
  • 1
  • 11
  • Unfortunately I have copied your code fully,, completely replacing my pom.xml and Rest class to match yours then ran a maven update but no luck. Here is the updated console logging output - https://pastebin.com/mUktw5Tb – shirafuno Nov 22 '17 at 23:14
  • please copy code including pom.xml from https://pastebin.com/QNYaZygA and then test by hitting http://localhost:8080/testApplication/ from the browser. I tested the code locally and it is working. – Har Krishan Nov 23 '17 at 06:43
  • I have overwritten my pom with your pom and then run a maven -> download sources & update project. Then right clicked App.java and run as -> Java application then went to localhost:8080/testApplication and still the error is 404 with message "The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.". If it is working for you and still not for me, could this be a tomcat issue? – shirafuno Nov 23 '17 at 07:04
  • There is nothing which I can think can cause the problem as I commented tomcat plugins from pom.xml. Please share your pom.xml – Har Krishan Nov 23 '17 at 07:09
  • Looks like the problem is with the project structure. Please follow the below steps to create a new Maven project: Using File ->New -> Other ->Maven Project -> (Select option Create a simple project (skip archetype selection)) and then provide groupid, artifact and version details. Once Maven project is created then copy pom.xml and classes to that project and then run. – Har Krishan Nov 23 '17 at 07:17
  • I created a new simple maven project named SimpleRestTest with groupId "com" and ArtifactId "SimpleRestTest". Copied over the pom.xml and created two packages in src/main/java called com & com.resources then copied App.java into com and RestService into com.resources. Then I ran maven update and restarted tomcat and then rightclick App.java run as -> java application. Still the same error unfortunately. – shirafuno Nov 23 '17 at 07:34
  • You need not to start tomcat. Just run App.java run as -> java application. It will automatically run the embedded tomcat – Har Krishan Nov 23 '17 at 08:39
  • In case Tomcat is already running then stop that and then just run App.java run as -> java application. It will automatically run the embedded tomcat – Har Krishan Nov 23 '17 at 08:41
  • I stopped Tomcat and ran App.java as java application. In both postman and my broswer it say that they are unable to get a response, there was an error connecting to "localhost:8080/testApplication" – shirafuno Nov 23 '17 at 09:55
  • In your application.properties file use different port for Tomcat adding: server.port=8081 and then rerun app App.java as java application and try connecting to this port – Har Krishan Nov 23 '17 at 10:08
  • I added server.port=8081 to application.properties and kept my Tomcat server stopped and ran the App.java as Java application but there is still no response. I guess the embredded tomcat server is not being run? – shirafuno Nov 23 '17 at 10:23
  • ok, change the jar to war. Rt click on pom.xml and then Run As -> Maven Clean. After this Rt click on pom.xml and then Run As -> Maven Install. It will create the .war file something like TestRestService-0.0.1-SNAPSHOT.war under target directory. Now put this war file after renaming like TestRestService.war under tomcat's webapps directory. Now start this tomcat and hit the url. In the url use the application context name. So the url will become http://localhost:8080/TestRestService/testApplication – Har Krishan Nov 23 '17 at 10:40
  • I have an odd error... "No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?" I have gone to windows -> preferences -> java -> installed JRE's and it says "java-8-openjdk-amd64(default)". Could this be a contributing factor? – shirafuno Nov 23 '17 at 11:18
  • The problem is only with your environment nothing wrong with code. – Har Krishan Nov 23 '17 at 11:32
  • I don't understand quite though. It is pointing to openjdk in installed JRE's. Is that not the jdk then? – shirafuno Nov 23 '17 at 12:34
  • I am using windows and here is jdk C:\Program Files\Java\jdk1.8.0_121 whereas here is jre C:\Program Files\Java\jre1.8.0_121. In your eclipse you need to point to the jdk i.e. C:\Program Files\Java\jdk1.8.0_121 – Har Krishan Nov 23 '17 at 12:40
  • I downloaded jdk1.9.1 and added it to Installed JRE's and pointed to that instead of default jdk. right clicking the app and running as java application works fine but maven install still fails thinkiing it is using a JRE or non-valid jdk..? – shirafuno Nov 23 '17 at 13:32
  • I upgraded my jdk and jre using https://www.wikihow.com/Upgrade-Oracle-Java-on-Ubuntu-Linux. I still get the issue with maven install through sts but in terminal I ran "mvn clean install" and got this error - https://pastebin.com/sG8yjTMF – shirafuno Nov 23 '17 at 13:42
  • check https://stackoverflow.com/questions/25235229/extracting-zipped-file-from-resourcestream-throws-error-invalid-stored-block-le if it solves your current problem. If not then please use jdk 1.8 not 1.9. – Har Krishan Nov 23 '17 at 13:55
  • I deleted the jar in question because it was most likely corrupted and rerun mvn clean install with a success. However I am met with a new problem (https://pastebin.com/Svek9iWx) but I will fix it using this solution (https://stackoverflow.com/questions/45917401/tomcat-7-0-73-doesnt-work-with-java-9) – shirafuno Nov 23 '17 at 14:11
  • Good to know that at least now things are looking better. I would recommend to use jdk 1.8 as I tested everything with this version but you can give try to resolve the current issue with 1.9 – Har Krishan Nov 23 '17 at 14:19
  • I wasn't able to start the tomcat server from within STS so I manually start it using it's start up script. I had placed TestRestService-0.0.1-SNAPSHOT.war within tomcat/webapps which also generated a directory of the same name. However I then navigate to the url and same problem. "The origin server did not find a current representation for the target resource or is not willing to disclose that one exists." – shirafuno Nov 23 '17 at 19:24
  • For somereason I closed and reopened my STS and then did a mvn update and run as java application on one of the projects and I now have the embedded tomcat starting on 8081. here is the console output - https://pastebin.com/1bzuH89u . I think what the problem is is that it is not mapping the endpoints properly to the application. – shirafuno Nov 23 '17 at 20:41
  • I created a new dynamic web module project which contains a simple endpoint and a web.xml which contains servlet mapping (https://pastebin.com/AcrMTvza) yet going to localhost:8080/test/resource/get still produces the error. Something is seriously wrong with my environment. – shirafuno Nov 24 '17 at 05:58
  • Yes, I think before doing anything you need to run this so that you will be sure that there is no problem with environment. You can try step by step i.e. first run Hello World java program to verify java has installed correctly and then move to web project to verify the tomcat installation. – Har Krishan Nov 24 '17 at 06:47
  • I have created a simple hello world program which compiled and showed "Hello world" out. I then compiled an old program demonstrating fizzbuzz from my command line and ran that with no problem. I think I can assume my java is okay. I can create web applications that display a html welcome page on the tomcat server (localhost:8080/applicationContext/) however anything beyond that is where the problems start. – shirafuno Nov 24 '17 at 07:46
  • rather than putting servlet put index.jsp to display the current date in the application root folder and call that from deployed application. – Har Krishan Nov 24 '17 at 08:20
  • I created index.jsp and made it display Date.toString(). I "run on server" the index.jsp file which correctly displays the current date and time. Is this a step in the right direction to get JAX-RS working? – shirafuno Nov 24 '17 at 09:02
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/159739/discussion-between-har-krishan-and-shirafuno). – Har Krishan Nov 24 '17 at 09:11
0

If running as Spring Boot App or java application then use localhost:8080/testApplication/hitme and if running within war file then use localhost:8080/app_context/testApplication/hitme to access the service URI.

Here app_context is your application context.

Har Krishan
  • 273
  • 1
  • 11
  • I am calling http://localhost:8080/testApplication/hitme within STS "run on server" but no luck still "The origin server did not find a current representation for the target resource or is not willing to disclose that one exists." – shirafuno Nov 22 '17 at 06:47
  • Try adding @Consumes({ "application/json" }) annotation to @GET @Path("/hitme") @Produces({ "application/json" }) public Response getServerInfo(){ String message = "Hit the end point"; return Response.ok(message).build(); } } – Har Krishan Nov 22 '17 at 06:51
  • Are you using Eclipse? If yes then rt click on App.java and click Run As -> Java Application. Then invoke localhost:8080/testApplication/hitme. – Har Krishan Nov 22 '17 at 07:11
  • I right click run as -> java application and it asks to Select Java Application. I select "SpringApplication - org.springframework.boot" and it then gives me "java.lang.IllegalArgumentException: Sources must not be empty". I then selected "App - packagename.packagename" and it then boots up the application and shuts down straight away. Possible help ?= "Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@2473b9ce: startup date [Wed Nov 22 07:19:46 GMT 2017]; root of context hierarchy" – shirafuno Nov 22 '17 at 07:23
  • Rt. click on App.java not on the project and then run as java application or Spring Boot App – Har Krishan Nov 22 '17 at 08:35
  • I right click on App.java and run as -> Java application. Once again immediantly starts and stops. Here is my console output = https://pastebin.com/wnL0xNmY – shirafuno Nov 22 '17 at 08:45
  • Try to reorganize the classes first. Use com.resources package to put TestRestService.java and use com package to put App.java and then run App.java using rt. click. Here will be your package structure: com.App.java and com.resources.TestRestService.java – Har Krishan Nov 22 '17 at 08:56
  • I have created a com package and a com.resources package and put the files where you have requested them to be (com.App.java && com.resources.RestServiceTest.java). It still starts the application and then closes the AnnotationConfigApplicationContext. I have tried both run as -> Java Application and Spring Boot App but both still close the ApplicationContext. Any further help is much appreciated! Could I possibly be setting up my project wrong? I have the project facets set up with Dynamic Web Module, Java, Javascript and JAX-RS. – shirafuno Nov 22 '17 at 09:12
  • OK, need to run application with DEBUG logging level to know what Spring Boot is doing behind the scenes. You can control logging level using application.properties file. SpringApplication will load properties from application.properties files in the following locations and add them to the Spring Environment: 1. A /config subdirectory of the current directory. 2. The current directory 3. A classpath /config package 4. The classpath root In the application.properties file use the below line to run application with debug logging level. logging.level.=DEBUG Then rt. Click App and run – Har Krishan Nov 22 '17 at 09:22
  • I have an application.properties with a single line (logging.level.*=) in all 4 places yet no additional information is being provided when I run or debug java application with TRACE, DEBUG and ERROR levels set in all 4 of them. I'm sorry if this is very stressful. – shirafuno Nov 22 '17 at 10:37
  • The correct instruction was logging.level.ROOT=DEBUG. Here is the output. - https://pastebin.com/2B2L0v8G – shirafuno Nov 22 '17 at 11:01
  • please check if the dependency below: org.springframework.boot spring-boot-starter-web is present or not. If missing then add this. Forgot to mention if using gradle then use: dependencies { compile 'org.springframework.boot:spring-boot-starter-web' } – Har Krishan Nov 22 '17 at 11:23
  • it's in my pom and uses version 1.5.8. I use the maven pom config from https://spring.io/guides/gs/spring-boot/ for my spring build. – shirafuno Nov 22 '17 at 11:28
  • after starting app please hit the service URI as I saw the console output and looks like ApplicationContext didn't stop – Har Krishan Nov 22 '17 at 11:44
  • Unfortunately it does stop. the 10th line from the bottom. – shirafuno Nov 22 '17 at 11:50
  • Please share your pom.xml – Har Krishan Nov 22 '17 at 12:07
0

As you mentioned you are using Spring-boot then for the REST services go for RestController annotation.

    @RestController
    @RequestMapping("/restServiceTest")
    public class RestServiceTest {

      @RequestMapping(value = "/test", method = RequestMethod.GET)
       public @ResponseBody ResponseEntity<String> test() {
              return new ResponseEntity<String>("Success",HttpStatus.OK)
       }
     }

RestClass

Hope this help!!

Main class

  • Unfortunately I still get "The origin server did not find a current representation for the target resource or is not willing to disclose that one exists." – shirafuno Nov 22 '17 at 08:06
  • have you installed the sts plugin for eclipse, In spring boot no web.xml required. Use http://start.spring.io/ to generate spring boot project – Akash gupta Nov 22 '17 at 08:57
  • I am in sts with no web.xml. It was previously impending my ability to view my index.html page. – shirafuno Nov 22 '17 at 08:59
  • I have added two images, have a look. , create a new project with spring web dependency – Akash gupta Nov 22 '17 at 09:15
  • So I have implemented your work into a new project and I seem to be running into the same problem as explained in my post with Har Krishan. The application starts up and then immediantly shuts down again. here is my console output. - https://pastebin.com/zF27yhfe. – shirafuno Nov 22 '17 at 10:50
  • I added some logging to my post. although this is on the original project, i'm hoping any help you might have could find a solution to the problem --https://pastebin.com/2B2L0v8G – shirafuno Nov 22 '17 at 11:04
  • On console logs I could not find TomcatEmbeddedServletContainer initialized. Ideally Spring boot will use Tomcat as default for spring-boot-starter-web dependency. Please try adding below dependency to see if it works: org.springframework.boot spring-boot-starter-tomcat – Har Krishan Nov 22 '17 at 11:54
0

i'll try help are you using spring boot?

have u put the right dependency? should be like this:

<?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.test</groupId>
 <artifactId>test1</artifactId>
 <version>1.0.0</version>
 <packaging>war</packaging>

 <name>test1</name>
 <description>Project for test</description>

 <parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>1.5.8.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-tomcat</artifactId>
   <scope>provided</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>

and the controller should be like this:

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

  @RequestMapping(value = { "/api/hitme" }, method = { RequestMethod.GET },
      produces = { MediaType.APPLICATION_JSON_VALUE })
  public String test() throws Exception {
    // your code here
    return "I'M HIT!!";
  }

}

then define this in your application.yml in src/main/resources

server:
  port: 9999
  context-path: /test
  display-name: test-service

then just run as boot apps and try localhost:9999/test/api/hitme if you want to run it in a apache tomcat container, just run mvn clean install copy the war generated in /target and copy to webapps folder in tomcat. run, test and voila.

hope that helps.