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

时间:2022-07-23
本文章向大家介绍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对象取一个新的名字。同时未修改的属性值可以被赋以原来的值。