web-dev-qa-db-fra.com

création de services de repos de printemps sans utiliser de botte de printemps

J'ai suivi le didacticiel Mise en route sur spring.io pour la création de services REEST https://spring.io/guides/gs/rest-service/ . Le problème est que ce didacticiel explique uniquement comment créer un fichier jar autonome avec Tomcat intégré à l'aide de Spring Boot.

Existe-t-il un moyen de créer un projet à partir de rien pour produire une guerre à déployer par exemple sur une instance Tomcat déjà existante?

PS: J'avais trouvé un fil précédent Spring RESTful Service en tant que fichier WAR au lieu de JAR dans Tomcat sur stackoverflow concernant le même problème. Le problème est que les réponses et suggestions acceptées ne résolvent pas exactement mon problème, car je ne cherche pas à modifier le projet de démarrage autonome de l'application autonome afin qu'il fonctionne sur un conteneur Tomcat externe, mais j'aimerais trouver un solution 'plus propre' ne comportant pas de botte à ressort. (Je ne sais pas exactement comment se comporter ici, étant encore assez nouveau en stackoverflow. J'espère qu'ouvrir une nouvelle question constitue la procédure correcte).

63
chrx

Vous n'avez pas besoin de Spring Boot pour créer un contrôleur de repos.

Veuillez suivre la documentation du framework Spring sur la configuration de MVC https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#spring-web

La configuration de MVC (le DispatcherServlet) dépend de votre version de printemps, vous pouvez utiliser xml ou vous pouvez configurer par programme: https://docs.spring.io/spring/docs/current/spring -framework-reference/web.html # mvc-servlet

Une fois que cela est configuré, vous pouvez ajouter un contrôleur de repos à votre application. Notez qu'un contrôleur de repos (le @RestController annotation) est une annotation stéréotypée combinant @ResponseBody et @Controller, autrement dit, le contrôleur renvoie un objet dans le corps de la réponse au lieu de retourner une vue.

Ceci est un exemple parfait expliquant ce que j'ai dit ci-dessus: http://www.programming-free.com/2014/01/spring-mvc-40-restful-web-services.html

56
selvinsource

Voici un autre exemple:

Structure du répertoire:

.
├── ./pom.xml
└── ./src
    └── ./src/main
        ├── ./src/main/Java
        │   └── ./src/main/Java/biz
        │       └── ./src/main/Java/biz/tugay
        │           └── ./src/main/Java/biz/tugay/restfulspring
        │               └── ./src/main/Java/biz/tugay/restfulspring/config
        │                   ├── ./src/main/Java/biz/tugay/restfulspring/config/RestfulHello.Java
        │                   └── ./src/main/Java/biz/tugay/restfulspring/config/WebAppInitalizer.Java
        └── ./src/main/webapp
            └── ./src/main/webapp/WEB-INF
                └── ./src/main/webapp/WEB-INF/web.xml

pom.xml

<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/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <groupId>biz.tugay</groupId>
    <artifactId>restfulSpring</artifactId>

    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>restfulSpring Maven Webapp</name>

    <url>http://maven.Apache.org</url>

    <dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>4.3.16.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.16.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>4.3.16.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.16.RELEASE</version>
        </dependency>
    </dependencies>

    <build>
        <finalName>restfulSpring</finalName>
        <plugins>
            <plugin>
                <groupId>org.Apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.Eclipse.jetty</groupId>
                <artifactId>jetty-maven-plugin</artifactId>
                <version>9.2.1.v20140609</version>
            </plugin>
        </plugins>
    </build>

</project>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://Java.Sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://Java.Sun.com/xml/ns/javaee
                             http://Java.Sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">
</web-app>

WebAppInitalizer.Java

package biz.tugay.restfulspring.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

@Configuration
@EnableWebMvc
@ComponentScan("biz.tugay.restfulspring")
public class WebAppInitalizer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected String[] getServletMappings() {
        return new String[]{"/*"};
    }

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class<?>[]{WebAppInitalizer.class};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[0];
    }
}

RestfulHello.Java

package biz.tugay.restfulspring.config;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = "/")
public class RestfulHello {

    @RequestMapping(value = "hello")
    public ResponseEntity<String> sayHello() {
        final HttpHeaders httpHeaders= new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        return new ResponseEntity<String>("{\"msg\": \"Hello World\"}", httpHeaders, HttpStatus.OK);
    }
}

Construire et exécuter:

mvn clean install
mvn jetty:start

Tester:

> GET /hello HTTP/1.1
> Host: localhost:8080
> User-Agent: insomnia/5.15.0
> Accept: */*
< HTTP/1.1 200 OK
< Date: Fri, 27 Apr 2018 00:06:07 GMT
< Content-Type: application/json
< Content-Length: 22
< Server: Jetty(9.2.1.v20140609)

Contenu reçu:

{
    "msg": "Hello World"
}
8
Koray Tugay