The difference between Controller and RestController

Guide In springboot, Controller and RestController are the two most commonly used annotations for controllers, but do you know the difference between the two? This article is about the difference between the two.

1. Common Points of Controller and RestController

Both are used to indicate whether a certain class of Spring can receive HTTP requests.

2. The difference between Controller and RestController

@Controller: Identifies that a Spring class is a Spring MVC controller processor, @RestController: @RestController is a combination of @Controller and @ResponseBody, the two annotations are combined. The methods in the @Controller class can directly jump to template pages such as jsp, ftl, html, etc. by returning String. Add @ResponseBody annotation to the method, you can also return the entity object. All methods in the @RestController class can only return entity objects such as String, Object, Json, etc., and cannot jump to the template page. Linux should be learned like this

If the method in @RestController wants to jump to the page, it is encapsulated with ModelAndView, as follows:

@RestController
public class UserController {

    @RequestMapping(value = "/index",method = RequestMethod.GET)
    public String toIndex(){
        ModelAndView mv = new ModelAndView("index");
      	return mv;    
    }
}
 

Examples are as follows:

@Controller  
@ResponseBody  
public class MyController { }  

@RestController  
public class MyRestController { }  

@Controller annotation source code:

package org.springframework.stereotype;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.stereotype.Component;

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Controller {
    String value() default "";
}

@RestController annotation source code:

package org.springframework.web.bind.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {
    String value() default "";
}

Guess you like

Origin blog.csdn.net/Linuxprobe18/article/details/113103223