SpringMVC(3)——SpringMVC注解实战

前言

SpringMVC(2)——controller方法参数与html表单对应(请求参数的绑定)

上篇博客我们提到了controller方法的参数与html表单之间的对应关系

但是这种对应关系有很多缺点:

  1. 传递参数只能放在request的body当中,url参数无法获取
  2. 传递参数无法设置哪些不可为空,哪些可以为空

SpringMVC为了简化这些繁琐的操作,为前后端字段的转换提供了一些很方便的注解

RequestParam注解

@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RequestParam {

	
	@AliasFor("name")
	String value() default "";
	
	@AliasFor("value")
	String name() default "";

	boolean required() default true;

	String defaultValue() default ValueConstants.DEFAULT_NONE;

}

可以设置是否必传,默认值,还有对应前端的字段名

value/name属性

作用相同。指定前端form表单传递的参数的名称

required属性

默认true,表示必传,前端若想调用此controller的此方法,必须保证此字段有值

设置为false则表示可以不传

defaultValue属性

表示默认值,只有required属性为false时才会生效,而且只能指定为字符串类型

demo

@Controller
@RequestMapping("/paramAnno")
public class ParamAnnoController {
    @RequestMapping("/requestParam")
    public String requestParamAnno(@RequestParam(value = "name") String username,
                                   @RequestParam(required = false) Integer age,
                                   @RequestParam(value = "id") Long id) {
        System.out.println("@RequestParam注解使用生效!");
        System.out.println("name:" + username + ",age:" + age + ",id:" + id);
        return "suc";
    }

jsp页面的表单部分

<h3>@RequestParam测试</h3>

<form action="/paramAnno/requestParam" method="post">
    姓名:<input type="text" name="name"/><br/>
    年龄:<input type="text" name="age"/><br/>
    id:<input type="text" name="id"/><br/>
    <input type="submit" value="提交"/>
</form>

@RequestBody注解

@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RequestBody {

	/**
	 * Whether body content is required.
	 * <p>Default is {@code true}, leading to an exception thrown in case
	 * there is no body content. Switch this to {@code false} if you prefer
	 * {@code null} to be passed when the body content is {@code null}.
	 * @since 3.2
	 */
	boolean required() default true;

}

只有一个required属性,表示可传可不传

表示前端传一个js对象给后端,js对象中可以包含各种属性

如果想要对应后端的实体类对象,需要前端使用js封装为js对象发送给后端,form表单做不到发送js对象

我们这里用String代替

    @PostMapping(value = "/requestBody")
    public String requestBodyAnno(@RequestBody String body) {
        System.out.println("@RequestBody注解使用生效!");
        System.out.println(body);
        return "suc";
    }
<form action="/paramAnno/requestBody" method="post">
    f1:<input type="text" name="fun.f1"/><br/>
    f2:<input type="text" name="fun.f2"/><br/>
    f3:<input type="text" name="fun.f3"/><br/>
    list0.f1:<input type="text" name="list[0].f1"/><br/>
    list0.f2:<input type="text" name="list[0].f2"/><br/>
    list0.f3:<input type="text" name="list[0].f3"/><br/>
    list1.f1:<input type="text" name="list[1].f1"/><br/>
    list1.f2:<input type="text" name="list[1].f2"/><br/>
    list1.f3:<input type="text" name="list[1].f3"/><br/>
    birthday:<input type="text" name="birthday"/><br/>
    map.f1:<input type="text" name="map['fun'].f1"/><br/>
    map.f2:<input type="text" name="map['fun'].f2"/><br/>
    map.f3:<input type="text" name="map['fun'].f3"/><br/>
    <input type="submit" value="提交"/>
</form>

在这里插入图片描述

@PathVariable注解

@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface PathVariable {

	/**
	 * Alias for {@link #name}.
	 */
	@AliasFor("name")
	String value() default "";

	/**
	 * The name of the path variable to bind to.
	 * @since 4.3.3
	 */
	@AliasFor("value")
	String name() default "";

	/**
	 * Whether the path variable is required.
	 * <p>Defaults to {@code true}, leading to an exception being thrown if the path
	 * variable is missing in the incoming request. Switch this to {@code false} if
	 * you prefer a {@code null} or Java 8 {@code java.util.Optional} in this case.
	 * e.g. on a {@code ModelAttribute} method which serves for different requests.
	 * @since 4.3.3
	 */
	boolean required() default true;

}

属性作用同上,这里不再赘述

此注解适用于js基本类型,不适用于js对象

作用是直接在请求的url中拼接我们想要的内容,比如数字,字符串等

需要在@RequestMapping中添加{}指定拼接的位置进行使用

    @PostMapping("/pathVariable/{id}")
    public String pathVariableAnno(@PathVariable Long id) {
        System.out.println("@PathVariable注解使用生效!");
        System.out.println(id);
        return "suc";
    }
<h3>@PathVariable测试</h3>

<form action="/paramAnno/pathVariable" method="post">
    <input type="submit" value="提交"/>
</form>

在这里插入图片描述

@RequestHeader

作用:获取指定请求头的值

请求头包含很多属性
在这里插入图片描述

    @PostMapping(value = "/requestHeader")
    public String requestHeaderAnno(@RequestHeader(value = "content-type") String contentType,
                                    @RequestHeader("Accept") String accept) {
        System.out.println("@RequestHeader注解使用生效!");
        System.out.println(contentType);
        System.out.println(accept);
        return "suc";
    }
<h3>@RequestHeader测试</h3>

<form action="/paramAnno/requestHeader" method="post">
    <input type="submit" value="提交"/>
</form>

在这里插入图片描述

@CookieValue注解

后端获取前端指定cookie的值

    @PostMapping("/cookieSession")
    public String cookieSessionAnno(@CookieValue(value = "JSESSIONID") String cookie) {
        System.out.println("@CookieValue注解使用生效!");
        System.out.println(cookie);
        return "suc";
    }
<h3>@CookieSession测试</h3>

<form action="/paramAnno/cookieSession" method="post">
    <input type="submit" value="提交"/>
</form>

在这里插入图片描述

JSESSIONID其实就是session,是一种标记http请求状态并且安全的浏览器存储

这里的数据都是经过加密的

  • 28
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值