SpringMVC常用注解:@ResponseBody、@RequestParam 等讲解

@Controller:

@Controller用于标记在一个类上,使用这个注解的类会被标记为SpringMVC 的Controller,当SpringMVC 容器初始化时,会扫描该类的方法,并检测到配有注解@RequestMapping 的方法,并将其作为一个Handler 初始化到系统中

@ResponseBody:

  1. 该注解可用于类和方法上,一般用于方法上,如果该方法被@ResponseBody标记后,那么方法的任何返回类型都会 HttpMessageConverter 进行转化并且写入到HttpServletResponse 返回,用于类上时,表示所用方法都生效。
  2. 本文结合FastJson 对方法放入返回结果进行处理:
  3. Maven 配置:
<dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.58</version>
</dependency>      
  1. SpringMVC.xml 加入以下配置:
<!-- 将返回对象解析为JSON 字符串-->
    <mvc:annotation-driven>
        <mvc:message-converters>
            <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/html;charset=UTF-8</value>
                        <value>application/json</value>
                        <value>application/xml;charset=UTF-8</value>
                    </list>
                </property>
                <property name="fastJsonConfig" ref="fastJsonConfig"></property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

    <!-- 下面的配置没有将对象属性为null的值过滤 -->
    <bean name="fastJsonConfig" class="com.alibaba.fastjson.support.config.FastJsonConfig">
        <property name="serializerFeatures">
            <array>
                <!--输出key时是否使用双引号,默认为true-->
                <value>QuoteFieldNames</value>
                <!--是否输出值为null的字段,默认为false-->
                <value>WriteMapNullValue</value>
                <!--全局修改日期格式-->
                <value>WriteDateUseDateFormat</value>
                <!--按照toString方式获取对象字面值-->
                <value>WriteNonStringValueAsString</value>
            </array>
        </property>
    </bean>
  1. 关于 SerializerFeature中 array配置可以参考博文:https://blog.csdn.net/zjkyx888/article/details/78673898
  2. Controller 写法
@RestController
@RequestMapping("/test")
public class TestController {
    @ResponseBody
    @RequestMapping("/json")
    public UserVo testJson(){
        UserVo userVo = new UserVo();
        userVo.setAge(27);
        userVo.setName("张井天");
        return userVo;
    }
}

7、测试返回

{"age":"27","name":"张井天"}

@RestController

@RestController 作用在类上,它是 @Controller 和 @ResponseBody的结合体,也是一种省略写法

@RequestMapping

  1. @RequestMapping 可以作用在类和方法上,用于请求Url 和 method 方法绑定。
  2. @RequestMapping 中属性:
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Mapping
public @interface RequestMapping {

    // 用于指定映射器名称
    String name() default "";

    // 绑定多个映射名称 同path
    String[] value() default {};

    // 用于指定映射路径,同value
    String[] path() default {};

    // 指定请求的方式,可以配置多个方法 GET, POST, HEAD, OPTIONS, PUT, PATCH, DELETE, TRACE
    RequestMethod[] method() default {};

    // 指定请求的参数 [常用于,同一请求多个版本区分]
    String[] params() default {};

    // 指定请求头包含的数据
    String[] headers() default {};

    // 指定处理请求提交的内容类型(Content-Type), 例如application/json, text/html
    String[] consumes() default {};

    // 指定请求返回的内容类型 例如:produces = "application/json; charset=UTF-8"
    String[] produces() default {};

}

其中比较长常用 value, method 例如工作中开发常用:

@RequestMapping(value="/json", method = RequestMethod.POST)
    public User testJson(User user){
   		// 业务逻辑
        return user;
    }

接受请求参数@PathVariable

1、@PathVariable顾名思义是从请求地址中获取到参数
请求信息 :http://localhost:8080/test/json/zhangjingtian/27
Controller method:

@RestController
@RequestMapping("/test")
public class TestController {

    @RequestMapping(value="/json/{name}/{age}", method = RequestMethod.POST)
    public User testJson(@PathVariable String name, @PathVariable int age){
        User user = new User();
        user.setName(name);
        user.setAge(age);
        return user;
    }

处理请求参数:@RequestParam

  1. @RequestParam 可以用于接受Url拼接参数获取和Form表单参数的获取。
  2. @RequestParam 中包含两个参数 value 对应请求参数的Key,required表示参数时候必传,默认必传!
  3. Controller method 写法,@RequestParam 可以省略:
@RequestMapping(value="/json", method = RequestMethod.POST)
    public User testJson(@RequestParam(value = "name", required = false)String name,
                         @RequestParam(value = "age", required = false) int age){
        User user = new User();
        user.setName(name);
        user.setAge(age);
        return user;
    }

处理请求参数:@RequestBody

  1. 用于接受http请求中Body中的Json 字符串并将其转化为 Bean对象。
  2. Post man 请求示例
    在这里插入图片描述
  3. Controller method 写法:
@RestController
@RequestMapping("/test")
public class TestController {

    @RequestMapping(value="/json")
    public User testJson(@RequestBody User user){
        return user;
    }

以上仅仅是博主对SpringMVC常用注解的粗浅认识,如有错误请评论告知,博主会及时更新!!

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值