为什么Spring文档并不完美

时间:2017-07-22 16:52:17

标签: java spring-mvc

嘿,我正在尝试使用maven构建简单的hello world spring web应用程序。

当我转到网址http://localhost:8080/mvc/greeting时,它会给我404.

这是我的pom

http://maven.apache.org/xsd/maven-4.0.0.xsd">     4.0.0

<groupId>com.ilyas.learning.mvcspring</groupId>
<artifactId>mvc</artifactId>
<version>1.0.0</version>
<packaging>war</packaging>

<name>mvc</name>

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

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot</artifactId>
        <version>1.5.4.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>4.3.9.RELEASE</version>
        <type>jar</type>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <artifactId>maven-war-plugin</artifactId>
            <configuration>
                <failOnMissingWebXml>false</failOnMissingWebXml>
            </configuration>
            <version>3.1.0</version>
        </plugin>
    </plugins>
</build>

这里是Greeting class

@Controller 公共类GreetingController {

@RequestMapping(value = "/greeting", method=RequestMethod.GET)
public String greeting(@RequestParam(value = "name", defaultValue = "World") String name){
    return "Hello " + name;
}

}

这是Main class。

public class Main扩展了SpringBootServletInitializer {

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
    return application.sources(Main.class);
}

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

}

2 个答案:

答案 0 :(得分:3)

您没有发送RequestParam值,您需要将其标记为required=false 所以你的方法将

public String greeting(@RequestParam(value = "name", required=false, defaultValue = "World") String name){

答案 1 :(得分:-1)

您需要在公共课@RequestMapping之前添加GreetingController注释。你可以参考下面的示例代码:

@Controller 
@RequestMapping("/mvc")
public class GreetingController {

    @RequestMapping(value = "/greeting", method = RequestMethod.POST, produces = "application/json", consumes = "application/json")
    public String greeting(@RequestParam(value = "name", defaultValue = "World") String name){

 //do things

    }

}

如果您创建了休息服务,则可以尝试在@RestController使用@Controller