簡體   English   中英

使用Spring Boot創建RESTful Web服務

[英]Creating a RESTful web service with Spring Boot

我正在使用Spring Boot學習RESTful Web服務。 我正在嘗試創建一個獲取特定客戶端地址的Web服務,但是當我嘗試運行該服務時,卻不斷出現以下錯誤:

白標錯誤頁面

此應用程序沒有針對/ error的顯式映射,因此您將其視為后備。

Sun Jan 03 11:20:44 CST 2016有一個意外錯誤(類型=未找到,狀態= 404)。 無訊息

我嘗試訪問的URL是

http:// localhost:8084 / showAddress

有人可以告訴我我要去哪里錯了。 我從朋友的github帳戶下載了一個類似的項目,它運行正常。 為了簡單起見,我嘗試對值進行硬編碼,並在控制器類中創建以下代碼:

package com.digitek.controller;

import java.math.BigInteger;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

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.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.example.model.Address;


@RestController
public class Controller {

    private static BigInteger id;
    private static Map<BigInteger, Address> addressMap;
    //saves address objects into HashMap
    private static void SaveAddress(Address address){
        //instantiate hashmap when id is null
        if(id == null){
            id = BigInteger.ONE;
            addressMap = new HashMap<BigInteger,Address>();
        }
        address.setId(id);
        id.add(BigInteger.ONE);
        addressMap.put(address.getId(), address);
    }

    static{
        Address a1 = new Address();
        a1.setAddress("29 East Judith Ann Drive");
        SaveAddress(a1);

        Address a2 = new Address();
        a1.setAddress("2 East Judith Ann Drive");
        SaveAddress(a2);
    }

    @RequestMapping(value = "/showAddress" ,method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Collection<Address>> showMessage(){
        Collection<Address> address = addressMap.values();
        return new ResponseEntity<Collection<Address>>(address , HttpStatus.OK);

    }



}

這是我的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>AddressService</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>AddressService</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <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>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

這是控制台日志

    2016-01-03 11:09:30.359  INFO 6028 --- [           main] com.example.AddressServiceApplication    : Starting AddressServiceApplication on Rishit with PID 6028 (started by Rishit Shah in D:\Rishit\Java workspaces\AddressService) 
2016-01-03 11:09:30.364  INFO 6028 --- [           main] com.example.AddressServiceApplication    : No active profile set, falling back to default profiles: default 
2016-01-03 11:09:30.449  INFO 6028 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@33cb5951: startup date [Sun Jan 03 11:09:30 CST 2016]; root of context hierarchy 2016-01-03 11:09:31.655  INFO 6028 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'beanNameViewResolver' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter.class]] 
2016-01-03 11:09:32.792  INFO 6028 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8084 (http) 
2016-01-03 11:09:32.814  INFO 6028 --- [          main] o.apache.catalina.core.StandardService   : Starting service Tomcat 2016-01-03 11:09:32.816  INFO 6028 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.0.30 2016-01-03 11:09:32.965  INFO 6028 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext 2016-01-03 11:09:32.965  INFO 6028 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 2521 ms 
2016-01-03 11:09:33.628  INFO 6028
    --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean        : Mapping servlet: 'dispatcherServlet' to [/] 
2016-01-03 11:09:33.637  INFO 6028 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'characterEncodingFilter' to: [/*] 
2016-01-03 11:09:33.639  INFO 6028
    --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'hiddenHttpMethodFilter' to: [/*] 
2016-01-03 11:09:33.639  INFO 6028 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'httpPutFormContentFilter' to: [/*]
 2016-01-03 11:09:33.639  INFO 6028
    --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'requestContextFilter' to: [/*]
 2016-01-03 11:09:34.221  INFO 6028 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@33cb5951: startup date [Sun Jan 03 11:09:30 CST 2016]; root of context hierarchy 2016-01-03 11:09:34.315  INFO 6028 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
 2016-01-03 11:09:34.317  INFO 6028 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
 2016-01-03 11:09:34.371  INFO 6028 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
 2016-01-03 11:09:34.371  INFO 6028 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] 2016-01-03 11:09:34.421  INFO 6028 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] 2016-01-03 11:09:34.588  INFO 6028 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup 
2016-01-03 11:09:34.753  INFO 6028 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8084 (http) 
2016-01-03 11:09:34.764  INFO 6028 --- [          main] com.example.AddressServiceApplication    : Started AddressServiceApplication in 4.867 seconds (JVM running for 5.705) 
2016-01-03 11:10:03.737  INFO 6028 --- [nio-8084-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring FrameworkServlet 'dispatcherServlet' 2016-01-03 11:10:03.737  INFO 6028 --- [nio-8084-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization started 2016-01-03 11:10:03.759  INFO 6028 --- [nio-8084-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization completed in 22 ms

PS我嘗試在不同端口上運行該應用程序,嘗試刪除並重新創建它,還嘗試運行我從我的朋友創建的github下載的類似應用程序。 每次他的應用程序有效但我的無效。 我還確保pom文件的每個和元素都匹配。 先感謝您

確保主類位於其他類之上的根包中。

當您運行Spring Boot Application(即用@SpringBootApplication注釋的類)時,Spring將僅掃描主類包下方的類。

  com
   +- digitek
         +- Application.java  <--- your main class should be here, above your controller classes
         |
         +- model
         |   +- Address.java
         +- controller
             +- AddressController.java

您遇到的問題是Spring無法找到您創建的控制器,因為您將其放置在了Spring尚未掃描的目錄中。

文檔中有一章介紹了如何使用Spring Boot構造代碼

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM