GVKun编程网logo

使用ResponseEntity时 和@RestController用于Spring RESTful应用程序(response.setcontenttype()的作用)

24

此处将为大家介绍关于使用ResponseEntity时和@RestController用于SpringRESTful应用程序的详细内容,并且为您解答有关response.setcontenttype(

此处将为大家介绍关于使用ResponseEntity时 和@RestController用于Spring RESTful应用程序的详细内容,并且为您解答有关response.setcontenttype()的作用的相关问题,此外,我们还将为您介绍关于3.7、@ResponseBody 和 @RestController、@Controller,@ResponseBody,@RestController,@RequestMapping,@GetMapping作用、@ResponseBody和@RestController、@ResponseBody和@RestController的区别的有用信息。

本文目录一览:

使用ResponseEntity时 和@RestController用于Spring RESTful应用程序(response.setcontenttype()的作用)

使用ResponseEntity时 和@RestController用于Spring RESTful应用程序(response.setcontenttype()的作用)

我正在使用Spring Framework 4.0.7,MVC和Rest

我可以在以下方面安心工作:

  • @Controller
  • ResponseEntity<T>

例如:

@Controller@RequestMapping("/person")@Profile("responseentity")public class PersonRestResponseEntityController {

用的方法(只是创建)

@RequestMapping(value="/", method=RequestMethod.POST)public ResponseEntity<Void> createPerson(@RequestBody Person person, UriComponentsBuilder ucb){    logger.info("PersonRestResponseEntityController  - createPerson");    if(person==null)        logger.error("person is null!!!");    else        logger.info("{}", person.toString());    personMapRepository.savePerson(person);    HttpHeaders headers = new HttpHeaders();    headers.add("1", "uno");    //http://localhost:8080/spring-utility/person/1    headers.setLocation(ucb.path("/person/{id}").buildAndExpand(person.getId()).toUri());    return new ResponseEntity<>(headers, HttpStatus.CREATED);}

退还一些东西

@RequestMapping(value="/{id}", method=RequestMethod.GET)public ResponseEntity<Person> getPerson(@PathVariable Integer id){    logger.info("PersonRestResponseEntityController  - getPerson - id: {}", id);    Person person = personMapRepository.findPerson(id);    return new ResponseEntity<>(person, HttpStatus.FOUND);}

工作良好

我可以用

  • @RestController(我知道它与@Controller+ 相同@ResponseBody
  • @ResponseStatus

例如:

@RestController@RequestMapping("/person")@Profile("restcontroller")public class PersonRestController {

用的方法(只是创建)

@RequestMapping(value="/", method=RequestMethod.POST)@ResponseStatus(HttpStatus.CREATED)public void createPerson(@RequestBody Person person, HttpServletRequest request, HttpServletResponse response){    logger.info("PersonRestController  - createPerson");    if(person==null)        logger.error("person is null!!!");    else        logger.info("{}", person.toString());    personMapRepository.savePerson(person);    response.setHeader("1", "uno");    //http://localhost:8080/spring-utility/person/1    response.setHeader("Location", request.getRequestURL().append(person.getId()).toString());}

退还一些东西

@RequestMapping(value="/{id}", method=RequestMethod.GET)@ResponseStatus(HttpStatus.FOUND)public Person getPerson(@PathVariable Integer id){    logger.info("PersonRestController  - getPerson - id: {}", id);    Person person = personMapRepository.findPerson(id);    return person;}

我的问题是:

  1. 如果 出于确凿的原因特定情况, 必须强制使用另一种选择
  2. 如果(1)无关紧要,则建议采用什么方法以及为什么。

答案1

小编典典

ResponseEntity旨在表示整个HTTP响应。您可以控制其中的所有内容:状态码,标头和正文。

@ResponseBody是HTTP响应正文的标记,并@ResponseStatus声明HTTP响应的状态代码。

@ResponseStatus不是很灵活。它标记了整个方法,因此您必须确保您的处理程序方法始终具有相同的行为。而且您仍然无法设置标题。您需要HttpServletResponseHttpHeaders参数。

基本上,ResponseEntity您可以执行更多操作。

3.7、@ResponseBody 和 @RestController

3.7、@ResponseBody 和 @RestController

  本部分示例代码见此项目的 mvc 分支下的 RespBodyController.java 和 TheRestController.java


① 使用注解@ResponseBody映射响应体

  注解@ResponseBody@RequestBody很像。这个注解可以放到一个方法中,指示返回类型应该直接被写进HTTP响应体中(而不是放到一个Model中、也不是翻译为一个视图名)。例如:

@GetMapping("/something")
@ResponseBody
public String helloWorld() { return "Hello World"; }

  上面的示例会返回文本 “Hello World”,并把它写到HTTP响应流中。

  就像@RequestBody,Spring 使用HttpMessageConverter把返回的对象转换到请求体中。更多关于这些转换器的消息,参见消息转换器.

② 使用注解@RestController创建 REST 控制器

  一个非常常见的场景是让控制器实现 REST API,因此只服务于 JSON、XML 或者自定义的 MediaType 内容。为了方便,避免在所有的@RequestMapping方法上加上@ResponseBody注解,你可以用@RestController注解你的控制器类.

  @RestController 是一个模板注解,它合并了@ResponseBody@Controller。不仅如此,它还为你的控制器赋予了更多的意义,在未来的发行版本中也将包含更多语义。

  就像常规的@Controllers@RestController可以由@ControllerAdvice或者@RestControllerAdvice Bean 协助。详情见用 @ControllerAdvice 和 @RestControllerAdvice 通知控制器”一节

@Controller,@ResponseBody,@RestController,@RequestMapping,@GetMapping作用

@Controller,@ResponseBody,@RestController,@RequestMapping,@GetMapping作用

1,@Controller 处理http请求,作用在类上:
  • 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;
  • @Target({ElementType.TYPE})
  • @Retention(RetentionPolicy.RUNTIME)
  • @Documented
  • @Component
  • public @interface Controller {
  • String value() default "";
  • }
  • 2,@ResponseBody 返回JSON格式的数据,作用在类上或方法上:
  • 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;
  • @Target({ElementType.TYPE, ElementType.METHOD})
  • @Retention(RetentionPolicy.RUNTIME)
  • @Documented
  • public @interface ResponseBody {
  • }
  • 3,@RestController=@ResponseBody + @Controller ,作用在类上:
  • 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;
  • @Target({ElementType.TYPE})
  • @Retention(RetentionPolicy.RUNTIME)
  • @Documented
  • @Controller
  • @ResponseBody
  • public @interface RestController {
  • String value() default "";
  • }
  • 4,@RequestMapping 配置url映射,作用在类上或方法上:
  • 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.core.annotation.AliasFor;
  • @Target({ElementType.METHOD, ElementType.TYPE})
  • @Retention(RetentionPolicy.RUNTIME)
  • @Documented
  • @Mapping
  • public @interface RequestMapping {
  • String name() default "";
  • @AliasFor("path")
  • String[] value() default {};
  • @AliasFor("value")
  • String[] path() default {};
  • RequestMethod[] method() default {};
  • String[] params() default {};
  • String[] headers() default {};
  • String[] consumes() default {};
  • String[] produces() default {};
  • }
  • 5, @GetMapping是一个组合注解,是@RequestMapping(method = RequestMethod.GET)的缩写。
  • 该注解将HTTP Get 映射到 特定的处理方法上。
  • 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.core.annotation.AliasFor;
  • @Target({ElementType.METHOD})
  • @Retention(RetentionPolicy.RUNTIME)
  • @Documented
  • @RequestMapping(
  • method = {RequestMethod.GET}
  • )
  • public @interface GetMapping {
  • @AliasFor(
  • annotation = RequestMapping.class
  • )
  • String name() default "";
  • @AliasFor(
  • annotation = RequestMapping.class
  • )
  • String[] value() default {};
  • @AliasFor(
  • annotation = RequestMapping.class
  • )
  • String[] path() default {};
  • @AliasFor(
  • annotation = RequestMapping.class
  • )
  • String[] params() default {};
  • @AliasFor(
  • annotation = RequestMapping.class
  • )
  • String[] headers() default {};
  • @AliasFor(
  • annotation = RequestMapping.class
  • )
  • String[] consumes() default {};
  • @AliasFor(
  • annotation = RequestMapping.class
  • )
  • String[] produces() default {};
  • }
  • 6,@RequestBody 注解则是使用 HttpMessageConverter 将 HTTP 请求正文写入某个对象。多用于post请求(insert数据时)

    7,@RequestParam 是从request里面取请求参数,而 @PathVariable 是从一个URI模板里面来取值


    关于6、7更多请见:

    https://blog.csdn.net/u010002184/article/details/80386322

    https://blog.csdn.net/ff906317011/article/details/78552426

    https://blog.csdn.net/walkerjong/article/details/7946109

    http://www.cnblogs.com/liaojie970/p/8591759.html

    https://blog.csdn.net/jiangyu1013/article/details/72627352

    @ResponseBody和@RestController

    @ResponseBody和@RestController

    Spring 关于ResponseBody注解的作用

    responseBody一般是作用在方法上的,加上该注解表示该方法的返回结果直接写到Http response Body中,常用在ajax异步请求中,

    在RequestMapping中 return返回值默认解析为跳转路径,如果你此时想让Controller返回一个字符串或者对象到前台 就会报404 not response的错误。

    当加上@ResponseBody注解后不会解析成跳转地址 会解析成相应的json格式的对象 集合 字符串或者xml等直接返回给前台 可以通过 ajax 的“success”:fucntion(data){} data直接获取到。

    下面是返回json格式的字符串

      @RequestMapping("/register")
      @ResponseBody  
      public String register(TestUserInfo testUserInfo,String username) throws Exception{
          if(testUserService.findByUserName(username)==null){
              testUserService.addTestUser(testUserInfo);
              return "success";
          }else{
              return "fail";
          }
      }

      下面是页面跳转

    @RequestMapping("/upload/condition")
        public String search(Model model) {
            List<ArchiveCategory> allArchiveCategory = archiveCategoryApi.getAllCategories();
            List<ArchiveCategory> topLevelCategory = allArchiveCategory.stream().filter(category -> category.getParentid() == 0 || "视频".equals(category.getName())).collect(Collectors.toList());
            model.addAttribute("archiveCategories", topLevelCategory);
            return "beike/upload-pop-condition";
        }

      

     

    注册验证: 希望返回给前台 一个json字符串 来表示 注册是否成功 而不是 跳转路径  所以此处 方法 加上 @ResponseBody注解 避免被解析成跳转路径

     

      @ResponseBody,一般是使用在单独的方法上的,需要哪个方法返回json数据格式,就在哪个方法上使用,具有针对性。

      @RestController,一般是使用在类上的,它表示的意思其实就是结合了@Controller和@ResponseBody两个注解,

    如果哪个类下的所有方法需要返回json数据格式的,就在哪个类上使用该注解,具有统一性;需要注意的是,使用了@RestController

    注解之后,其本质相当于在该类的所有方法上都统一使用了@ResponseBody注解,所以该类下的所有方法都会返回json数据格式,

    输出在页面上,而不会再返回视图。

    @ResponseBody和@RestController的区别

    @ResponseBody和@RestController的区别

    @ResponseBody

    一般作用于方法上,加上该注解表示该方法返回结果直接写入到HHTP response Body中,常用于异步加载请求中。在RequestMapping中return返回值默认解析为跳转路径,如果此时想让controller返回一个字符串或对象到前台就会报404 not response的错误。加上之后就不会解析为跳转路径,会解析成相应的json格式对象、集合、字符串、xml等直接返回到前台,可以通过 ajax 的“success”:fucntion(data){} data直接获取到。

    @ResponseBody,一般是使用在单独的方法上的,需要哪个方法返回json数据格式,就在哪个方法上使用,具有针对性。

    下面是返回json格式的字符串

    @RequestMapping("/register")
    @ResponseBody
    public String register(TestUserInfo testUserInfo,String username) throws Exception{
    if(testUserService.findByUserName(username)==null){
    testUserService.addTestUser(testUserInfo);
    return "success";
    }else{
    return "fail";
    }
    }

    @RequestMapping("/upload/condition")
    public String search(Model model) {
    List<ArchiveCategory> allArchiveCategory = archiveCategoryApi.getAllCategories();
    List<ArchiveCategory> topLevelCategory = allArchiveCategory.stream().filter(category -> category.getParentid() == 0 || "视频".equals(category.getName())).collect(Collectors.toList());
    model.addAttribute("archiveCategories", topLevelCategory);
    return "beike/upload-pop-condition";
    }

    @RestController

    @RestController,一般是使用在类上的,它表示的意思其实就是结合了@Controller和@ResponseBody两个注解,,使用了@RestController注解之后,其本质相当于在该类的所有方法上都统一使用了@ResponseBody注解,所以该类下的所有方法都会返回json数据格式,输出在页面上,而不会再返回视图。

    关于使用ResponseEntity时 和@RestController用于Spring RESTful应用程序response.setcontenttype()的作用的介绍现已完结,谢谢您的耐心阅读,如果想了解更多关于3.7、@ResponseBody 和 @RestController、@Controller,@ResponseBody,@RestController,@RequestMapping,@GetMapping作用、@ResponseBody和@RestController、@ResponseBody和@RestController的区别的相关知识,请在本站寻找。

    本文标签:

    上一篇Android兼容性问题(Api 8,ActionbarSherlock)(android兼容模式)

    下一篇Spring WebSocket @SendToSession:向特定会话发送消息(springboot websocket消息推送)