SpringMVC後臺獲取前臺參數和向前臺傳值的幾種方式

獲取前臺參數:java

咱們以用戶登陸爲例,用戶登陸涉及兩個參數:spring

帳號:loginName  
密碼:password  


這是前臺登陸視圖:mvc

 

 

相應的前臺源碼:app

<form action="login">  
    賬號:<input type="text" name="loginName" > <br/>  
    密碼:<input type="text" name="password" > <br/>  
    <input type="submit" value="登陸">  
</form>  


------------------------------------------------------jsp

 介紹SpringMVC最經常使用的3種取值方法函數

------------------------------------------------------ui

方法1:參數直接獲取this

ps: 函數參數名與請求參數名保持一致。url

@RequestMapping("/login")  
public String login(String loginName,String password){  
    System.out.println("方法1:參數直接獲取");  
    System.out.println("loginName:"+loginName);  
    System.out.println("password:"+password);         
    return "loginSuccess";  
}  


運行結果:spa

 

方法2:對象獲取

ps:創建一個對象,屬性名對應請求參數名保持一致,並生成相應的getter()和setter()方法。

創建對象User:

package com.springdemo.entities;  
  
public class User {  
    private String loginName;         
    private String password;   
  
    public String getLoginName() {  
        return loginName;  
    }  
  
    public void setLoginName(String loginName) {  
        this.loginName = loginName;  
    }  
      
    public String getPassword() {  
        return password;  
    }  
  
    public void setPassword(String password) {  
        this.password = password;  
    }  
}  


開始接收:

@RequestMapping("/login")  
public String login(User u){  
    System.out.println("方法2:對象獲取");  
    System.out.println("loginName:"+u.getLoginName());  
    System.out.println("password:"+u.getPassword());          
    return "loginSuccess";  
}  


運行結果:

 

方法3:@RequestParam參數綁定獲取

ps:方法1的變種,但該接收參數名能夠隨意,經過註解@RequestParam指明便可。

請求URL爲:

http://localhost:8080/springmvc/hello/101?loginName=wangwu&password=123

對於上面這個url,controller裏面能夠這麼寫:

​
@RequestMapping("/login")  
public String login(@RequestParam("loginName") String name,@RequestParam("password") String pwd){  
    System.out.println("方法3:參數綁定獲取");  
    System.out.println("loginName:"+name);  
    System.out.println("password:"+pwd);          
    return "loginSuccess";  
} 

​


方法4:@PathVariable獲取請求路徑中的參數

這個註解可以識別URL裏面的一個模板,咱們看下面的一個URL

http://localhost:8080/springmvc/hello/101?param1=10&param2=20

上面的一個url你能夠這樣寫:

@RequestMapping("/hello/{id}")
    public String getDetails(@PathVariable(value="id") String id,
    @RequestParam(value="param1", required=true) String param1,
    @RequestParam(value="param2", required=false) String param2){
.......
}

 

向前臺傳值(除了使用ModelAndView方式外。還可使用Map、Model和ModelMap的方式):

Java代碼

1.使用Map、Model和ModelMap的方式

@RequestMapping("/test")
public String test(Map<String,Object> map,Model model,ModelMap modelMap,HttpServletRequest request){
    //1.放在map裏  
    map.put("names", Arrays.asList("caoyc","zhh","cjx"));
    //2.放在model裏 建議使用
    model.addAttribute("time", new Date());
    //3.放在request裏  
    request.setAttribute("request", "requestValue");
    //4.放在modelMap中 
    modelMap.addAttribute("city", "ChengDu");
    modelMap.put("gender", "male");
    return "hello";
}

JSP寫法:

time:${requestScope.time}
names:${requestScope.names }
city:${requestScope.city }
gender:${requestScope.gender }
request:${requestScope.request}

2.使用ModelAndView的方式:

@RequestMapping(value="/test2.do",method = RequestMethod.POST)  
public ModelAndView checknameIsExist2(@RequestParam("sid") String sid,Model model,HttpServletRequest request) {  
    ModelAndView mav = new ModelAndView();  
    mav.addObject("ModelAndView", "ModelAndViewValue");  
    //設置要跳轉的頁面,與返回值時String時返回success相似,如下跳轉到/student/studentList.jsp  
    mav.setViewName("/student/studentList");  
    return mav;  
}

說明:使用ModelAndView,能夠直接使用AddObject來傳遞數據,而且數據㐓使用EL表達式在前臺頁面處理。使用setViewName("/student/studentList");來設置頁面跳轉路徑。

借用一篇文章:

springMVC的@RequestParam註解和@PathVariable註解的區別

 

@RequestParam註解和@PathVariable註解的區別,從字面上能夠看出前者是獲取請求裏邊攜帶的參數;後者是獲取請求路徑裏邊的變量參數。

(例如:127.0.0.1/user/{userId}?userName=zhangshan,userId是路徑上的變量,userName纔是請求參數信息)

1.@RequestParam註解

@RequestParam有三個參數:

value:參數名;

required:是否必需,默認爲true,表示請求參數中必須包含該參數,若是不包含拋出異常。

defaultValue:默認參數值,若是設置了該值自動將required設置爲false,若是參數中沒有包含該參數則使用默認值。

示例:@RequestParam(value = "userId", required = false, defaultValue = "1")

 

2.@PathVariable註解

當使用@RequestMapping URI佔位符映射時,Url中能夠經過一個或多個{xxxx}佔位符映射,經過@PathVariable能夠綁定佔位符參數到方法參數中。

例如:@PathVariable("userId") Long userId,@PathVariable("userName") String userName

(注:Long類型能夠根據需求本身改變String或int,spring會自動作轉換)

@RequestMapping(「/user/{userId}/{userName}/query")

請求URL:http://localhost/user/8/張山/query

 

@PathVariable小誤區:

在有些參考資料中說,若是定義的參數名和佔位符中的名稱是相同的,則能夠將 @PathVariable(xxxx) 簡寫爲:@PathVariable,這實際上是錯誤的!

由於在正常編譯時,Java類反射對象是不包含方法的入參名稱的,若是編譯時將debug打開(javac –debug=no),方法的入參名稱會記錄到類中。

在Eclipse中能夠這樣設置(項目屬性Java Compiler):

相關文章
相關標籤/搜索