SpringMVC中常用注解
- 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>
控制器代碼:
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";
}
}
輸出結果:
執行了:com.Keafmd.controller.AnnoConteoller - testRequestParam
username:keafmd
這樣我們在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>
控制器代碼:
/**
* 獲取到請求體的內容 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";
}
輸出結果:
執行了: testRequestBody
body:uname=Keafmd&age=21&birthday=2000-01-01
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/>
控制器代碼:
/**
* 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";
}
輸出結果:
執行了: testPathVariable
id:10
RequestHeader
說明
作用:
用于獲取請求訊息頭,
屬性:
value:提供訊息頭名稱
required:是否必須有此訊息頭
提示:
在實際開發中一般不常用
代碼示例
jsp代碼:
<a href="anno/testRequestHeader">testRequestHeader</a><br/>
控制器代碼:
/**
* 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";
}
輸出結果:
執行了: testRequestHeader
head:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3
CookieValue
說明
作用:
用于把指定 cookie 名稱的值傳入控制器方法引數,
屬性:
value:指定 cookie 的名稱,
required:是否必須有此 cookie,
代碼示例
jsp代碼:
<a href="anno/testCookieValue">testCookValue</a><br/>
控制器代碼:
/**
* 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";
}
輸出結果:
執行了: testCookieValue
cookievalue:DCCFE2C1F975AC04D4F55973ADA5C89C
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>
修飾的方法有回傳值
控制器代碼:
/**
* 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;
}
輸出結果:
執行了: testModelAttribute
User{uname='牛哄哄的柯南', age=21, birthday=Mon Jan 25 19:34:46 CST 2021}
修飾的方法沒有回傳值
注意:沒有回傳值的時候利用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);
}
輸出結果:
執行了: testModelAttribute
User{uname='牛哄哄的柯南', age=21, birthday=Mon Jan 25 19:32:20 CST 2021}
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/>
控制器代碼:
注意:需要在類的上面添加
@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";
}
}
依次點擊存入->獲取->清除->獲取,
輸出結果:
執行了: testSessionAttributes
執行了: getSessionAttributes
牛哄哄的柯南
執行了: delSessionAttributes
執行了: getSessionAttributes
null
在success.jsp可以通過
${msg}和${sessionScope}獲取到在類上面把msg存入到session域的內容:牛哄哄的柯南和{msg=牛哄哄的柯南}
在success.jsp可以通過${requestScope}獲取到在testSessionAttributes方法中存入Request域中的內容,
以上就是SpringMVC中常用注解(案例講解)的全部內容,
看完如果對你有幫助,感謝點贊支持!
如果你是電腦端的話,看到右下角的 “一鍵三連” 了嗎,沒錯點它[哈哈]

加油!
共同努力!
Keafmd
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/253083.html
標籤:java

