You return an object from a @Controller and get “Error resolving template.” You return a String and it doesn’t come back as JSON. You call the endpoint with curl and get a 406. Almost everyone runs into all three of these early on with Spring MVC.

If you understand @ResponseBody and the HttpMessageConverter that works behind it, you can quickly tell these problems apart. Here’s the short version:

  • @ResponseBody tells Spring: “Don’t treat the return value as a view name. Write it to the response body with an HttpMessageConverter.”
  • @RestController is @Controller with @ResponseBody added.

Everything here was tested with Spring Boot 3.5.x (Spring Framework 6.2.x) on Java 21. Where Spring Boot 4 behaves differently, I point it out in that section.

What Changes With and Without @ResponseBody

@ResponseBody (org.springframework.web.bind.annotation.ResponseBody) is an annotation you put on a method or a class. Whether it’s there or not changes how the return value is handled.

Without @ResponseBody (@Controller)With @ResponseBody
How the return value is treatedView name (template name)The response body itself
Mechanism usedViewResolverHttpMessageConverter
Typical usePages (Thymeleaf, etc.)REST API

If you return "hello", it means “find a template named hello” without the annotation, and “send back the string hello” with it.

@RestController Is @Controller Plus @ResponseBody

The source of @RestController shows how the two are related:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {

    @AliasFor(annotation = Controller.class)
    String value() default "";
}

@Controller and @ResponseBody are both there as meta-annotations. Putting @ResponseBody on a class is the same as putting it on every method, so “@Controller + @ResponseBody on the class” behaves exactly like @RestController. For new code, @RestController is all you need.

Jackson, which handles the JSON conversion, comes with spring-boot-starter-web. I cover what’s inside the starter in What is spring-boot-starter-web?.

Method Level or Class Level?

If a class only serves an API, just use @RestController.

It gets trickier when one @Controller has both Thymeleaf page methods and methods that return JSON. In that case, put @ResponseBody only on the methods that return JSON (fields and similar code are left out):

@Controller
public class TodoController {

    @GetMapping("/todos")
    public String list(Model model) {
        model.addAttribute("todos", todoService.findAll());
        return "todos/list"; // テンプレート名として扱われる
    }

    @GetMapping("/api/todos")
    @ResponseBody
    public List<Todo> listApi() {
        return todoService.findAll(); // JSONとして返る
    }
}

This works, but the code is easier to read later if pages and APIs live in separate classes. URL mapping is covered in the @RequestMapping article, so I’ll skip it here.

How a Return Value Becomes JSON

Here’s a rough outline of what happens inside Spring:

  1. The return value of a method with @ResponseBody goes to RequestResponseBodyMethodProcessor. Without the annotation, handlers such as ViewNameMethodReturnValueHandler treat it as a view name.
  2. Spring uses the Accept header and produces to decide which media types it can return.
  3. Spring goes through the HttpMessageConverters in registration order and looks for one that can write both the return type and the media type.
  4. The first matching converter writes the body.

The key part is “the first matching converter” in step 4. This ordering is what causes the “returning a String doesn’t give you JSON” problem covered later.

Default Order of HttpMessageConverters

These are the main converters registered by WebMvcConfigurationSupport#addDefaultHttpMessageConverters, in order:

OrderConverterType handledMain Content-Type
1ByteArrayHttpMessageConverterbyte[]application/octet-stream
2StringHttpMessageConverterStringtext/plain
3ResourceHttpMessageConverterResourceDetermined by the file
4ResourceRegionHttpMessageConverterResourceRegionDetermined by the file
5AllEncompassingFormHttpMessageConverterMultiValueMapapplication/x-www-form-urlencoded
6MappingJackson2HttpMessageConverterAny objectapplication/json

The important point is that Jackson comes after String.

Spring Boot also adds converters of its own, such as a StringHttpMessageConverter that defaults to UTF-8, so the same type can appear twice. The most reliable way to see the actual order is to log it at startup:

@Component
public class ConverterLogger implements ApplicationRunner {

    private static final Logger log = LoggerFactory.getLogger(ConverterLogger.class);
    private final RequestMappingHandlerAdapter adapter;

    public ConverterLogger(RequestMappingHandlerAdapter adapter) {
        this.adapter = adapter;
    }

    @Override
    public void run(ApplicationArguments args) {
        adapter.getMessageConverters()
               .forEach(c -> log.info(c.getClass().getSimpleName()));
    }
}

Spring Boot 4 (Spring Framework 7) uses Jackson 3 by default. Packages such as databind move from com.fasterxml.jackson to tools.jackson, and the converter becomes JacksonJsonHttpMessageConverter. The name in the log changes, but the converter does the same job.

For settings like date formats and leaving out nulls, see the Jackson configuration article.

Mistake 1: Forgetting @ResponseBody, So the Value Becomes a View Name

This is the most common one. You meant to write @RestController but wrote @Controller:

@Controller
public class HelloController {

    @GetMapping("/hello")
    public String hello() {
        return "hello";
    }
}

If Thymeleaf is on the classpath, Spring looks for a template named hello and returns a 500. Without Thymeleaf, the view name matches the URL, so Spring tries to forward the request back to the same handler and fails:

# Thymeleafあり
org.thymeleaf.exceptions.TemplateInputException: Error resolving template [hello], template might not exist or might not be accessible by any of the configured Template Resolvers

# Thymeleafなし
jakarta.servlet.ServletException: Circular view path [hello]: would dispatch back to the current handler URL [/hello] again. Check your ViewResolvers setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)

Without Thymeleaf, if the returned name doesn’t match the URL, the request is forwarded to a path with that name and you get a 404. The cause is the same in every case: the return value is being treated as a view name.

To fix it, add @ResponseBody to the method or change the class to @RestController. After the fix, the string comes back as-is (some headers omitted):

$ curl -i http://localhost:8080/hello
HTTP/1.1 200
Content-Type: text/plain;charset=UTF-8

hello

Mistake 2: Getting 406 Not Acceptable

Next, here’s what happens when a client asks for XML from an endpoint that returns an object:

public record Greeting(String message) {}

@RestController
public class GreetingController {

    @GetMapping("/greeting")
    public Greeting greeting() {
        return new Greeting("ok");
    }
}
$ curl -i -H 'Accept: application/xml' http://localhost:8080/greeting
HTTP/1.1 406

The log shows this (excerpt):

DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpMediaTypeNotAcceptableException: No acceptable representation]

Jackson can only write JSON, so when the client asks for XML, no converter can produce it. You also get a 406 when a request’s Accept header doesn’t match a method that declares produces = "application/json".

If you remove Jackson entirely, you get a 500 instead of a 406:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-json</artifactId>
        </exclusion>
    </exclusions>
</dependency>

With this setup, returning an object throws HttpMessageNotWritableException: No converter found for return value of type: class com.example.demo.Greeting. This time there’s no converter that can write the object at all.

To fix it, do one of the following: set the client’s Accept header to application/json, review your produces setting, or add back the Jackson dependency you excluded.

Mistake 3: Returning a String Doesn’t Give You JSON

Have you ever written something like this, expecting a JSON-looking string to come back as JSON?

@GetMapping("/status")
public String status() {
    return "{\"message\":\"ok\"}";
}
$ curl -i http://localhost:8080/status
HTTP/1.1 200
Content-Type: text/plain;charset=UTF-8

{"message":"ok"}

The body looks like JSON, but the Content-Type is text/plain. StringHttpMessageConverter comes before Jackson in the order, so it writes String values.

For the same reason, return "ok"; won’t be turned into the JSON string "ok" by Jackson. People get this wrong a lot.

If you want JSON, return an object such as a record or a Map:

@GetMapping("/status")
public Map<String, String> status() {
    return Map.of("message", "ok"); // application/json になる
}

// どうしても文字列のJSONを返すなら produces を指定する
@GetMapping(value = "/status-raw", produces = MediaType.APPLICATION_JSON_VALUE)
public String statusRaw() {
    return "{\"message\":\"ok\"}";
}

The version with produces returns a Content-Type of application/json, but StringHttpMessageConverter still writes the body. Only the header changes, so it’s up to you to make sure the string is valid JSON. Returning an object is the safer choice in most cases.

How ResponseEntity Fits In

If you return a ResponseEntity, it’s written as the response body even without @ResponseBody, because HttpEntityMethodProcessor handles it.

The rule is simple: if you only need to return a body, return the value from a @RestController. If you also need to set the status or headers, use ResponseEntity.

@PostMapping("/todos")
public ResponseEntity<Todo> create(@RequestBody TodoRequest request) {
    Todo saved = todoService.create(request);
    return ResponseEntity
            .created(URI.create("/todos/" + saved.id()))
            .body(saved); // 201 + Locationヘッダー
}

For when to use @ResponseStatus or ResponseStatusException instead, see the @ResponseStatus article.

Checking the Content-Type With MockMvc

Finally, let’s check these differences with tests. The examples assume /status (the String version) is also in GreetingController.

@WebMvcTest(GreetingController.class)
class GreetingControllerTest {

    @Autowired
    MockMvc mockMvc;

    @Test
    void オブジェクトはJSONで返る() throws Exception {
        mockMvc.perform(get("/greeting"))
               .andExpect(status().isOk())
               .andExpect(content().contentType(MediaType.APPLICATION_JSON))
               .andExpect(jsonPath("$.message").value("ok"));
    }

    @Test
    void Stringはtext_plainで返る() throws Exception {
        mockMvc.perform(get("/status"))
               .andExpect(content().contentTypeCompatibleWith(MediaType.TEXT_PLAIN));
    }

    @Test
    void XMLを要求すると406() throws Exception {
        mockMvc.perform(get("/greeting").accept(MediaType.APPLICATION_XML))
               .andExpect(status().isNotAcceptable());
    }
}

If your tests also check the Content-Type, you’ll catch a missing @ResponseBody or an accidental String return right away. In Spring Boot 4, @WebMvcTest moves to the org.springframework.boot.webmvc.test.autoconfigure package, so update your imports. For more on writing MockMvc tests, see the article on testing controllers with MockMvc.

Summary

Here’s how each symptom maps to its cause:

SymptomCause
Template error, Circular view pathMissing @ResponseBody
406 Not AcceptableAccept or produces doesn’t match any available converter
Returned as a plain string (text/plain)The return type is String, so StringHttpMessageConverter is used

@RestController is @Controller + @ResponseBody, and the converter order decides how a return value gets written. Remember those two things and you should be able to track down most of these problems yourself.

To control the shape of your JSON, see the Jackson configuration article. To see what the starter pulls in, see the spring-boot-starter-web article.