說明
作用:
把請求中指定名稱的參數給控制器中的形參賦值。
屬性:
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。
說明
作用:
用于獲取請求體內容。直接使用得到是 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
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
說明
作用:
用于獲取請求消息頭。
屬性:
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
說明
作用:
用于把指定 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
說明
作用:
該注解是 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
說明
作用:
用于多次執行控制器方法間的參數共享。
屬性:
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上面?! ?/p>
@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配置文件漫天飛的年代,它讓程序擁有更高的可讀性,可配置性與靈活性。當然,也有一些人說注解不如配置文件顯的結構清晰,個人覺得所謂的結構應該是一個統一的規范,而不是將一堆文件結構糅合在一起。這就好比是面向對象與面向結構,你能說面向對象的邏輯不清晰嗎?
*請認真填寫需求信息,我們會在24小時內與您取得聯系。