SpringMVC中參數的傳遞(一)


前言

1.首先,我們在web.xml里面配置前端控制器DispatcherServlet以及字符編碼過濾器(防止中文亂碼),配置如下:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app version="3.0" 
 3     xmlns="http://java.sun.com/xml/ns/javaee"
 4     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 5     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
 6     http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
 7     
 8     <!-- 配置前端控制器 -->
 9     <servlet>
10         <servlet-name>abc</servlet-name>
11         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
12         <!-- 修改springMVC的配置文件路徑 -->
13         <!-- 如果不配置init-param就會在  這個路徑下找/WEB-INF/servletName-servlet.xml(默認名) -->
14         <!-- 所以如果init-param配置錯誤的話會報FileNotFound異常,提示找不到servletName-servlet.xml文件 -->
15         <init-param>
16             <param-name>contextConfigLocation</param-name>
17             <param-value>classpath:springmvc.xml</param-value>
18         </init-param>
19         <!-- 自啟動,Tomcat啟動時加載這個類 -->
20         <load-on-startup>1</load-on-startup>
21     </servlet>
22     <!-- 攔截請求     /表示攔截所有請求但不攔截jsp請求,其他的靜態資源如html,css,images都會被攔截 -->
23     <servlet-mapping>
24         <servlet-name>abc</servlet-name>
25         <url-pattern>/</url-pattern>
26     </servlet-mapping>
27     
28     <!-- 字符編碼過濾器 -->
29     <filter>
30         <filter-name>encoding</filter-name>
31         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
32         <!-- 初始化參數 -->
33         <init-param>
34             <param-name>encoding</param-name>
35             <param-value>utf-8</param-value>
36         </init-param>
37         
38     </filter>
39     <!-- 要過濾那些請求 -->
40     <filter-mapping>
41         <filter-name>encoding</filter-name>
42         <!-- 過濾器配置為/* -->
43         <url-pattern>/*</url-pattern>
44     </filter-mapping>
45 </web-app>
web.xml

2.配置SpringMVC的配置文件springmvc.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xmlns:mvc="http://www.springframework.org/schema/mvc"
 5     xmlns:context="http://www.springframework.org/schema/context"
 6      xsi:schemaLocation="http://www.springframework.org/schema/beans
 7      http://www.springframework.org/schema/beans/spring-beans.xsd
 8      http://www.springframework.org/schema/context
 9      http://www.springframework.org/schema/context/spring-context.xsd
10      http://www.springframework.org/schema/mvc
11      http://www.springframework.org/schema/mvc/spring-mvc.xsd">
12     
13     <!-- 掃描注解 -->
14     <context:component-scan base-package="com.lmw.controller"></context:component-scan>
15     <!-- 注解驅動 -->
16     <!-- handlerMapping的注解方式實現方法 -->
17     <!-- org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping -->
18     <!-- handlerAdapter的注解方式實現方法 -->
19     <!-- org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter -->
20     <mvc:annotation-driven></mvc:annotation-driven>
21     <!-- 不攔截靜態資源請求  -->
22     <!-- mapping里面填的是請求的URL以通配符的形式表示 -->
23     <!-- Location里填的是請求的資源在項目里的位置,即要在哪里去尋找這個資源 -->
24     <mvc:resources location="/WEB-INF/js/" mapping="/abc/**"></mvc:resources>
25     <mvc:resources location="/js/" mapping="/js/**"></mvc:resources>
26     <mvc:resources location="/css/" mapping="/css/**"></mvc:resources>
27     <mvc:resources location="/images/" mapping="/images/**"></mvc:resources>
28 </beans>
springmvc.xml

3.編寫People類

 1 package com.lmw.pojo;
 2 
 3 public class People {
 4     private String name;
 5     private int age;
 6     public String getName() {
 7         return name;
 8     }
 9     public void setName(String name) {
10         this.name = name;
11     }
12     public int getAge() {
13         return age;
14     }
15     public void setAge(int age) {
16         this.age = age;
17     }
18     @Override
19     public String toString() {
20         return "People [name=" + name + ", age=" + age + "]";
21     }
22     
23 }
People類

4.編寫index.jsp頁面(就是一個form表單)

1 <body>
2     <form action="#" method="post">
3         <input type="text" name="name"/>
4         <input type="text" name="age"/>
5         <input type="submit" value="提交"/> 
6     </form>
7 </body>

這里的action先空着,后面根據實際情況再填寫對應的控制器

一、基本數據類型參數的傳遞

1.首先新建一個main.jsp頁面

1 <body>
2     這里是main.jsp!
3 </body>

2.編寫控制器DemoController

package com.lmw.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;


@Controller
public class DemoController {
    /**
     * 基本數據類型的傳遞demo
     * @param name
     * @param age
     * @return
     */
    @RequestMapping("demo1")
    public String demo1(String name, int age){
        System.out.println("執行demo1"+" "+name+" "+age);
        return "main";
    }
}

在DemoController面里我們寫了一個叫demo1的方法,這個方法有兩個參數:String類型的name和int類型的age。SpringMVC會自動幫我們給這兩個參數注入值,這里只需要我們的參數名稱和index.jsp里面input的name相同即可。這樣寫好后,將index.jsp里的form表單的action值改為控制器的名字demo1就可以運行了 。

                                     圖1 輸入name和age

                                 圖2 提交后跳轉到了mian.jsp頁面

                                                    圖3 控制台輸出

 

 二、對象類型參數的傳遞

對象數據類型的參數傳遞包括普通對象、請求對象(request)、session對象等對象的傳遞。

(一)普通對象類型參數的傳遞

我們在上面的DemoController里再添加一個demo2方法,如下:

 1  2 /**
 3 * 對象數據類型的傳遞demo
 4 * @param name
 5 * @param age
 6 * @return
 7 */
 8 @RequestMapping("demo2")
 9 public String demo2(People people){
10     System.out.println("執行demo2"+" "+people);
11     return "main";
12 }

SpringMVC同樣也可以對普通對象進行注入,前提條件是input的name要和對象的屬性名稱相同。將action的值改為demo2就可以了,結果圖下面就不貼了。

(二)request對象的傳遞

首先,同樣的,我們在DemoController里再添加一個demo3方法,如下:

 1 /**
 2 * 利用request對象傳值
 3 * @param req
 4 * @return
 5 */
 6 @RequestMapping("demo3")
 7 public String demo3(HttpServletRequest req){
 8     req.setAttribute("req", "利用request對象傳的值");
 9     return "main";
10 }

在mian.jsp里接收request對象傳過來的值:

1 <body>
2     request:${request.req }
3 </body>

然后我們在瀏覽器里訪問控制器demo3,在瀏覽器輸入:http://localhost:8080/springmvc02/demo3,回車

 

(三)session對象傳值

利用session向jsp頁面傳值和request對象傳值類似,在DemoController里添加一個demo4方法,如下:

 1 /**
 2 * 利用session對象傳值
 3 * @param session
 4 * @return
 5 */
 6 @RequestMapping("demo4")
 7 public String demo4(HttpSession session){
 8     session.setAttribute("session", "利用session傳遞了一個值");
 9     return "main";
10 } 

在mian.jsp里接收session對象傳過來的值:

1 <body>
2     session:${sessionScope.session }
3 </body>

然后我們在瀏覽器里訪問控制器demo4,在瀏覽器輸入:http://localhost:8080/springmvc02/demo3,回車

 

 三、HandlerMethod參數的注解

所謂的handlerMethod即是上面的這些demo方法,在編寫這些handlerMethod時,我們可以給這些方法的參數添加注解,用以控制參數。

(一)給參數取別名

當控制器方法的參數名稱和jsp頁面的參數的名稱不相同時,可以使用@RequestParam()注解來實現給控制器方法參數取別名。但實際上這個注解做的事情是將請求中的參數(name1和age1)綁定到控制器中的參數(name和age)里

1.在方法對應的參數之前添加@RequestParam(value="參數名稱")注解就可以實現給參數取別名

2.注意,這里的value的值要和jsp頁面的name相同

3.當@RequestParam()注解括號里面只有value時,可以將注解簡化為@RequestParam("參數名稱")(示例里面的參數age)

在DemoController里添加一個demo5方法,如下:

 1 /**
 2 * 參數注解1:給參數取別名
 3 * 例如:Controller的方法里面的參數名和jsp頁面的參數名不一致時可以給參數取別名
 4 * @param name
 5 * @param age
 6 * @return
 7 */
 8 @RequestMapping("demo5")
 9 public String demo5(@RequestParam(value="name1")String name, @RequestParam("age1")int age){
10     System.out.println("執行demo5"+" "+name+" "+age);
11     return "main";
12 }

index.jsp如下:

1 <body>
2     <form action="demo5" method="post">
3         <input type="text" name="name1"/>
4         <input type="text" name="age1"/>
5         <input type="submit" value="提交"/> 
6     </form>
7 </body>

在瀏覽器里輸入:http://localhost:8080/springmvc02/index.jsp,回車

(二)給參數一個默認值

當不管什么情況下,我們都需要給控制器里面的參數一個默認值時,這個時候就可以使用到注解@RequestParam()的另外一個屬性:defaultValue屬性。

1.在參數前添加注解@RequestParam(defaultValue="參數的默認值")就可以給參數一個默認值,參數的默認值是defaultValue的值

2.當我們不給出這個參數的值時,該參數就取默認值

在DemoController里添加一個demo6方法,如下:

 1 /**
 2 * 參數注解2:給參數一個默認值
 3 * 如果不給出這個參數的值,該參數就取默認值
 4 * 例如:在分頁功能的Controller里面給pageSize和pageNumber一個默認值既可以少寫幾個非空判斷了
 5 * @param name
 6 * @param age
 7 * @return
 8 */
 9 @RequestMapping("demo6")
10 public String demo6(@RequestParam(defaultValue="lmw")String name, @RequestParam(defaultValue="21")int age){
11     System.out.println("執行demo6"+" "+name+" "+age);
12     return "main";
13 }

index.jsp如下:

1 <body>
2     <form action="demo6" method="post">
3         <input type="text" name="name"/>
4         <input type="text" name="age"/>
5         <input type="submit" value="提交"/> 
6     </form>
7 </body>

在瀏覽器里輸入:http://localhost:8080/springmvc02/index.jsp,回車

(三)設置參數為必須值

如果控制器方法里面的參數是必須給出的,這個時候就需要使用到@RequestParam()的第三個屬性:required屬性。required是boolen類型,默認為true,即必須要給出這個參數,否則就會報異常。

1.在參數前添加注解@RequestParam(required=true)設置參數為必須值

2.如果不給出這個參數就會報異常

在DemoController里添加一個demo7方法,如下:

 1 /**
 2 * 參數注解3:設置參數為必須值
 3 * 如果不給出這個參數就會報異常
 4 * 例如:name作為SQL查詢語句的條件這種情況,我們把name設置為必須值
 5 * @param name
 6 * @param age
 7 * @return
 8 */
 9 @RequestMapping("demo7")
10 public String demo7(@RequestParam(required=true)String name, @RequestParam(required=true)int age){
11     System.out.println("執行demo7"+" "+name+" "+age);
12     return "main";
13 }

index.jsp頁面將from表單里面的action的值改為demo7,其他不變,在瀏覽器里輸入:http://localhost:8080/springmvc02/index.jsp回車

四、復雜參數的傳遞

(一)傳遞多個同名參數的值

除了上面的基本數據類型的參數和對象類型的參數傳遞,那么當表單里有復選框的時候,我們要怎么將勾選中的復選框的值傳到控制器里面呢?也就是說當請求的參數中包含多個同名參數的時候,我們要如何實現這些參數的傳遞呢?

那么首先就要思考一個問題,我們要將這些同名參數存儲在一個什么樣容器里面呢?一個很簡單的方式,我們可以使用一個List來存儲這些同名參數的值。那么是不是同之前一樣,只要我們將List的對象名改為input的name就可以了呢?答案是否定的,即使你這樣做SpringMVC也無法對List容器進行注入的,因為我們還沒有將這些參數與List進行綁定,所以需要使用到注解@RequestParam()來將請求中的參數與List進行綁定。給出一個示例如下:

在DemoController里添加一個demo8方法,如下。

 1 /**
 2 * 當請求參數中包含多個同名參數的情況,如復選框傳遞的參數
 3 * @param name
 4 * @param age
 5 * @param hobbyList 
 6 * @return
 7 */
 8 @RequestMapping("demo8")
 9 public String demo8(String name, int age, @RequestParam("hobby")List<String> hobbyList){
10     System.out.println("執行demo8"+" "+name+" "+age+" "+hobbyList.toString());
11     return "main";
12 }

index.jsp頁面如下:

 1 <body>
 2     <form action="demo8" method="post">
 3         <input type="text" name="name"/>
 4         <input type="text" name="age"/>
 5         <input type="checkbox" name="hobby" value="健身"/>
 6         <input type="checkbox" name="hobby" value="游泳"/>
 7         <input type="checkbox" name="hobby" value="讀書"/>
 8         <input type="checkbox" name="hobby" value="玩游戲"/>
 9         <input type="submit" value="提交"/> 
10     </form>
11 </body>

在瀏覽器里輸入:http://localhost:8080/springmvc02/index.jsp回車

(二)請求參數名為對象名.屬性名的格式

顯然,針對這種特殊的情況,使用普通對象類型參數的傳遞方式無法實現要求。那么此時我們就需要對這個"."前面的對象進行一個封裝了,采取的方法是將這個對象封裝在另外一個類里面,使其成為該類的一個屬性。給出一個示例如下:

index.jsp如下:

1 <body>
2     <form action="demo9" method="post">
3         <input type="text" name="peo.name"/>
4         <input type="text" name="peo.age"/>
5         <input type="submit" value="提交"/> 
6     </form>
7 </body>

根據上面name的值,我們對People類進行封裝,示例如下:

 1 package com.lmw.pojo;
 2 
 3 public class Peo {
 4     private People peo;
 5 
 6     public People getPeo() {
 7         return peo;
 8     }
 9 
10     public void setPeo(People peo) {
11         this.peo = peo;
12     }
13 
14     @Override
15     public String toString() {
16         return "Peo [peo=" + peo + "]";
17     }
18 }

在DemoController里添加一個demo9方法,如下:

 1 Peo example = new Peo();
 2 /**
 3 * 請求參數名為對象名.屬性名的格式的情況
 4 * 請求參數為集合對象類型
 5 * @param example
 6 * @return
 7 */
 8 @RequestMapping("demo9")
 9 public String demo9(Peo example){
10     System.out.println("執行demo9"+" "+example);
11     return "main";
12 }

在瀏覽器里輸入:http://localhost:8080/springmvc02/index.jsp回車

類似的,當請求參數名為如下這種格式時,我們也可以采取相同的做法。

1 <body>
2     <form action="demo9" method="post">
3         <input type="text" name="peo[0].name"/>
4         <input type="text" name="peo[0].age"/>
5         <input type="text" name="peo[1].name"/>
6         <input type="text" name="peo[1].age"/>
7         <input type="submit" value="提交"/> 
8     </form>
9 </body>

這種情況做法和上面類似,同樣是將對象進行封裝,具體如何實現大家可以自己去試一試。

(三)restful風格傳值方式

所謂REST是REpresentational State Transfer的縮寫(一般中文翻譯為表述性狀態轉移),REST 是一種體系結構,具體可自行百度。使用這種風格開發最顯而易見的就是傳遞參數的時候不再是url?paramname1=paramvalue1&paramname2=paramvalue2這種格式,而是變成了https://www.jianshu.com/p/91600da4df95這種格式,每個"/"后面的緊跟着的是參數。那么在SpringMVC中如何實現這種方式傳遞參數呢?

在DemoController里添加一個demo10方法,示例代碼如下:

 1 /**
 2 * restful傳值方式
 3 * @param name
 4 * @param age
 5 * @return
 6 */
 7 @RequestMapping("demo10/{name}/{age1}")
 8 public String demo10(@PathVariable String name, @PathVariable(value="age1")int age){
 9     System.out.println(name+" "+age);
10     return "main";
11 }

注意:

1.需要使用到請求映射注解——@RequestMapping,這個注解會將 HTTP 請求映射到SpringMVC控制器的處理方法上。你只需要像這樣配置這個注解:@RequestMapping("控制器名稱/{XXX}/{XXX}")。其中,每一個{XXX}表示URL請求中的參數的占位符。

2.在每個參數之前需要添加注解@PathVariable。這個注解可以將請求的URL中的參數映射到控制器處理方法的參數上

3.如果請求中的參數名和注解里面的參數名不一致,需要給注解@PathVariable一個value,這個value的值要和請求的參數名相同(上面的參數age,在注解里面的名稱是age1,類似於給控制器里面的參數取一個別名)

在瀏覽器里輸入:http://localhost:8080/springmvc02/demo10/lmw/21回車即可在控制台看到效果

 

 未完待續。。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM