1

I created a simple RestController, using Spring (not Boot).

@RestController
@RequestMapping(UserRestController.REST_URL)
public class UserRestController extends AbstractUserController {

    static final String REST_URL = "/users";

    @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
    public User get(int id) {
      return super.get(id);
  }
}

But when I invoke this method and use curl I receive:

$ curl -v http://localhost:8080/users
Trying 127.0.0.1...
TCP_NODELAY set
connect to 127.0.0.1 port 8080 failed: Connection refused
Failed to connect to localhost port 8080: Connection refused

Additionally: I push MocMvc-test and it failed with following result:

java.lang.AssertionError: Status expected:<200> but was:<404>
  Expected :200
  Actual   :404

I run my app with:

public static void main(String[] args) {

try (ConfigurableApplicationContext appCtx = new 
ClassPathXmlApplicationContext("spring/spring-app.xml")) {
 System.out.println("Bean definition names: " + 
  Arrays.toString(appCtx.getBeanDefinitionNames()));
UserRestController userRestController = 
  appCtx.getBean(UserRestController.class);
        System.out.println(userRestController.get(2));
    }
}

In the console I see the output of System.out.println(userRestController.get(2)); So my CRUD-methods works good.

JuanMoreno
  • 2,498
  • 1
  • 25
  • 34
Jelly
  • 972
  • 1
  • 17
  • 40

1 Answers1

1

In order to attend an HTTP request with Spring without using Spring Boot, you need typically the following:

  1. Use spring-webmvc dependency. I understood that you already have.
  2. Package your application as a war. If you build with maven, you need to add the <packaging>war</packaging> sentence in your pom.xml
  3. In your web.xml declare the org.springframework.web.servlet.DispatcherServlet. You can also use the org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer to register it.
  4. Define the mappings and configuration in your application-context file or class if you use java-config.
  5. Deploy your war file in a Servlet container like Tomcat or Jetty.

I put an example with Spring 5 here.

You can found another example with Spring 4 here.

JuanMoreno
  • 2,498
  • 1
  • 25
  • 34