zoukankan      html  css  js  c++  java
  • Java单体应用

    原文地址:http://www.work100.net/training/monolithic-frameworks-spring-mvc-other-annotation.html
    更多教程:光束云 - 免费课程

    其它注解

    序号 文内章节 视频
    1 @ModelAttribute -
    2 @ResponseBody -

    请参照如上章节导航进行阅读

    1.@ModelAttribute

    @ModelAttribute 具有如下三个作用:

    • 绑定请求参数到命令对象

      放在功能处理方法的入参上时,用于将多个请求参数绑定到一个命令对象,从而简化绑定流程,而且自动暴露为模型数据用于视图页面展示时使用

    • 暴露 @RequestMapping 方法返回值为模型数据

      放在功能处理方法的返回值上时,是暴露功能处理方法的返回值为模型数据,用于视图页面展示时使用

    • 暴露表单引用对象为模型数据

      放在处理器的一般方法(非功能处理方法)上时,是为表单准备要展示的表单引用对象,如注册时需要选择的所在城市等,而且在执行功能处理方法(@RequestMapping 注解的方法)之前,自动添加到模型对象中,用于视图页面展示时使用

    例子

    暴露表单引用对象为模型数据的例子:

    @ModelAttribute
    public User get(@RequestParam(required = false) String id) {
        User entity = null;
        if (StringUtils.isNotBlank(id)) {
            entity = userService.get(id);
        }
        if (entity == null) {
            entity = new User();
        }
        return entity;
    }
    

    2.@ResponseBody

    @ResponseBody 注解表示该方法的返回的结果直接写入 HTTP 响应正文(ResponseBody)中,一般在异步获取数据时使用,通常是在使用 @RequestMapping 后,返回值通常解析为跳转路径,加上 @ResponseBody 后返回结果不会被解析为跳转路径,而是直接写入HTTP 响应正文中。

    作用

    该注解用于将 Controller 的方法返回的对象,通过适当的 HttpMessageConverter 转换为指定格式后,写入到 Response 对象的 body 数据区。

    使用时机

    返回的数据不是 html 标签的页面,而是其他某种格式的数据时(如:jsonxml 等)使用

    处理自定义类型

    如果需要返回自定义对象为 JSON 数据类型,需要增加 jackson 依赖,pom.xml 配置文件如下:

    <!-- Json Begin -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.9.5</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.5</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>${jackson.version}</version>
    </dependency>
    <!-- Json End -->
    

    上一篇:表单标签库

    下一篇:MyBatis


    如果对课程内容感兴趣,可以扫码关注我们的 公众号QQ群,及时关注我们的课程更新

  • 相关阅读:
    Kibana 基本操作
    kibana安装
    es7.2版本安装ik分词
    Elastic Search闪退问题
    Elastic Search安装-windows
    1-ES简单介绍
    vue项目1-pizza点餐系统12-设计购物车
    vue项目1-pizza点餐系统11-设计menu页面
    前端:table、thead、th、tr、td
    某二分图匹配题的题解
  • 原文地址:https://www.cnblogs.com/liuxiaojun/p/training-monolithic-frameworks-spring-mvc-other-annotation.html
Copyright © 2011-2022 走看看