笔记:各种注解的用法。@ModelAttribute, @SuppressWarnings("rawtypes"),@PathVariable

来源:互联网 发布:java 16进制颜色转rgb 编辑:程序博客网 时间:2024/05/22 04:32

@ModelAttribute一个具有如下三个作用:

     ①绑定请求参数到命令对象:放在功能处理方法的入参上时,用于将多个请求参数绑定到一个命令对象,从而简化绑定流程,而且自动暴露为模型数据用于视图页面展示时使用;

    ②暴露表单引用对象为模型数据:放在处理器的一般方法(非功能处理方法)上时,是为表单准备要展示的表单引用对象,如注册时需要选择的所在城市等,而且在执行功能处理方法(@RequestMapping 注解的方法)之前,自动添加到模型对象中,用于视图页面展示时使用;

    ③暴露@RequestMapping 方法返回值为模型数据:放在功能处理方法的返回值上时,是暴露功能处理方法的返回值为

模型数据,用于视图页面展示时使用。

一、绑定请求参数到指定对象

public String test1(@ModelAttribute("user") UserModel user) 
     只是此处多了一个注解@ModelAttribute("user"),它的作用是将该绑定的命令对象以“user”为名称添加到模型对象中供视图页面展示使用。我们此时可以在视图页面使用${user.username}来获取绑定的命令对象的属性。如请求参数包含“?username=zhang&password=123&workInfo.city=bj”自动绑定到user 中的workInfo属性的city属性中。

二、暴露表单引用对象为模型数据

/**  * 设置这个注解之后可以直接在前端页面使用hb这个对象(List)集合  * @return  */  @ModelAttribute("hb")  public List<String> hobbiesList(){      List<String> hobbise = new LinkedList<String>();      hobbise.add("basketball");      hobbise.add("football");      hobbise.add("tennis");      return hobbise;  } 
JSP页面把代码展示出来

    <br>      初始化的数据 :    ${hb }      <br>                <c:forEach items="${hb}" var="hobby" varStatus="vs">              <c:choose>                  <c:when test="${hobby == 'basketball'}">                  篮球<input type="checkbox" name="hobbies" value="basketball">                  </c:when>                  <c:when test="${hobby == 'football'}">                      足球<input type="checkbox" name="hobbies" value="football">                  </c:when>                  <c:when test="${hobby == 'tennis'}">                      网球<input type="checkbox" name="hobbies" value="tennis">                  </c:when>              </c:choose>          </c:forEach>  

备注:

1、通过上面这种方式可以显示出一个集合的内容

2、上面的jsp代码使用的是JSTL,需要导入JSTL相关的jar包

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

三、暴露@RequestMapping方法返回值为模型数据

public @ModelAttribute("user2") UserModel test3(@ModelAttribute("user2") UserModel user) 

     大家可以看到返回值类型是命令对象类型,而且通过@ModelAttribute("user2")注解,此时会暴露返回值到模型数据( 名字为user2 ) 中供视图展示使用@ModelAttribute 注解的返回值会覆盖@RequestMapping 注解方法中的@ModelAttribute 注解的同名命令对象

原文出处:http://hbiao68.iteye.com/blog/1948380



@SuppressWarnings("rawtypes")

SuppressWarnings压制警告,即去除警告      rawtypes是说传参时也要传递带泛型的参数


@PathVariable注解

带占位符的 URL 是 Spring3.0 新增的功能,该功能在SpringMVC 向 REST 目标挺进发展过程中具有里程碑的意义

通过 @PathVariable 可以将 URL 中占位符参数绑定到控制器处理方法的入参中:URL 中的 {xxx} 占位符可以通过@PathVariable("xxx") 绑定到操作方法的入参中。

 @RequestMapping("/pathVariable/{name}")      public String pathVariable(@PathVariable("name")String name){          System.out.println("hello "+name);          return "helloworld";      } 
在jsp页面(指定全路径)
    <h1>pathVariable</h1>      <a href="${pageContext.request.contextPath}/hello/pathVariable/bigsea" > name is bigsea </a>      <br/>      <a href="${pageContext.request.contextPath}/hello/pathVariable/sea" > name is sea</a>      <br/>  
即@PathVariable("xxx")里面的xxx是用来占位的。







原创粉丝点击