【归纳总结】SpringMVC之HandlerMethod参数的封装

直接封装

1️⃣基本类型和其对应的包装类的封装

例如请求携带如下参数:
localhost:8080/register?username=octavius&password=123456&age=20

使用Handler可以自动接收到参数:

 @RequestMapping("register")
    public void register(String username,String password,Integer age){
        System.out.println(username + ":" + password + ":" + age);
    }

建议:如果你想要接收基本类型,不建议直接写基本类型,建议以基本类型所对应的包装类来接收

2️⃣Date类型数据的封装

假设现在请求参数中携带了一个birthday=2021-04-04的参数,我们需要把它封装成Date类型

① @DateTimeFormat

使用SpringMVC提供的日期转换器@DateTimeFormat(pattern)

    @RequestMapping("register")
    public void register(@DateTimeFormat Date birthday){
        System.out.println(birthday);
    }

② 自定义转换器

第一步

写一个类实现Converter<S, T>接口,重写convert方法

当请求参数名和Handler方法的形参名一致,类型又匹配为Converter<S, T>接口中的T类型时,则会按照convert方法中的逻辑进行转换

@Component
public class String2DateConverter implements Converter<String, Date> {

    //什么情况下会调用convert方法执行类型转换
    //请求参数名和handler方法的形参名一致,类型又匹配为Converter接口这里的类型
    @SneakyThrows
    @Override
    public Date convert(String s) {
        Date date = null;
        //业务逻辑自定义
        String pattern1 = "yyyy-MM-dd";
        String pattern2 = "yyyy-MM-dd HH:mm:ss";
        String pattern3 = "yyyy-MM-dd HH:mm";
        if (s.length() == pattern1.length()){
            date = new SimpleDateFormat(pattern1).parse(s);
        }else if (s.length() == pattern2.length()){
            date = new SimpleDateFormat(pattern2).parse(s);
        } else if (s.length() == pattern3.length()) {
            date = new SimpleDateFormat(pattern3).parse(s);
        }
        return date;
    }
}

第二步

将该组件注册为convert(转换器)

    <!-- bean definitions here -->
    <context:component-scan base-package="com.cskaoyan"/>
    <mvc:annotation-driven conversion-service="conversionService2"/>

    <bean id="conversionService2" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <ref bean="string2DateConverter"/>
                <!--<bean class="com.cskaoyan.converter.String2DateConverter"/>-->
            </set>
        </property>
    </bean>

完毕后“xxxx-xx-xx”形式的字符串参数就会自动被封装成Date类型了。

3️⃣数组的封装

如请求中有多个参数名相同:
localhost:8080/register?hobbies=sing&hobbies=dance&hobbies=basketball

则可以用数组接收,会自动封装

    @RequestMapping("register")
    public void register(String[] hobbies){
        System.out.println(hobbies);
    }

4️⃣二进制文件的封装

① 单个二进制文件的封装

第一步

导包

        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.4</version>
        </dependency>

会引入commons-io和commons-fileupload两个依赖

第二步

组件注册——multipartResolver

    <!--组件id为固定值,不可以修改为其他值-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="5000000"/>
    </bean>

注意:组件id为固定值multipartResolver,不可以修改为其他值

可以设置参数,如最大允许上传文件大小。

第三步

使用Handler方法接收文件并上传

    @RequestMapping("uplodfile")
    //注意:方法参数名要和请求参数名保持一致
    public void fileUpload(MultipartFile theFile) throws IOException {
        //文件的保存路径
        File path = new File("D:\\test\\img");
        //构造一个file来接收multipartFile
        File file = new File(path, "img01");
        //执行上传方法
        theFile.transferTo(file);
    }

在theFile对象上调用方法也可以获取一些东西:

        //请求参数名
        String name = theFile.getName();
        //上传时的文件名
        String originalFilename = theFile.getOriginalFilename();
        //文件类型
        String contentType = theFile.getContentType();
        //文件大小
        long size = theFile.getSize();

② 多个二进制文件的封装

第一步和第二步同上

第三步
    @RequestMapping("uplodfiles")
    //注意:方法参数名要和请求参数名保持一致
    public void filesUpload(MultipartFile[] theFiles) throws IOException {
        for (MultipartFile theFile : theFiles) {
            //文件的保存路径
            File path = new File("D:\\test\\img");
            //构造一个file来接收multipartFile
            File file = new File(path, "img01");
            //执行上传方法
            theFile.transferTo(file);
        }
    }

使用pojo封装

1️⃣封装请求参数

请求参数名和javabean的成员变量名一致时使用

比如将请求参数封装到如下bean中

@Data
public class User {
    String username;
    String password;
    Integer age;

    //@DateTimeFormat //请求参数封装过程中的转换
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")    //响应结果json格式的限定
    Date birthday;
    
    String[] hobbys;
}
    @RequestMapping("register")
    public void register(User user){
        System.out.println(user);
    }

2️⃣封装json数据

前端的json数据要传过来
Content-Type:application/json
Method:post

在pojo前加上@RequestBody注解(对应响应json数据的数据时需要加上@ResponseBody注解)

@RestController
public class JsonController {

    //{
    //  "username":"octavius",
    //  "password":"123456"
    // }
    @RequestMapping("json/login")
    public BaseRespVo login(@RequestBody User user){
        return BaseRespVo.ok(user);
    }
}

也可以使用map来接收


其他参数

1️⃣HttpServletRequest、HttpServletResponse

HttpServletRequest、HttpServletResponse也可以作为参数传入handler

2️⃣Model

返回值为String作为viewname的时候,使用Model作为形参
上一篇文章

3️⃣Cookie

cookie是不能直接获得的,只能通过request获得

    @RequestMapping("fetch/cookie")
    public BaseRespVo fetchCookie(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            System.out.println(cookie.getName() + " = " + cookie.getValue());
        }
        return BaseRespVo.ok();
    }

在浏览器中设置cookie的方法:开发者工具→application→cookie

4️⃣Session

Session可以写在形参中,也可以用request获得

    @RequestMapping("fetch/session")
    public BaseRespVo fetchSession(HttpSession session) {
        Object username = session.getAttribute("username");
        return BaseRespVo.ok(username);
    }
    @RequestMapping("fetch/session2")
    public BaseRespVo fetchSession2(HttpServletRequest request) {
        HttpSession session = request.getSession();
        return BaseRespVo.ok();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值