• springmvc之如何确定目标方法Pojo类型的参数?


    springmvc确定目标方法pojo类型入参的过程:
    (1)确定一个Key。

    • 若目标方法的pojo参数没有使用@ModelAttribute作为修饰,则key为pojo类名第一个字母小写的字符串一致。若使用了@ModelAttribute来修饰,则key为@ModelAttribute注解的value属性值。

    (2)在ImplicitModel中查找Key对应的对象,若存在,则作为入参传入。

    • 若在@ModelAttribute标注的方法中保存过,且key和(1)中保持的一致,就会获取到。

    (3)在ImplicitModel中不存在Key对应的对象,则检查当前的Handler是否使用@SessionAtributes注解修饰。若使用了注解修饰,且SessionAttributes注解的value属性值中包含了key,则会从HttpSession中获取key所对应的value值,若存在则直接传入到目标方法的入参中。若不存在,则将抛出异常。

    (4)若Handler没有标识SessionAttributes注解或SessionAttributes直接的value中不包含Key,则会通过反射来创建pojo类型的参数,传入为目标方法的参数。

    (5)springmvc会把Key和value保存到implicitModel中,进而保存到request中。

    @RequestMapping("/springmvc")
    @Controller
    public class SpringmvcTest {
        private static final String SUCCESS = "success";
        
        @ModelAttribute
        public void getPerson(@RequestParam(value="id",required=false) Integer id,
                Map<String,Object> map) {
            if(id != null) {
                Person person = new Person(1,"jack",18,"123456");
                System.out.println("模拟的数据库中的数据"+person);
                map.put("myperson", person);
            }
        }
        
        @RequestMapping(value="/testModelAttribute")
        public String testModelAttribute(@ModelAttribute("myperson") Person person) {
            System.out.println(person);
            return SUCCESS;
        }
    }

    index.jsp

        <form action="springmvc/testModelAttribute" method="POST"><br>
            <input type="hidden" name="id" value="1"><br>
            <span>username:</span><input type="text" name="username" value="tom"><br>
            <span>age:</span><input type="text" name="age" value="20"><br>
            <input type="submit" value="submit"><br>
        </form>

    succes.jsp

        <p>Success</p>
        <p>myperson person:${requestScope.myperson}</p>

    其实就是根据放入到map中的名字ModelAttribute中的value值来进行匹配,并为person对象取一个新的名字。同时未修改的属性值可以被赋以原来的值。

  • 相关阅读:
    MySQL练习题
    MySql基础操作
    解决使用IDEA启动Tomcat成功但localhost:8080无法访问的问题
    1417. 重新格式化字符串--来源:力扣(LeetCode)
    字符消除
    Comsol中Absolute Pressure的解释
    气体流量与质量流率换算
    FileZilla MLSD错误:连接超时、读取目录列表失败
    Avalon总线的地址对齐与NIOS编程
    同步复位和异步复位--好文章就是要记录下来
  • 原文地址:https://www.cnblogs.com/xiximayou/p/12179610.html
Copyright © 2020-2023  润新知