整合营销服务商

电脑端+手机端+微信端=数据同步管理

免费咨询热线:

赞!SpringMVC中常用注解(案例讲解)

pringMVC中常用注解

  • RequestParam
  • RequestBody
  • PathVaribale
    • 先了解下REST 风格 URL
  • RequestHeader
  • CookieValue
  • ModelAttribute
    • 修饰的方法有返回值
    • 修饰的方法没有返回值
  • SessionAttribute

RequestParam

说明

作用:
把请求中指定名称的参数给控制器中的形参赋值。
属性:
value:请求参数中的名称。
required:请求参数中是否必须提供此参数。默认值:true。表示必须提供,如果不提供将报错。

代码示例

jsp代码:

<%--
  Created by IntelliJ IDEA.
  User: Keafmd
  Date: 2021/1/25
  Time: 10:48
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>常用注解</title>
</head>
<body>

    <!-- requestParams 注解的使用 -->
    <a href="anno/testRequestParam?name=keafmd">RequestParam</a><br/>

</body>
</html>
12345678910111213141516171819

控制器代码:

package com.Keafmd.controller;

import com.Keafmd.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;

import java.util.Date;
import java.util.Map;

/**
 * Keafmd
 *
 * @ClassName: AnnoConteoller
 * @Description: 注解的控制器
 * @author: 牛哄哄的柯南
 * @date: 2021-01-25 10:50
 */
@Controller
@RequestMapping("/anno")
public class AnnoConteoller {

    /**
     * requestParams 注解的使用
     * @param username
     * @return
     */
    @RequestMapping("/testRequestParam")
    public String testRequestParam(@RequestParam(value="name") String username){
        // @RequestParam(value="name") 必须传name,required:请求参数中是否必须提供此参数,默认值是true,必须提供
        // 获得当前类名
        String clazz = Thread.currentThread().getStackTrace()[1].getClassName();
        // 获得当前方法名
        String method = Thread.currentThread().getStackTrace()[1].getMethodName();

        System.out.println("执行了:"+clazz+" - "+method);
        System.out.println("username:"+username);
        return "success";
    }

}
12345678910111213141516171819202122232425262728293031323334353637383940414243

输出结果:

执行了:com.Keafmd.controller.AnnoConteoller - testRequestParam
username:keafmd
12

这样我们在href中传入name就会赋值给username。

RequestBody

说明

作用:
用于获取请求体内容。直接使用得到是 key=value&key=value…结构的数据。
get 请求方式不适用。
属性:
required:是否必须有请求体。默认值是:true。当取值为 true 时,get 请求方式会报错。如果取值为 false,get 请求得到是 null。

代码示例

jsp代码:

<form action="anno/testRequestBody" method="post">
        用户姓名:<input type="text" name="uname" /><br/>
        用户年龄:<input type="text" name="age" /><br/>
        用户生日:<input type="text" name="birthday" /><br/>
        <input type="submit" value="提交">
</form>
123456

控制器代码:

/**
* 获取到请求体的内容 RequestBody
 */

@RequestMapping("/testRequestBody")
public String testRequestBody(@RequestBody String body){
    String method = Thread.currentThread().getStackTrace()[1].getMethodName();
    System.out.println("执行了:"+" "+method);
    System.out.println("body:"+body);
    return "success";
}
1234567891011

输出结果:

执行了: testRequestBody
body:uname=Keafmd&age=21&birthday=2000-01-01
12

PathVaribale

先了解下REST 风格 URL

REST(英文:Representational State Transfer,简称 REST)描述了一个架构样式的网络系统,比如 web 应用程序。值得注意的是 REST 并没有一个明确的标准,而更像是一种设计的风格。

说明

作用:
用于绑定 url 中的占位符。例如:请求 url 中 /delete/{id},这个{id}就是 url 占位符。
url 支持占位符是 spring3.0 之后加入的。是 springmvc 支持 rest 风格 URL 的一个重要标志。
属性:
value:用于指定 url 中占位符名称。
required:是否必须提供占位符。

代码示例

jsp代码:

<a href="anno/testPathVariable/10">testPathVariable</a><br/>
1

控制器代码:

/**
* PathVariable
* @param id
* @return
*/
@RequestMapping("/testPathVariable/{sid}")
public String testPathVariable(@PathVariable(name="sid") String id){
   // 获得当前方法名
   String method = Thread.currentThread().getStackTrace()[1].getMethodName();
   System.out.println("执行了:"+" "+method);
   System.out.println("id:"+id);
   return "success";
}
12345678910111213

输出结果:

执行了: testPathVariable
id:10
12

RequestHeader

说明

作用:
用于获取请求消息头。
属性:
value:提供消息头名称
required:是否必须有此消息头
提示:
在实际开发中一般不常用

代码示例

jsp代码:

<a href="anno/testRequestHeader">testRequestHeader</a><br/>
1

控制器代码:

/**
* RequestHeader获取请求头的值  不常用
* @param head
* @return
*/
@RequestMapping("/testRequestHeader")
public String testRequestHeader(@RequestHeader(value = "Accept") String head){
   // 获得当前方法名
   String method = Thread.currentThread().getStackTrace()[1].getMethodName();
   System.out.println("执行了:"+" "+method);

   System.out.println("head:"+head);
   return "success";
}
1234567891011121314

输出结果:

执行了: testRequestHeader
head:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3
12

CookieValue

说明

作用:
用于把指定 cookie 名称的值传入控制器方法参数。
属性:
value:指定 cookie 的名称。
required:是否必须有此 cookie。

代码示例

jsp代码:

<a href="anno/testCookieValue">testCookValue</a><br/>
1

控制器代码:

/**
 * CookieValue 不常用
 * @param cookievalue
 * @return
 */
@RequestMapping("/testCookieValue")
public String testCookieValue(@CookieValue(value = "JSESSIONID") String cookievalue){
    // 获得当前方法名
    String method = Thread.currentThread().getStackTrace()[1].getMethodName();
    System.out.println("执行了:"+" "+method);

    System.out.println("cookievalue:"+cookievalue);
    return "success";
}
1234567891011121314

输出结果:

执行了: testCookieValue
cookievalue:DCCFE2C1F975AC04D4F55973ADA5C89C
12

ModelAttribute

说明

作用:
该注解是 SpringMVC4.3 版本以后新加入的。它可以用于修饰方法和参数。
出现在方法上,表示
当前方法会在控制器的方法执行之前,先执行。它可以修饰没有返回值的方法,也可以修饰有具体返回值的方法。
出现在参数上,获取指定的数据给参数赋值。
属性:
value:用于获取数据的 key。key 可以是 POJO 的属性名称,也可以是 map 结构的 key。
应用场景:
当表单提交数据不是完整的实体类数据时,保证没有提交数据的字段使用数据库对象原来的数据。

代码示例

jsp代码:

<form action="anno/testModelAttribute" method="post">
	用户姓名:<input type="text" name="uname" /><br/>
    用户年龄:<input type="text" name="age" /><br/>
    <input type="submit" value="提交">
</form>
12345

修饰的方法有返回值

控制器代码:

/**
 * ModelAttribute
 * @return
 */

@RequestMapping("/testModelAttribute")
public String testModelAttribute(User user){
    // 获得当前方法名
    String method = Thread.currentThread().getStackTrace()[1].getMethodName();
    System.out.println("执行了:"+" "+method);
    System.out.println(user);
    return "success";
}

//有返回值
@ModelAttribute
public User showUser(String uname){
    String method = Thread.currentThread().getStackTrace()[1].getMethodName();
    System.out.println("执行了:"+" "+method);
    User user = new User();
    user.setUname(uname);
    user.setAge(20);
    user.setBirthday(new Date());
    return user;
}
12345678910111213141516171819202122232425

输出结果:

执行了: testModelAttribute
User{uname='牛哄哄的柯南', age=21, birthday=Mon Jan 25 19:34:46 CST 2021}
12

修饰的方法没有返回值

注意:没有返回值的时候利用Map把参数传回去,testModelAttribute的参数User前加上@ModelAttribute(“abc”)接收Map传回的数据。

控制器代码:

/**
 * ModelAttribute
 * @return
 */

@RequestMapping("/testModelAttribute")
public String testModelAttribute(@ModelAttribute("abc")User user){
    // 获得当前方法名
    String method = Thread.currentThread().getStackTrace()[1].getMethodName();
    System.out.println("执行了:"+" "+method);
    System.out.println(user);
    return "success";
}

//无返回值
@ModelAttribute
public void showUser(String uname, Map<String,User> map){
    String method = Thread.currentThread().getStackTrace()[1].getMethodName();
    System.out.println("执行了:"+" "+method);
    User user = new User();
    user.setUname(uname);
    user.setAge(20);
    user.setBirthday(new Date());
    map.put("abc",user);
}
12345678910111213141516171819202122232425

输出结果:

执行了: testModelAttribute
User{uname='牛哄哄的柯南', age=21, birthday=Mon Jan 25 19:32:20 CST 2021}
12

SessionAttribute

说明

作用:
用于多次执行控制器方法间的参数共享。
属性:
value:用于指定存入的属性名称
type:用于指定存入的数据类型。

代码示例

jsp代码:

<a href="anno/testSessionAttributes">存入SessionAttributes</a><br/>
<a href="anno/getSessionAttributes">获取SessionAttributes</a><br/>
<a href="anno/delSessionAttributes">清除SessionAttributes</a><br/>
123

控制器代码:

注意:需要在类的上面添加@SessionAttributes(value = {"msg"}) //把msg=牛哄哄的柯南存到session域中

package com.Keafmd.controller;

import com.Keafmd.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;

import java.util.Date;
import java.util.Map;

/**
 * Keafmd
 *
 * @ClassName: AnnoConteoller
 * @Description: 注解的控制器
 * @author: 牛哄哄的柯南
 * @date: 2021-01-25 10:50
 */
@Controller
@RequestMapping("/anno")
@SessionAttributes(value = {"msg"}) //把msg=牛哄哄的柯南存到session域中
public class AnnoConteoller {

    /**
     * SessionAttributes注解,存入msg
     * @return
     */
    @RequestMapping("/testSessionAttributes")
    public String testSessionAttributes(Model model){
        // 获得当前方法名
        String method = Thread.currentThread().getStackTrace()[1].getMethodName();
        System.out.println("执行了:"+" "+method);

        //底层会存到Request域中
        model.addAttribute("msg","牛哄哄的柯南");

        return "success";
    }

    /**
     * 获取
     * @param modelMap
     * @return
     */
    @RequestMapping("/getSessionAttributes")
    public String getSessionAttributes(ModelMap modelMap){
        // 获得当前方法名
        String method = Thread.currentThread().getStackTrace()[1].getMethodName();
        System.out.println("执行了:"+" "+method);

        //从session域中取出来
        String msg = (String)modelMap.get("msg");
        System.out.println(msg);
        return "success";
    }

    /**
     * 清除
     * @param sessionStatus
     * @return
     */
    @RequestMapping("/delSessionAttributes")
    public String delSessionAttributes(SessionStatus sessionStatus) {
        // 获得当前方法名
        String method = Thread.currentThread().getStackTrace()[1].getMethodName();
        System.out.println("执行了:"+" "+method);

        //从session域中清除
        sessionStatus.setComplete();
        return "success";
    }


}

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677

依次点击存入->获取->清除->获取。

输出结果:

执行了: testSessionAttributes
执行了: getSessionAttributes
牛哄哄的柯南
执行了: delSessionAttributes
执行了: getSessionAttributes
null
123456

在success.jsp可以通过${msg}和${sessionScope}获取到在类上面把msg存入到session域的内容:牛哄哄的柯南和{msg=牛哄哄的柯南}
在success.jsp可以通过${requestScope}获取到在testSessionAttributes方法中存入Request域中的内容。

以上就是SpringMVC中常用注解(案例讲解)的全部内容。

点点关注!

看完记得点赞+评论+转发哦~

本文主要介绍SpringMVC常用注解及使用方法汇总。

常用注解有哪些呢?

@Controller

@Controller 用于标记在一个类上,使用它标记的类就是一个SpringMVC Controller 对象。分发处理器将会扫描使用了该注解的类的方法,并检测该方法是否使用了@RequestMapping 注解。@Controller 只是定义了一个控制器类,而使用@RequestMapping 注解的方法才是真正处理请求的处理器。

@Controller
public class UserLogonCotroller {

}

@RequestMapping

RequestMapping是一个用来处理请求地址映射的注解,可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径。RequsestMapping有六个属性:

value:指定请求的实际地址;

method:指定请求的method类型, GET、POST、PUT、DELETE等;

consumes:指定处理请求的提交内容类型(Content-Type),例如application/json, text/html;

produces:指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回;

params:指定request中必须包含某些参数值是,才让该方法处理。

headers:指定request中必须包含某些指定的header值,才能让该方法处理请求。

@Controller
@RequestMapping("/user")
public class UserLogonCotroller {
  
		@RequestMapping(value = "/logon", method = {RequestMethod.GET, RequestMethod.POST },
		params = {"loginname", "username"})
		public void logon(HttpServletRequest request){
  
		}
}

@Autowired

@Autowired做bean的注入时使用,如果写在字段上,就不需要再写setter方法。

// 用于字段上
@Autowired
private UserinfoDao userinfoDao;

// 用于属性的方法上
@Autowired
public void setUserinfoDao(UserinfoDao userinfoDao) {
		this.userinfoDao = userinfoDao;
}

@PathVariable

@PathVariable用于将请求URL中的模板变量映射到功能处理方法的参数上,即取出uri模板中的变量作为参数。

@RequestMapping(value = "/logon", method = {RequestMethod.GET, RequestMethod.POST },
params = {"loginname", "username"})
public void logon(HttpServletRequest request
		,@PathVariable("loginname") String loginname
		,@PathVariable("username") String username){

}

@requestParam

@requestParam主要用于在SpringMVC后台控制层获取参数,类似一种是request.getParameter("name"),它有三个常用参数:defaultValue = "0", required = false, value = "isApp";defaultValue 表示设置默认值,required 铜过boolean设置是否是必须要传入的参数,value 值表示接受的传入的参数类型。

@RequestMapping(value = "/logon", method = {RequestMethod.GET, RequestMethod.POST },
params = {"loginname", "username"})
public void logon(HttpServletRequest request
      ,@RequestParam(value = "loginname", required = false) String loginname
      ,@RequestParam(value = "username", required = false) String username){
}

@ResponseBody

用于将Controller的方法返回的对象,通过适当的HttpMessageConverter转换为指定格式后,写入到Response对象的body数据区。

使用时机:返回的数据不是html标签的页面,而是其他某种格式的数据时(如json、xml等)使用;

@RequestMapping(value = "/logon", method = {RequestMethod.GET, RequestMethod.POST },
@ResponseBody
params = {"loginname", "username"})
public void logon(HttpServletRequest request
       ,@RequestParam(value = "loginname", required = false) String loginname
      ,@RequestParam(value = "username", required = false) String username){
}

@ModelAttribute

该Controller的所有方法在调用前,先执行此@ModelAttribute方法,可用于注解和方法参数中,可以把这个@ModelAttribute特性,应用在BaseController当中,所有的Controller继承BaseController,即可实现在调用Controller时,先执行@ModelAttribute方法。

@RequestMapping(value = "/logon", method = {RequestMethod.GET, RequestMethod.POST },
@ResponseBody
public void logon(@ModelAttribute("loginname") Userinfo userinfo){
      
}

@SessionAttributes

@SessionAttributes即将值放到session作用域中,写在class上面。  

@SessionAttributes 除了可以通过属性名指定需要放到会话中的属性外(value 属性值),

还可以通过模型属性的对象类型指定哪些模型属性需要放到会话中(types 属性值)。

@Controller
@RequestMapping("/user")
@SessionAttributes(value = {"loginname"}, types = {String.class})
public class UserLogonCotroller {
   
}

@CookieValue

作用:用来获取Cookie中的值;

参数: value:参数名称 required:是否必须 defaultValue:默认值

@CookieValue(value = LoginBase.TGC_ID, required = false) String tgcid)

@Service

注入dao,用于标注服务层,主要用来进行业务的逻辑处理。

@repository

dao层使用,用于标注数据访问层,也可以说用于标注数据访问组件,即DAO组件。

@component

把普通pojo实例化到spring容器中。


ok,以上就是SpringMVC常用注解及使用方法汇总,看完记得转发、点赞和收藏。想了解更多内容,请关注本小编,如果有错误,欢迎批评指正,感谢支持。

(云渺书斋)

pring从2.5版本开始在编程中引入注解,用户可以使用@RequestMapping, @RequestParam, @ModelAttribute等等这样类似的注解。到目前为止,Spring的版本虽然发生了很大的变化,但注解的特性却是一直延续下来,并不断扩展,让广大的开发人员的双手变的更轻松起来,这都离不开Annotation的强大作用,今天我们就一起来看看Spring MVC 4中常用的那些注解吧。

1. @Controller

Controller控制器是通过服务接口定义的提供访问应用程序的一种行为,它解释用户的输入,将其转换成一个模型然后将试图呈献给用户。Spring MVC 使用 @Controller 定义控制器,它还允许自动检测定义在类路径下的组件并自动注册。如想自动检测生效,需在XML头文件下引入 spring-context:

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:p="http://www.springframework.org/schema/p"

xmlns:context="http://www.springframework.org/schema/context"

xsi:schemaLocation="

http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context.xsd">

<context:component-scan base-package="org.springframework.samples.petclinic.web"/>

<!-- ... --></beans>

2. @RequestMapping

我们可以 @RequestMapping 注解将类似 “/favsoft”这样的URL映射到整个类或特定的处理方法上。一般来说,类级别的注解映射特定的请求路径到表单控制器上,而方法级别的注解只是映射为一个特定的HTTP方法请求(“GET”,“POST”等)或HTTP请求参数。

@Controller

@RequestMapping("/favsoft")

public class AnnotationController {

@RequestMapping(method=RequestMethod.GET)

public String get(){

return "";

}

@RequestMapping(value="/getName", method = RequestMethod.GET)

public String getName(String userName) {

return userName;

}

@RequestMapping(value="/{day}", method=RequestMethod.GET)

public String getDay(Date day){

DateFormat df = new SimpleDateFormat("yyyy-MM-dd");

return df.format(day);

}

@RequestMapping(value="/addUser", method=RequestMethod.GET)

public String addFavUser(@Validated FavUser favUser,BindingResult result){

if(result.hasErrors()){

return "favUser";

}

//favUserService.addFavUser(favUser);

return "redirect:/favlist";

}

@RequestMapping("/test")

@ResponseBody

public String test(){

return "aa";

}

}

@RequestMapping 既可以作用在类级别,也可以作用在方法级别。当它定义在类级别时,标明该控制器处理所有的请求都被映射到 /favsoft 路径下。@RequestMapping中可以使用 method 属性标记其所接受的方法类型,如果不指定方法类型的话,可以使用 HTTP GET/POST 方法请求数据,但是一旦指定方法类型,就只能使用该类型获取数据。

@RequestMapping 可以使用 @Validated与BindingResult联合验证输入的参数,在验证通过和失败的情况下,分别返回不同的视图。

@RequestMapping支持使用URI模板访问URL。URI模板像是URL模样的字符串,由一个或多个变量名字组成,当这些变量有值的时候,它就变成了URI。

3. @PathVariable

在Spring MVC中,可以使用 @PathVariable 注解方法参数并将其绑定到URI模板变量的值上。如下代码所示:

String findOwner( String , Model model) {

FavUser favUser = favUserService.findFavUser();

model.addAttribute(

;

}

URI模板 “favusers/{favUserId}"指定变量的名字 favUserId ,当控制器处理这个请求的时候, favUserId的值会被设定到URI中。比如,当有一个像“favusers/favccxx”这样的请求时,favUserId的值就是 favccxx。

@PathVariable 可以有多个注解,像下面这样:

@RequestMapping(value="/owners/{ownerId}/pets/{petId}", method=RequestMethod.GET)public String findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {

Owner owner = ownerService.findOwner(ownerId);

Pet pet = owner.getPet(petId);

model.addAttribute("pet", pet); return "displayPet";

}

@PathVariable中的参数可以是任意的简单类型,如int, long, Date等等。Spring会自动将其转换成合适的类型或者抛出 TypeMismatchException异常。当然,我们也可以注册支持额外的数据类型。

如果@PathVariable使用Map<String, String>类型的参数时, Map会填充到所有的URI模板变量中。

@PathVariable支持使用正则表达式,这就决定了它的超强大属性,它能在路径模板中使用占位符,可以设定特定的前缀匹配,后缀匹配等自定义格式。

@PathVariable还支持矩阵变量,因为现实场景中用的不多,这就不详细介绍了,有需要的童鞋请查看官网的文档。

4. @RequestParam

@RequestParam将请求的参数绑定到方法中的参数上,如下面的代码所示。其实,即使不配置该参数,注解也会默认使用该参数。如果想自定义指定参数的话,如果将@RequestParam的 required 属性设置为false(如@RequestParam(value="id",required=false))。

5. @RequestBody

@RequestBody是指方法参数应该被绑定到HTTP请求Body上。

@RequestMapping(value = "/something", method = RequestMethod.PUT)public void handle(@RequestBody String body, Writer writer) throws IOException {

writer.write(body);

}

如果觉得@RequestBody不如@RequestParam趁手,我们可以使用 HttpMessageConverter将request的body转移到方法参数上, HttMessageConverser将 HTTP请求消息在Object对象之间互相转换,但一般情况下不会这么做。事实证明,@RequestBody在构建REST架构时,比@RequestParam有着更大的优势。

6. @ResponseBody

@ResponseBody与@RequestBody类似,它的作用是将返回类型直接输入到HTTP response body中。@ResponseBody在输出JSON格式的数据时,会经常用到,代码见下图:

@RequestMapping(value = "/something", method = RequestMethod.PUT)@ResponseBodypublic String helloWorld() { return "Hello World";

}

7. @RestController

我们经常见到一些控制器实现了REST的API,只为服务于JSON,XML或其它自定义的类型内容,@RestController用来创建REST类型的控制器,与@Controller类型。@RestController就是这样一种类型,它避免了你重复的写@RequestMapping与@ResponseBody。

@RestController

public class FavRestfulController {

@RequestMapping(value="/getUserName",method=RequestMethod.POST)

public String getUserName(@RequestParam(value="name") String name){

return name;

}

}

8. HttpEntity

HttpEntity除了能获得request请求和response响应之外,它还能访问请求和响应头,如下所示:

@RequestMapping("/something")public ResponseEntity<String> handle(HttpEntity<byte[]> requestEntity) throws UnsupportedEncodingException {

String requestHeader = requestEntity.getHeaders().getFirst("MyRequestHeader")); byte[] requestBody = requestEntity.getBody(); // do something with request header and body

HttpHeaders responseHeaders = new HttpHeaders();

responseHeaders.set("MyResponseHeader", "MyValue"); return new ResponseEntity<String>("Hello World", responseHeaders, HttpStatus.CREATED);

}

9. @ModelAttribute

@ModelAttribute可以作用在方法或方法参数上,当它作用在方法上时,标明该方法的目的是添加一个或多个模型属性(model attributes)。该方法支持与@RequestMapping一样的参数类型,但并不能直接映射成请求。控制器中的@ModelAttribute方法会在@RequestMapping方法调用之前而调用,示例如下:

@ModelAttribute

public Account addAccount(@RequestParam String number) {

return accountManager.findAccount(number);

}

@ModelAttribute

public void populateModel(@RequestParam String number, Model model) {

model.addAttribute(accountManager.findAccount(number));

// add more ...

}

@ModelAttribute方法用来在model中填充属性,如填充下拉列表、宠物类型或检索一个命令对象比如账户(用来在HTML表单上呈现数据)。

@ModelAttribute方法有两种风格:一种是添加隐形属性并返回它。另一种是该方法接受一个模型并添加任意数量的模型属性。用户可以根据自己的需要选择对应的风格。

@ModelAttribute作用在方法参数上

当@ModelAttribute作用在方法参数上时,表明该参数可以在方法模型中检索到。如果该参数不在当前模型中,该参数先被实例化然后添加到模型中。一旦模型中有了该参数,该参数的字段应该填充所有请求参数匹配的名称中。这是Spring MVC中重要的数据绑定机制,它省去了单独解析每个表单字段的时间。

@ModelAttribute是一种很常见的从数据库中检索属性的方法,它通过@SessionAttributes使用request请求存储。在一些情况下,可以很方便的通过URI模板变量和类型转换器检索属性。

注解的出现终结了XML配置文件漫天飞的年代,它让程序拥有更高的可读性,可配置性与灵活性。当然,也有一些人说注解不如配置文件显的结构清晰,个人觉得所谓的结构应该是一个统一的规范,而不是将一堆文件结构糅合在一起。这就好比是面向对象与面向结构,你能说面向对象的逻辑不清晰吗?