Java – Spring boot uses @PathVariable to report 404 errors

Spring boot uses @PathVariable to report 404 errors… here is a solution to the problem.

Spring boot uses @PathVariable to report 404 errors

I’m a beginner with Spring Boot.

I just wrote a Controller, the code is here.

package hello;

import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.stereotype.*;
import org.springframework.web.bind.annotation.*;

@Controller
@EnableAutoConfiguration
public class SampleController {

@RequestMapping("/")
    @ResponseBody
    String home() {
        return "Hello Name!";
    }

@RequestMapping(value = "/hello/{name}", method = RequestMethod.GET)
    String hello(@PathVariable String name) {
        return "hello " + name;
    }

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

Then when I visit “localhost:8080”, I get the right page.
But when I visit “localhost:8080/hello/someName,” I get “Whitelabel Error Page.”

What’s wrong with my code? Thank you so much.

Solution

Try @PathVariable("name") the string name. And use the @ResponseBody comment in the hello method.

@ResponseBody
@RequestMapping(value = "/hello/{name}", method = RequestMethod.GET)
    String hello(@PathVariable("name") String name) {
        return "hello " + name;
    }

Related Problems and Solutions