ControllerとRestControllerの違い

ガイド springbootでは、ControllerとRestControllerがコントローラーに最も一般的に使用される2つのアノテーションですが、2つの違いを知っていますか?この記事は、2つの違いについてです。

1.コントローラーとRestControllerの共通点

どちらも、特定のクラスのSpringがHTTPリクエストを受信できるかどうかを示すために使用されます。

2.ControllerとRestControllerの違い

@Controller:SpringクラスがSpring MVCコントローラープロセッサであることを識別します。@ RestController:@RestControllerは@Controllerと@ResponseBodyの組み合わせであり、2つのアノテーションが組み合わされます。@Controllerクラスのメソッドは、Stringを返すことにより、jsp、ftl、htmlなどのテンプレートページに直接ジャンプできます。@ResponseBodyアノテーションをメソッドに追加します。エンティティオブジェクトを返すこともできます。@RestControllerクラスのすべてのメソッドは、String、Object、Jsonなどのエンティティオブジェクトのみを返すことができ、テンプレートページにジャンプすることはできません。Linuxはこのように学ぶ必要があります

@RestControllerのメソッドがページにジャンプする場合は、次のようにModelAndViewでカプセル化されます。

@RestController
public class UserController {

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

例は次のとおりです。

@Controller  
@ResponseBody  
public class MyController { }  

@RestController  
public class MyRestController { }  

@Controllerアノテーションのソースコード:

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アノテーションのソースコード:

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 "";
}

おすすめ

転載: blog.csdn.net/Linuxprobe18/article/details/113103223