javascript
java的requestmapping_SpringMVC RequestMapping 详解
SpringMVC RequestMapping 詳解
RequestMapping這個注解在SpringMVC扮演著非常重要的角色,可以說是隨處可見。它的知識點很簡單。今天我們就一起學習SpringMVC的RequestMapping這個注解。文章主要分為兩個部分:RequestMapping 基礎用法和RequestMapping 提升用法。
準備工作
pom.xml 這里是需要的jar包和相關的配置。這里設置了maven-compiler-plugin的java版本為1.7,避免打包出錯和中文亂碼的問題。
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
com.springmvc
springmvc
0.0.1-SNAPSHOT
war
maven-compiler-plugin
1.7
1.7
UTF-8
4.1.3.RELEASE
org.springframework
spring-webmvc
${spring.version}
org.springframework
spring-context
${spring.version}
org.springframework
spring-aop
${spring.version}
org.springframework
spring-core
${spring.version}
org.springframework
spring-web
${spring.version}
javax.servlet
javax.servlet-api
4.0.0
provided
web.xml 設置字符攔截器,避免中文亂碼
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
springmvc
dispatcher
org.springframework.web.servlet.DispatcherServlet
1
dispatcher
/
encodingFilter
org.springframework.web.filter.CharacterEncodingFilter
encoding
UTF-8
forceEncoding
true
encodingFilter
/*
SpringMVC的配置文件(dispatcher-servlet.xml)沒有變,這里就不再貼出來了。可以去上一章找
RequestMapping 基礎用法
核心類 ApiStudyController,這是重點需要看的java文件。里面主要介紹了@RequestMapping 的基礎用法。
你需要重點學習的有: 獲取請求參數值的@RequestParam注解;通過占位符獲取參數值的@PathVariable注解;指定請求方式的method屬性;用于將數據存儲到作用域中返回給前端的Map,Model和ModelMap參數;以及如何使用POJO對象作為方法的參數。
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
@RequestMapping("apiStudy")
public class ApiStudyController {
private static final String SUCCESS = "apistudy";
private static final String RESULT_KEY = "result";
/**
* 常用知識點:在類或者方法上使用 @RequestMapping 注解
* 若沒有修飾類,則訪問路徑是: http://ip:port/項目名/方法的@RequestMapping值
* 若類有修飾類,則訪問路徑是: http://ip:port/項目名/類的@RequestMapping值/方法的@RequestMapping值
*/
/**
* 方法中用map作為參數,可以將數據存儲到request作用域中,放回到頁面上。
* 同樣用法的有 Model 類型 和 ModelMap 類型
*/
@RequestMapping("/testMapResult")
public String testMapResult(Map map, Model model, ModelMap modelMap){
String apiDocs = "Map,Model,ModelMap (常用方法) : 在方法中添加Map的參數,可以將數據放到request 作用域中!";
map.put(RESULT_KEY, apiDocs);
model.addAttribute("model", "Model");
modelMap.addAttribute("modelMap", "ModelMap");
return SUCCESS;
}
/**
* 常用知識點:使用 method 屬性來指定請求方式
* 若用GET方式請求,會提示:HTTP Status 405 - Request method 'GET' not supported 錯誤信息
*/
@RequestMapping(value = "/testRequestMethod", method=RequestMethod.POST)
public String testRequestMethod(Map map) {
String apiDocs = "RequestMethod (常用方法) : 若設置只有POST請求才能進入,則用GET方式請求,會報405的錯誤。反之亦然!";
map.put(RESULT_KEY, apiDocs);
return SUCCESS;
}
/**
* 常用知識點:使用注解 @PathVariable 映射 URL綁定占位,屬于REST風格。
* 注意兩點:
* 1. 嚴格用法: @PathVariable("arg") String arg; 前一個arg參數,必須要和占位參數{arg}保持一致。后面一個arg參數可以自定義。
* 2. 偷懶用法: @PathVariable String arg; 這里的參數名 arg 必須要和占位參數{arg}保持一致,不然會提示400的錯誤
*/
@RequestMapping("/testPathVariable/{arg}")
public String testPathVariable(@PathVariable("arg") String arg, Map map) {
String apiDocs = "PathVariable (常用方法) : 通過映射 URL綁定占位獲取的值是 " + arg;
map.put(RESULT_KEY, apiDocs);
return SUCCESS;
}
/**
* 常用知識點:使用注解 @RequestParam 來映射請求參數
* 該注解有三個參數,
* value 請求的參數名,
* required 請求的參數是否必填 ,默認是true,
* defaultValue 請求的參數默認值.
* 參數的類型建議是封裝數據類型,因為float默認值是0.0 ,若該參數是非必填,則會報錯 HTTP Status 500
*/
@RequestMapping("/testRequestParam")
public String testRequestParam(@RequestParam("account") String account,
@RequestParam(value="password", required=true) String password,
@RequestParam(value="price", required=false, defaultValue="0.0") float price,
Map map) {
String apiDocs = "RequestParam (常用方法) : 獲取映射請求參數的值有 account : " + account + " password : " + password + " price : " + price;
map.put(RESULT_KEY, apiDocs);
return SUCCESS;
}
/**
* 常用知識點:方法參數是POJO對象
* 前端的請求參數名一定要和POJO對象屬性一致。支持級聯
*/
@RequestMapping(value = "/testPojo", method = RequestMethod.POST)
public String testPojo(User user, Map map) {
map.put(RESULT_KEY, user);
return SUCCESS;
}
/**
* 不常用方法:params 和 headers
* @RequestMapping 注解中,除了常用的value和method外,還有兩個較為常用的params和headers
* 他們可以是請求跟精確,制定那些參數的請求不接受,同時也可以指定那些參數的請求接收。
* params={param1,param2}
* param1 表示 請求必須包含名為param1的請求參數
* !param1 表示 請求不能包含名為param1的請求參數
* param1!=value1 表示請求包含param1的請求參數,但是其值不能是value1
*/
@RequestMapping(value="/testParamsAndHeaders", params={"itdragon"},
headers = { "Accept-Language=zh-CN,zh;q=0.8" })
public String testParamsAndHeaders(Map map) {
String apiDocs = "params,headers (了解用法) : 這里表示當請求參數中包含了itdragon的時候才能進來";
map.put(RESULT_KEY, apiDocs);
return SUCCESS;
}
/**
* 不常用方法:ant風格
* ?匹文件名中一個字
* *匹文件名中任意字
* ** 匹多 層徑
*/
@RequestMapping("/*/testAntUrl")
public String testAntUrl(Map map) {
String apiDocs = "Ant風格 (了解用法) : ?匹文件名中一個字 ; *匹文件名中任意字 ; ** 匹多 層徑 ";
map.put(RESULT_KEY, apiDocs);
return SUCCESS;
}
/**
* 不常用方法:@RequestHeader 注解獲取請求頭數據。
*/
@RequestMapping("/testRequestHeader")
public String testRequestHeader(@RequestHeader(value = "Accept-Language") String al,
Map map) {
String apiDocs = "@RequestHeader (了解用法) : 獲取請求頭數據的注解, 如Accept-Language 的值是 : " + al;
map.put(RESULT_KEY, apiDocs);
return SUCCESS;
}
/**
* 不常用方法:@CookieValue: 映射一個 Cookie值
*/
@RequestMapping("/testCookieValue")
public String testCookieValue(@CookieValue("JSESSIONID") String sessionId,
Map map) {
String apiDocs = "@CookieValue(了解用法) : 映射一個 Cookie值的注解, 如JSESSIONID 的Cookie值是 : " + sessionId;
map.put(RESULT_KEY, apiDocs);
return SUCCESS;
}
}
用于測試的前端頁面 index.jsp
pageEncoding="UTF-8"%>
SpringMVC 快速入門@RequestMapping 注解基本用法
史上最丑的HelloWorld
Map,Model,ModelMap的使用方法
用GET請求方式測試POST方法
@PathVariable獲取占位數據
@RequestParam獲取請求參數值
account:
level:
salary:
params 和 headers用法
Ant風格URL請求
@RequestHeader 注解獲取請求頭數據
@CookieValue 注解獲取 Cookie值
方便查看結果的apistudy.jsp頁面
pageEncoding="UTF-8"%>
SpringMVC 快速入門@RequestMapping 注解基本用法
request 作用域 :
${requestScope.result}
${requestScope.model}
${requestScope.modelMap}
session 作用域 :
${sessionScope.result}
最后是兩個用于測試的POJO對象,分別是User和Position
public class User {
private Integer id;
private String account;
private String password;
private Position position;
public User() {
}
public User(Integer id, String account, String password) {
this.id = id;
this.account = account;
this.password = password;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Position getPosition() {
return position;
}
public void setPosition(Position position) {
this.position = position;
}
@Override
public String toString() {
return "User [id=" + id + ", account=" + account + ", password=" + password + ", position="
+ position + "]";
}
}
public class Position {
private Integer id;
private String level;
private Double salary;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLevel() {
return level;
}
public void setLevel(String level) {
this.level = level;
}
public Double getSalary() {
return salary;
}
public void setSalary(Double salary) {
this.salary = salary;
}
@Override
public String toString() {
return "Position [level=" + level + ", salary=" + salary
+ "]";
}
}
測試的效果圖
RequestMapping 提升用法
這里的知識點有:輸出模型數據 ModelAndView類型,Map(Model,ModelMap),@ModelAttribute注解,@SessionAttributes注解的使用,和 原生的Servlet Api的使用。
ModelAndView數據類型:見名知意,即包含了模型數據,又包含了視圖數據。設置模型數據有兩種方式:modelAndView.addObject(String attributeName, Object attributeValue) 方分別表示Key和Value。modelAndView.addAllObjects(modelMap) 存的參數是一個Map(Model,ModelMap其實都是Map數據類型)。
設置視圖數據常用方法也有兩種方式:
ModelAndView modelAndView = new ModelAndView(viewName) 初始化ModelAndView的時候設置。
modelAndView.setViewName(viewName) 初始化后再she'zh
@ModelAttribute 注解:被該注解修飾的方法, 會在每個目標方法執行之前被 SpringMVC 調用。實際開發中其實用的并不是很多。在我們更新數據的時候,一般都會先查詢,后更新。該注解就扮演督促查詢的角色,在執行更新的方法前先執行該注解修飾的查詢數據方法。
@SessionAttributes 注解:只能修飾在類上,將模型數據暫存到HttpSession中,從而使多個請求的數據共享。常用方法有@SessionAttributes(value={"obj1", "obj2"}, types={String.class, Obj1.class})。表示可以將數據類型是String或者是對象Obj1的模型數據放到HttpSession中。也可以將變量名是obj1,obj2的模型數據放到HttpSession中。用這個注解容易出一個問題。HttpSessionRequiredException 異常,原因在代碼注釋中。
原生的Servlet Api:如果發現不能引入javax.servlet.* 的文件,可能是因為項目里面中沒有servlet-api.jar。
普通項目解決方法:右擊項目工程名稱 ---> Build Path ---> Configure Build Path... ---> 選擇 Libraries 點擊 Add External JARS ---> 在按照tomcat的里面下,找到lib目錄,里面就有。
Maven項目解決方法:如果按照上面的方法處理,雖然引入文件,當打包的時候會提示"找不到符號",是因為servlet-api.jar 沒有真正的加入到classpath下。最簡單的方法就是在pom.xml加入servlet-api.jar。
看代碼:
import java.io.IOException;
import java.io.Writer;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping("apiStudy")
@SessionAttributes(value={"user"}, types={String.class})
public class ApiStudyController {
private static final String SUCCESS = "apistudy";
private static final String RESULT_KEY = "result";
/**
* @SessionAttributes 將數據存儲到session中,達到多個請求數據共享的目的。
* 只能修飾在類上的注解
* 通過屬性名value,指定需要放到會話中的屬性
* 通過模型屬性的對象類型types,指定哪些模型屬性需要放到會話中
*/
/**
* 常用方法:ModelAndView 方法的返回值設置為 ModelAndView 類型。
* ModelAndView 顧名思義,是包含視圖和模型信息的類型。
* 其數據存放在 request 域對象中.
*/
@RequestMapping("/testModelAndView")
public ModelAndView testModelAndView() {
String viewName = SUCCESS; // 需要返回的視圖名
String apiDocs = "ModelAndView(常用方法) : 之前學習的方法返回值是字符串,數據是通過Map返回到前端。現在可以通過ModelAndView類型直接完成。";
ModelAndView modelAndView = new ModelAndView(viewName);
modelAndView.addObject(RESULT_KEY, apiDocs); // 添加數據到model中
return modelAndView;
}
/**
* SpringMVC 確定目標方法 POJO 類型入參的過程
* 第一步: 確定一個 key
* 若方法形如 "testModelAttribute(User user)" , 則key為 user(POJO 類名第一個字母小寫)
* 若方法形如"testModelAttribute(@ModelAttribute("userObj") User user)" ,則key為 userObj
* 第二步: 在 implicitModel 中查找 key 對應的對象
* 若 implicitModel 存在, 則作為入參傳入
* 若 implicitModel 中不存在, 則檢查當前Handler 是否使用 @SessionAttributes 注解
* 若使用了該注解, 且 @SessionAttributes 注解的 value 屬性值中包含了 key, 則會從 HttpSession 中來獲取 key 所對應的 value 值, 若存在則直接傳入到目標方法的入參中. 若不存在則將拋出異常.
* 若 Handler 沒有標識 @SessionAttributes 注解或 @SessionAttributes 注解的 value 值中不包含 key, 則通過反射來創建 POJO 類型的參數, 傳入為目標方法的參數
* implicitModel? SpringMVC 會把 key 和 POJO 類型的對象保存到 implicitModel 中, 進而會保存到 request 中.
*/
@RequestMapping("/testModelAttribute")
public ModelAndView testModelAttribute(User user){
ModelAndView modelAndView = new ModelAndView(SUCCESS);
modelAndView.addObject(RESULT_KEY, "update : " + user); // 添加數據到model中
return modelAndView;
}
/**
* 常用方法:@ModelAttribute 修飾方法。 被該注解修飾的方法, 會在每個目標方法執行之前被 SpringMVC 調用
* 運行流程:
* 第一步: 在執行 testModelAttribute(User user) 方法前,會先執行被@ModelAttribute 注解修飾的方法 getUser()
* 第二步: 執行getUser() 后,將執行放入到Map中,其中的key 必須和目標方法User對象的首字母小寫user
* 第三步: SpringMVC 從 Map 中取出 User 對象,然后把對象傳入目標方法的參數.
*
* 未使用 @ModelAttribute testModelAttribute方法 打印的信息 :
* update : User [id=1, account=itdragon, password=null, position=null]
* 使用@ModelAttribute testModelAttribute方法 打印的信息 :
* update : User [id=1, account=itdragon, password=zhangdeshuai, position=null]
*/
@ModelAttribute
public void getUser(@RequestParam(value="id",required=false) Integer id,
Map map){
if(id != null){
//模擬從數據庫中獲取對象
User user = new User(1, "itdragon", "zhangdeshuai");
map.put("user", user); // 這里的key 一定是該對象User的首字母小寫user
}
}
/**
* 常用方法:可以使用 Serlvet 原生的 API 作為目標方法的參數 具體支持以下類型
*
* HttpServletRequest
* HttpServletResponse
* HttpSession
* InputStream
* OutputStream
* Reader
* Writer
*/
@RequestMapping("/testServletAPI")
public void testServletAPI(HttpServletRequest request,
HttpServletResponse response, Writer out) throws IOException {
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
out.write("Hello Servlet API,和用Servlet一樣(0——0) ; 
request : " + request + " ;
response : " + response);
}
}
一樣的前端index.jsp
pageEncoding="UTF-8"%>
SpringMVC 快速入門@RequestMapping 注解提升用法
ModelAndView的使用方法
account:
使用原生的Servlet API
兩個實體類和查看結果的jsp頁面沒有變
效果圖:
總結
以上是生活随笔為你收集整理的java的requestmapping_SpringMVC RequestMapping 详解的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 如何在民营银行存钱?民营银行智能存款购买
- 下一篇: 理解 e.clientX,e.clien
