springMVC各种注解及解释和使用
3、@RequestMapping 注解
Spring MVC 使用 @RequestMapping 注解為控制器指定可以處理哪些 URL 請求,@RequestMapping把請求與處理請求的方法映射在一起。
Spring MVC 使用 @RequestMapping 注解為控制器指定可以處理哪些 URL 請求,@RequestMapping把請求與處理請求的方法映射在一起。
4、窄化請求映射
(1)@RequestMapping可以修飾控制器類和方法上
類定義處:提供初步的請求映射信息,相對于WEB 應用的根目錄。
方法處:提供進一步的細分映射信息,相對于類定義處的 URL。
若類定義處未標注 @RequestMapping,則方法處標記的 URL 相對于WEB 應用的根目錄DispatcherServlet 截獲請求后,就通過控制器上@RequestMapping 提供的映射信息確定請求所對應的處理方法。
package com.offcn.mvc.controller;/**
?* Created by Administrator on 2019/9/19 0019.
?*/
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
/**
?* @author Administrator
?* @date 2019/9/19 0019 15:33
?* @description
?*/
@Controller
@RequestMapping("/dept")
public class DeptController {
????/**
?????* 處理器方法
?????* @param request
?????* @param response
?????* @return
?????* @throws Exception
?????*/
????@RequestMapping("/add")
????public ModelAndView addDept() throws Exception {
????????//創建模型視圖對象
????????ModelAndView mav=new ModelAndView();
????????//把數據綁定到模型對象
????????mav.addObject("name","add dept");
????????//設置跳轉視圖名稱
????????mav.setViewName("success");
????????return mav;
????}
}
?
package com.offcn.mvc.controller;/**
?* Created by Administrator on 2019/9/19 0019.
?*/
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
?* 頁面處理器
?* @author Administrator
?* @date 2019/9/19 0019 14:15
?* @description
?*/
@Controller
@RequestMapping("/user")
public class UserController{
????/**
?????* 處理器方法
?????* @param request
?????* @param response
?????* @return
?????* @throws Exception
?????*/
????@RequestMapping("/login")
????public ModelAndView login() throws Exception {
????????//創建模型視圖對象
????????ModelAndView mav=new ModelAndView();
????????//把數據綁定到模型對象
????????mav.addObject("name","admin");
????????//設置跳轉視圖名稱
????????mav.setViewName("success");
????????return mav;
????}
????@RequestMapping(value = {"/logout","/exit"})
????public ModelAndView logout() throws Exception {
????????//創建模型視圖對象
????????ModelAndView mav=new ModelAndView();
????????//把數據綁定到模型對象
????????mav.addObject("name","logout");
????????//設置跳轉視圖名稱
????????mav.setViewName("success");
????????return mav;
????}
}
訪問路徑:
http://localhost:9091/mvc/user/login
(2)組合使用是“或”的關系
package com.offcn.mvc.controller;/**
?* Created by Administrator on 2019/9/19 0019.
?*/
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
?* 頁面處理器
?* @author Administrator
?* @date 2019/9/19 0019 14:15
?* @description
?*/
@Controller
@RequestMapping("/user")
public class UserController{
????/**
?????* 處理器方法
?????* @param request
?????* @param response
?????* @return
?????* @throws Exception
?????*/
????@RequestMapping("/login")
????public ModelAndView login() throws Exception {
????????//創建模型視圖對象
????????ModelAndView mav=new ModelAndView();
????????//把數據綁定到模型對象
????????mav.addObject("name","admin");
????????//設置跳轉視圖名稱
????????mav.setViewName("success");
????????return mav;
????}
????@RequestMapping(value = {"/logout","/exit"})
????public ModelAndView logout() throws Exception {
????????//創建模型視圖對象
????????ModelAndView mav=new ModelAndView();
????????//把數據綁定到模型對象
????????mav.addObject("name","logout");
????????//設置跳轉視圖名稱
????????mav.setViewName("success");
????????return mav;
????}
}
http://localhost:9091/mvc/user/exit或
http://localhost:9091/mvc/user/logout
?
method:用于限制請求方法,如果沒有定義該屬性則意味著get和post同時支持。
@RequestMapping(value="/login",method = RequestMethod.GET)
@RequestMapping(value = {"/logout","/exit"},method = RequestMethod.POST)
@RequestMapping(value = {"/delete"},method = {RequestMethod.POST,RequestMethod.GET})
@RequestMapping(value="/update",params="id")
請求中必須有一個參數叫id
?
http://localhost:9091/mvc/user/delete?id=100
@RequestMapping(value="/update",params="id=100")
請求中必須有一個參數叫id,值必須是100
@RequestMapping(value="/update",params="!id")
請求中必須不能有參數叫id
@RequestMapping(value="/update",params="id=!100")
請求中必須有一個參數叫id,值必須不是100
//同時接受get或post請求
@RequestMapping(value = {"/request"},method = {RequestMethod.POST,RequestMethod.GET})
public String request(HttpServletRequest request, HttpSession session) throws Exception {
????request.setAttribute("reqKey","reqValue");
????session.setAttribute("sessKey","sessValue");
????return "success";//只返回視圖名稱
}
//接受一個參數
@RequestMapping(value = {"/addVal"},method = {RequestMethod.POST,RequestMethod.GET})
public String addUserVal(String name) throws Exception {
????System.out.println(name);
????return "success";//只返回視圖名稱
}
//接受多個參數,并把參數封裝到java對象中
@RequestMapping(value = {"/addObj"},method = {RequestMethod.POST,RequestMethod.GET})
public String addUserVal(UserModel userModel) throws Exception {
????System.out.println(userModel);
????return "success";//只返回視圖名稱
}
?
?
8、模型Model、Map、ModelMap
Spring Web MVC 提供Model、Map或ModelMap讓我們能去暴露渲染視圖需要的模型數據。
雖然此處注入的是三個不同的類型(Model model, Map model2, ModelMap model3),但三者是同一個對象,頁面取值都在request中。
???????????????????????????
//測試Model Map ModelMap
@RequestMapping("/testModel")
public String testModel(Model model, Map map, ModelMap modelMap){
????model.addAttribute("m","mModel");
????//
????String mapVal=(String)map.get("m");
????System.out.println("mapVal:"+mapVal);
????String modelMapVal =(String)modelMap.get("m");
????System.out.println("modelMapVal:"+modelMapVal);
????System.out.println(model==map);
????System.out.println(map==modelMap);
????return "success";//只返回視圖名稱
}
?
9、@RequestParam綁定單個請求參數值
@RequestParam用于將請求參數區數據映射到功能處理方法的參數上。
public String requestparam(@RequestParam String username)
請求中包含username 參數(如/requestparam?username=zhang),則自動傳入。
指定入參名稱:
public String requestparam2(@RequestParam("username") String username)
@RequestParam注解主要有哪些參數:
value:參數名字,即入參的請求參數名字,如username表示請求的參數區中的名字為username的參數的值將傳入;
required:是否必須,默認是true,表示請求中一定要有相應的參數,否則將報400錯誤碼;
defaultValue:默認值,表示如果請求中沒有同名參數時的默認值
public String requestparam5(@RequestParam(value="username", required=true, defaultValue="zhang") String username)
?
//測試@RequestParam
@RequestMapping(value = {"/trp"})
public String testRequestParam(@RequestParam(value="name",required=false,defaultValue = "scott") String username) throws Exception {
????System.out.println(username);
????return "success";//只返回視圖名稱
}
10、@PathVariable 綁定URI 模板變量值
@PathVariable用于將請求URL中的模板變量映射到功能處理方法的參數上。
@RequestMapping(value="/users/{userId}/topics/{topicId}")
public String test(
@PathVariable(value="userId") int userId,
@PathVariable(value="topicId") int topicId){
......
}
如請求的 URL 為“控制器URL/users/123/topics/456”,則自動將URL 中模板變量{userId}和{topicId}綁定到通過@PathVariable注解的同名參數上,即入參后userId=123、topicId=456。
?
//測試 @PathVariable
?@RequestMapping(value="/document/{userId}/topics/{topicId}")
?public String testPathVariable(
?????????@PathVariable(value="userId") int userId,
?????????@PathVariable(value="topicId") int topicId){
?????System.out.println(userId);
?????System.out.println(topicId);
?????return "success";//只返回視圖名稱
?}
?
測試url:
http://localhost:9091/mvc/user/document/100/topics/1001
Creates a cookie, a small amount of information sent by a servlet to a Web browser, saved by the browser, and later sent back to the server. A cookie's value can uniquely identify a client, so cookies are commonly used for session management.
A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number. Some Web browsers have bugs in how they handle the optional attributes, so use them sparingly to improve the interoperability of your servlets.
The servlet sends cookies to the browser by using the?HttpServletResponse.addCookie(javax.servlet.http.Cookie)?method, which adds fields to HTTP response headers to send cookies to the browser, one at a time. The browser is expected to support 20 cookies for each Web server, 300 cookies total, and may limit cookie size to 4 KB each.
@CookieValue 綁定Cookie數據值
@CookieValue用于將請求的Cookie數據映射到功能處理方法的參數上。
public String test(@CookieValue(value="JSESSIONID", defaultValue="") ?String sessionId){
......
}
如上配置將自動將JSESSIONID 值入參到sessionId參數上,defaultValue 表示Cookie 中沒有JSESSIONID 時默認為空。
傳入參數類型也可以是javax.servlet.http.Cookie類型:
public String test2(@CookieValue(value="JSESSIONID", defaultValue="") Cookie sessionId){
......
}
//測試發送cookie
@RequestMapping(value = {"/sc"})
public String sendCookie(HttpServletResponse response) throws Exception {
????????????//創建Cookie
????Cookie user=new Cookie("name","admin");
????user.setMaxAge(1000*60*60*24*7);
????response.addCookie(user);
????System.out.println("保存cookie成功");
????return "success";//只返回視圖名稱
}
//測試獲取cookie
@RequestMapping(value = {"/gc"})
public String getCookie(@CookieValue(value="name",defaultValue = "") String name) throws Exception {
????//獲取Cookie
????System.out.println("name:"+name);
????return "success";//只返回視圖名稱
}
Win7系統中Cookie位置:
C:\Users\Administrator\AppData\Roaming\Microsoft\Windows\Cookies
File -->setting --> maven --> runner 里面的 VM Options 添加?-Dfile.encoding=GB2312?
13、@RequestHeader 綁定請求頭數據
@RequestHeader 用于將請求的頭信息區數據映射到功能處理方法的參數上。
@RequestMapping(value="/header")
public String test(@RequestHeader("User-Agent")
String userAgent,@RequestHeader(value="Accept") String[] accepts){
......
}
如上配置將自動將請求頭“User-Agent”值入參到userAgent 參數上,并將“Accept”請求頭值入參到accepts參數上。
//測試獲取header
@RequestMapping(value = {"/gh"})
public String getHeader(@RequestHeader("User-Agent") String userAgent) throws Exception {
????//獲取Cookie
????System.out.println("userAgent:"+userAgent);
????return "success";//只返回視圖名稱
}
14、命令對象入參
@RequestMapping(value = { "/dept" })
//參數為對象類型,可直接接收請求中的參數
public ModelAndView dept(DeptEntity dept) {
System.out.println("dept:" + dept);
// 模型試圖對象
ModelAndView mav = new ModelAndView();
mav.setViewName("update");
return mav;
}
?
15、@ModelAttribute
1.綁定請求參數到命令對象:放在功能處理方法的入參上時,用于將多個請求參數綁定到一個命令對象,從而簡化綁定流程,而且自動暴露為模型數據用于視圖頁面展示時使用;
?
//測試@ModelAttribute
@RequestMapping(value = {"/ma1"})
public String testMA1(@ModelAttribute("user") UserModel userModel) throws Exception {
????return "ma";//只返回視圖名稱
}
?
@ModelAttribute它的作用是將該綁定的命令對象以“user”為名稱添加到模型對象中供視圖頁面展示使用。我們此時可以在視圖頁面使用${user.uname}來獲取綁定的命令對象的屬性。
?
對應頁面:
<body>
Hello World<br>
${user.uid}<br>
${user.uname}<br>
${user.upass}<br>
${user.uage}<br>
</body>
?
暴露表單引用對象為模型數據:放在處理器的一般方法(非功能處理方法)上時,是為表單準備要展示的表單引用對象,該方法在執行功能處理方法(@RequestMapping 注解的方法)之前,自動添加到模型對象中,用于視圖頁面展示時使用或在處理方法中使用;
?
//測試@ModelAttribute
@RequestMapping(value = {"/ma2"})
public String testMA2(Integer uid) throws Exception {
????System.out.println("testMA2:"+uid);
????return "ma";//只返回視圖名稱
}
@ModelAttribute("user")
public ?UserModel preQueryUser(Integer uid){
????System.out.println("preQueryUser:"+uid);
????UserModel userModel=new UserModel();
????userModel.setUname("testMa2");
????return ?userModel;
}
?
如上代碼會在執行功能處理方法之前執行,并將其自動添加到模型對象中。
1、先于處理方法執行
2、把方法的返回值放入model中
3、可以通過參數接收表單對象
?
暴露@RequestMapping 方法返回值為模型數據:放在功能處理方法的返回值上時,是暴露功能處理方法的返回值為模型數據,用于視圖頁面展示時使用。
//測試@ModelAttribute,此時處理方法沒有指定view信息,使用RequestMapping的value值作為跳轉路徑信息
@RequestMapping(value = {"/ma3"})
public @ModelAttribute("user") UserModel testMA3() throws Exception {
????System.out.println("testMA3");
????UserModel userModel=new UserModel();
????userModel.setUname("testMa2");
????userModel.setUage(200);
????userModel.setUpass("111111");
????userModel.setUid(456);
????return userModel;//只返回視圖名稱
}
沒有設置viewname,該如何跳轉?
RequestToViewNameTranslator類:
用于直接將請求轉換為邏輯視圖名。默認實現為DefaultRequestToViewNameTranslator。
DefaultRequestToViewNameTranslator:將請求URL轉換為邏輯視圖名,默認規則如下:
http://localhost:9080/web 上下文/list -------> 邏輯視圖名為list
http://localhost:9080/web 上下文/list.html -------> 邏輯視圖名為list(默認刪除擴展名)
http://localhost:9080/web 上下文/user/list.html -------> 邏輯視圖名為user/list
?1.把處理方法中的命令對象,放到model中。
?2.把非處理方法的返回值,放到model中,必須注意該方法先于處理方法執行,同時其參數可以封裝表單參數。
?3.把處理方法的返回值,放入model中。
17、@SessionAttributes 綁定命令對象到session(了解)
@SessionAttributes注解的作用是把與@ModelAttribute中的相同屬性的數據綁定到session作用域中。
?
//1、在控制器類頭上添加@SessionAttributes注解
@Controller
@RequestMapping("/user")
@SessionAttributes(value={"user"})
public class UserController{
......
}
//2、@ModelAttribute注解的方法進行表單引用對象的創建
@ModelAttribute("user")
public ?UserModel preQueryUser(Integer uid){
????System.out.println("preQueryUser:"+uid);
????UserModel userModel=new UserModel();
????userModel.setUname("testMa2");
????return ?userModel;
}
//3、@RequestMapping注解方法的@ModelAttribute注解的參數進行命令對象的綁定
//測試@ModelAttribute
@RequestMapping(value = {"/ma2"})
public String testMA2(Integer uid) throws Exception {
????System.out.println("testMA2:"+uid);
????return "ma2";//只返回視圖名稱
}
通過SessionStatus的setComplete()方法清除@SessionAttributes指定的會話數據
@RequestMapping("/logout") //
public String logout(SessionStatus status) {
if(true) { //④
status.setComplete();
}
return "success";
}
?
18、重定向與轉發
SpringMVC默認情況下是服務器端跳轉,向jsp頁面中跳轉,一般情況下,控制器方法返回字符串類型的值會被當成邏輯視圖名處理;如果返回的字符串中帶 forward: 或 redirect:前綴時,SpringMVC 會對他們進行特殊處理:
將 forward: 和redirect: 當成指示符,其后的字符串作為 URL 來處理。
redirect:success.jsp:會完成一個到 success.jsp 的重定向的操作,不經過試圖解析器處理。
forward:success.jsp:會完成一個到 success.jsp 的轉發操作。
@RequestMapping(value= {"/jumpOne"})
public String jumpOne() {
return "forward:one.jsp";
}
?
@RequestMapping(value= {"/jumpTwo"})
public String jumpTwo() {
return "redirect:two.jsp";
}
總結:
1.從地址欄顯示來說
forward是服務器請求資源,服務器直接訪問目標地址的URL,把那個URL的響應內容讀取過來,然后把這些內容再發給瀏覽器.瀏覽器根本不知道服務器發送的內容從哪里來的,所以它的地址欄還是原來的地址
redirect是服務端根據邏輯,發送一個狀態碼,告訴瀏覽器重新去請求那個地址.所以地址欄顯示的是新的URL
2.從數據共享來說
forward:轉發頁面和轉發到的頁面可以共享request里面的數據
redirect:不能共享數據
3.從運用地方來說
forward:一般用于用戶登陸的時候,根據角色轉發到相應的模塊
redirect:一般用于用戶注銷登陸時返回主頁面和跳轉到其它的網站等
4.從效率來說
forward:高
redirect:低
19、mvc:annotation-driven注解
<mvc:annotation-driven/>注解簡介
<mvc:annotation-driven/>注解的作用?
<mvc:annotation-driven /> 注解會自動注冊
RequestMappingHandlerMapping、RequestMappingHandlerAdapter 與
ExceptionHandlerExceptionResolver 三個bean。
還將提供以下支持:
支持使用 ConversionService 實例對表單參數進行類型轉換
支持使用 @NumberFormat annotation、@DateTimeFormat注解完成數據類型的格式化
支持使用 @Valid 注解對 JavaBean 實例進行 JSR 303 驗證
支持使用 @RequestBody 和 @ResponseBody 注解。
比如直接使用@ResponseBody時,報Description?The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
導入mvc命名空間:
<?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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/mvc
" >http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">
?
導入jackson依賴:
<dependency>
????<groupId>com.fasterxml.jackson.core</groupId>
????<artifactId>jackson-databind</artifactId>
????<version>2.9.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
????<groupId>com.fasterxml.jackson.core</groupId>
????<artifactId>jackson-core</artifactId>
????<version>2.9.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
<dependency>
????<groupId>com.fasterxml.jackson.core</groupId>
????<artifactId>jackson-annotations</artifactId>
????<version>2.9.0</version>
</dependency>
?
代碼實現:
@RequestMapping("/queryUser")
@ResponseBody //該注解將導致無法跳轉
public UserModel queryUser() throws Exception {
????System.out.println("queryUser()");
????UserModel userModel=new UserModel();
????userModel.setUname("testMa2");
????userModel.setUage(200);
????userModel.setUpass("111111");
????userModel.setUid(456);
????return userModel;
}
@RequestMapping("/queryUsers")
@ResponseBody //該注解將導致無法跳轉
public List<UserModel> queryUsers() throws Exception {
????System.out.println("queryUsers()");
????UserModel userModel1=new UserModel();
????userModel1.setUname("testMa1");
????userModel1.setUage(200);
????userModel1.setUpass("111111");
????userModel1.setUid(456);
????UserModel userModel2=new UserModel();
????userModel2.setUname("testMa2");
????userModel2.setUage(200);
????userModel2.setUpass("111111");
????userModel2.setUid(456);
????List<UserModel> list=new ArrayList<>();
????list.add(userModel1);
????list.add(userModel2);
????return list;
}
@RequestMapping("/queryUserMap")
@ResponseBody //該注解將導致無法跳轉
public Map<String,List<UserModel>> queryUserMap() throws Exception {
????System.out.println("queryUserMap()");
????UserModel userModel1=new UserModel();
????userModel1.setUname("testMa1");
????userModel1.setUage(200);
????userModel1.setUpass("111111");
????userModel1.setUid(456);
????UserModel userModel2=new UserModel();
????userModel2.setUname("testMa2");
????userModel2.setUage(200);
????userModel2.setUpass("111111");
????userModel2.setUid(456);
????List<UserModel> list=new ArrayList<>();
????list.add(userModel1);
????list.add(userModel2);
????Map<String,List<UserModel>> map=new HashMap<>();
????map.put("userMap",list);
????return map;
}
@RequestMapping("/queryHello")
@ResponseBody //該注解將導致無法跳轉
public String queryHello() throws Exception {
????System.out.println("queryHello()");
????return "Hello World";
}
@RequestMapping("/addUser")
@ResponseBody //該注解將導致無法跳轉
public String addUser(@RequestBody UserModel userModel) throws Exception {
????System.out.println("queryUser():"+userModel);
????return "success";
}
總結
以上是生活随笔為你收集整理的springMVC各种注解及解释和使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 大剑无锋之HTTP连接、Tcp三次握手四
- 下一篇: 无招胜有招之Java进阶JVM(三)内存