(1) 普通方式-請求引數名和Controller方法的引數一致

 

 1 @Controller
 2 @RequestMapping("/param")
 3 public class TestParamController {
 4     private static final Logger logger = LoggerFactory.getLogger(TestParamController.class);
 5     /**
 6      * 請求引數名和Controller方法的引數一致
 7      * produces 設定返回引數的編碼格式可以設定返回資料的型別以及編碼,可以是json或者xml
 8      * {
 9      *     @RequestMapping(value="/xxx",produces = {"application/json;charset=UTF-8"})
10      *      或
11      *     @RequestMapping(value="/xxx",produces = {"application/xml;charset=UTF-8"})
12      *      或
13      *     @RequestMapping(value="/xxx",produces = "{text/html;charset=utf-8}")
14      * }
15      * @param name 使用者名稱
16      * @param pwd 密碼
17      * @return
18      *
19      */
20     @RequestMapping(value = "/add", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
21     @ResponseBody
22     public String addUser(String name, String pwd){
23         logger.debug("name:" + name + ",pwd:" + pwd);
24         return "name:" + name + ",pwd:" + pwd;
25     }
26 
27 }

如下圖所示:

通過訪問:http://localhost:8080/sty/param/add.action?name=張三&pwd=123456

          

 

 (2) 物件方式-請求引數名和Controller方法中的物件的引數一致

 

@Controller
@RequestMapping("/param")
public class TestParamController {
    private static final Logger logger = LoggerFactory.getLogger(TestParamController.class);
    /**
     * 請求引數名和Controller方法的引數一致
     * produces 設定返回引數的編碼格式可以設定返回資料的型別以及編碼,可以是json或者xml
     * }
     * @param user 使用者資訊
     * @return
     *
     */
    @RequestMapping(value = "/addByObject", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public String addUserByObject(User user){
        logger.debug("name:" + user.getName() + ",pwd:" + user.getPwd());
        return "name:" + user.getName() + ",pwd:" + user.getPwd();
    }
}

如下圖所示:

通過訪問:http://localhost:8080/sty/param/addByObject.action?name=張三&pwd=123456 。

 

 

(3) 自定義方法引數名-當請求引數名與方法引數名不一致時

 

  注意可以在引數中增加@RequestParam註解。如果在方法中的引數增加了該註解,說明請求的url必須帶該帶有該引數,否則不能執行該方法。如果在方法中的引數沒有增加該註解,說明請求的url無需帶有該引數,也能繼續執行該方法。

  @RequestParam(defaultValue="0")可設定預設值(僅當傳入引數為空時)。

  @RequestParam(value="id")可接受傳入引數為id的值,覆蓋該註解註釋的欄位。

  @RequestParam(name="name",defaultValue = "李四") String u_name   如果傳入欄位”name”為空,預設u_name的值為”李四”。若傳入”name”不為空,預設u_name值為傳入值。

以下只該出方法:

/**
 * 自定義方法引數名-當請求引數名與方法引數名不一致時
 * @param u_name 使用者名稱
 * @param u_pwd 密碼
 * @return
 */
@RequestMapping(value = "/addByDifName", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
@ResponseBody
public String addUserByDifName(@RequestParam("name") String u_name, @RequestParam("pwd")String u_pwd){
    logger.debug("name:" + u_name + ",pwd:" + u_pwd);
    return "name:" + u_name + ",pwd:" + u_pwd;
}

如下圖所示:

通過訪問:http://localhost:8080/sty/param/addUserByDifName.action?name=張三&pwd=123456 。

 

 

(4) HttpServletRequest方式

 

  以下只給出該方法:

/**

 * 通過HttpServletRequest接收

 * @param request

 * @return

 */

@RequestMapping(value = "/addByHttpServletRequest", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})

@ResponseBody

public String addUserByHttpServletRequest(HttpServletRequest request){

    String name = request.getParameter("name");

    String pwd = request.getParameter("pwd");

    logger.debug("name:" + name + ",pwd:" + pwd);

    return "name:" + name + ",pwd:" + pwd;

}

如下圖所示:

通過訪問:http://localhost:8080/sty/param/addByHttpServletRequest.action?name=張三&pwd=123456

 

 

(5) @PathVariable獲取路徑中的引數接收

 

         參考:https://www.iteye.com/blog/zhlj11-1885005 。

   注:url含有中文名稱時,因為編碼問題,無法進行對映,需要修改tomcat下的conf資料夾下的server.xml中的URIEncoding=”UTF-8”,對URL編碼設定就可以解決中文問題。

對於經常遇到路徑在有符號”.”問題,因為springmvc預設是把點後面的資訊作為檔案字尾,需要修改預設值:

<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"> 
              <property name="interceptors" ref="localeChangeInterceptor"/>
              <property name="useDefaultSuffixPattern" value="false" /> 
       </bean> 

  另外,這時候如果只設置這個,請求可以傳遞到對於的controller,但傳過去的資料會有問題,只會傳最後一個點前面的資料,除非你在最後加上“/”,比如/news/測試.點/  這樣就會把“測試.點”當作整體,不然只會得到“測試”。這時候我們可以這樣設定@RequestMapping("/news/{title:.*}") 

以下只給出該方法(本次不進行中文及特殊符號測試):

/**

 * 通過@PathVariable獲取路徑中的引數 

 * @param name 使用者名稱

 * @param pwd 密碼

 * @return

 */

@RequestMapping(value = "/add/{name}/{pwd}", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})

@ResponseBody

public String addUserByPathVariable(@PathVariable String name, @PathVariable String pwd){

    logger.debug("name:" + name + ",pwd:" + pwd);

    return "name:" + name + ",pwd:" + pwd;

}

 

如下圖所示:

通過訪問:http://localhost:8080/sty/param/add/zhangsan/123456.action

 

 

(6) @RequestBody-JSON方式接收

 

  以上方式(1)/(2)/)(3)/(4)/(5)都是非JSON方式,也就是說如果使用JSON方式提交,會報錯(在第二種物件方式中,將get請求方式修改為POST,並將上送資料修改為JSON串方式):

       此時未引入jackson-databind.jar依賴。並在springmvc.xml檔案未進行開啟json格式的支援,也就是說未加入以下程式碼:

<!-- 同時開啟json格式的支援-->
<mvc:annotation-driven></mvc:annotation-driven>

  提交請求列印未有報錯,但是返回的資料為null,如圖所示:

   

         若開啟json格式的支援,測試也如上圖所示,也並能正常返回。

         原因:因為為在欄位名稱之前未使用@RequestBody註解。

eg1(測試普通物件)

         程式碼如下所示,

/**

 * RequestBody-JSON 物件方式

 * @param user

 * @return

 */

@RequestMapping(value = "/addByObjectJSON", produces = {"application/json;charset=UTF-8"})

@ResponseBody

public String addUserByObjectJSON(@RequestBody User user){

    logger.debug("name:" + user.getName() + ",pwd:" + user.getPwd());

    return "name:" + user.getName() + ",pwd:" + user.getPwd();

}
測試結果如圖所示(訪問 http://localhost:8080/sty/param/addByObjectJSON.action ):

 

eg2(測試List物件)

程式碼如下所示,

/**
 * RequestBody-JSON List物件方式
 * @param users
 * @return
 */
@RequestMapping(value = "/addByListJSON", produces = {"application/json;charset=UTF-8"})
@ResponseBody
public String addUsersByListJSON(@RequestBody List<User> users){
    StringBuilder sb = new StringBuilder("{");
    if(null != users){
        for(User user : users){
            sb.append("{" + "name:" + user.getName() + ",pwd:" + user.getPwd() + "}");
        }
    }
    sb.append("}");
    logger.debug(sb.toString());
    return sb.toString();
}

   測試結果

  測試結果如圖所示(訪問 http://localhost:8080/sty/param/addByListJSON.action  ):

   

eg3(測試Map物件)

程式碼如下圖所示:

/**

 * RequestBody-JSON Map物件方式

 * @param users

 * @return

 */

@RequestMapping(value = "/addByMapJSON", produces = {"application/json;charset=UTF-8"})

@ResponseBody

public String addUsersByMapJSON(@RequestBody Map<String, User> users){

    StringBuilder sb = new StringBuilder("{");

    if(null != users){

        Iterator it = users.keySet().iterator();

        while(it.hasNext()){

            User user = users.get(it.next());

            sb.append("{" + "name:" + user.getName() + ",pwd:" + user.getPwd() + "}");

        }

    }

    sb.append("}");

    logger.debug(sb.toString());

    return sb.toString();

}

   測試結果

測試結果如圖所示(訪問 http://localhost:8080/sty/param/addByMapJSON.action ):

另外附部分原始碼:

  User.java

package com.mjs.study.action.dto;

/**
 * @Description 
 * @ClassName User
 * @Author Administrator
 * @Data 2019/10/13 2:43
 * @Version 1.0
 */
public class User {
    private String name;
    private String pwd;
    private String sex;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }
}
View Code
 TestParamController.java 
package com.mjs.study.action;

import com.github.pagehelper.PageInfo;
import com.mjs.study.action.dto.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @Description 測試springmvc傳入引數
 * @ClassName TestParamController
 * @Author Administrator
 * @Data 2019/10/13 1:33
 * @Version 1.0
 */
@Controller
@RequestMapping("/param")
public class TestParamController {
    private static final Logger logger = LoggerFactory.getLogger(TestParamController.class);
    /**
     * 請求引數名和Controller方法的引數一致
     * produces 設定返回引數的編碼格式 可以設定返回資料的型別以及編碼,可以是json或者xml
     * {
     *     @RequestMapping(value="/xxx",produces = {"application/json;charset=UTF-8"})
     *      或
     *     @RequestMapping(value="/xxx",produces = {"application/xml;charset=UTF-8"})
     *      或
     *     @RequestMapping(value="/xxx",produces = "{text/html;charset=utf-8}")
     * }
     * @param name 使用者名稱
     * @param pwd 密碼
     * @return
     *
     */
    @RequestMapping(value = "/add", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public String addUser(String name, String pwd){
        logger.debug("name:" + name + ",pwd:" + pwd);
        return "name:" + name + ",pwd:" + pwd;
    }

    /**
     * 自定義方法引數名-當請求引數名與方法引數名不一致時
     * @param u_name 使用者名稱
     * @param u_pwd 密碼
     * @return
     */
    @RequestMapping(value = "/addByDifName", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public String addUserByDifName(@RequestParam(name="name",defaultValue = "李四") String u_name, @RequestParam("pwd")String u_pwd){
        logger.debug("name:" + u_name + ",pwd:" + u_pwd);
        return "name:" + u_name + ",pwd:" + u_pwd;
    }

    /**
     * 請求引數名和Controller方法的引數一致
     * produces 設定返回引數的編碼格式 可以設定返回資料的型別以及編碼,可以是json或者xml
     * @param user 使用者資訊
     * @return
     *
     */
    @RequestMapping(value = "/addByObject", produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public String addUserByObject(User user){
        logger.debug("name:" + user.getName() + ",pwd:" + user.getPwd());
        return "name:" + user.getName() + ",pwd:" + user.getPwd();
    }

    /**
     * RequestBody-JSON 物件方式
     * @param user
     * @return
     */
    @RequestMapping(value = "/addByObjectJSON", produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public String addUserByObjectJSON(@RequestBody User user){
        logger.debug("name:" + user.getName() + ",pwd:" + user.getPwd());
        return "name:" + user.getName() + ",pwd:" + user.getPwd();
    }

    /**
     * RequestBody-JSON List物件方式
     * @param users
     * @return
     */
    @RequestMapping(value = "/addByListJSON", produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public String addUsersByListJSON(@RequestBody List<User> users){
        StringBuilder sb = new StringBuilder("{");
        if(null != users){
            for(User user : users){
                sb.append("{" + "name:" + user.getName() + ",pwd:" + user.getPwd() + "}");
            }
        }
        sb.append("}");
        logger.debug(sb.toString());
        return sb.toString();
    }
    /**
     * RequestBody-JSON Map物件方式
     * @param users
     * @return
     */
    @RequestMapping(value = "/addByMapJSON", produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public String addUsersByMapJSON(@RequestBody Map<String, User> users){
        StringBuilder sb = new StringBuilder("{");
        if(null != users){
            Iterator it = users.keySet().iterator();
            while(it.hasNext()){
                User user = users.get(it.next());
                sb.append("{" + "name:" + user.getName() + ",pwd:" + user.getPwd() + "}");
            }
        }
        sb.append("}");
        logger.debug(sb.toString());
        return sb.toString();
    }
    /**
     * 通過HttpServletRequest接收
     * @param request
     * @return
     */
    @RequestMapping(value = "/addByHttpServletRequest", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public String addUserByHttpServletRequest(HttpServletRequest request){
        String name = request.getParameter("name");
        String pwd = request.getParameter("pwd");
        logger.debug("name:" + name + ",pwd:" + pwd);
        return "name:" + name + ",pwd:" + pwd;
    }

    /**
     * 通過@PathVariable獲取路徑中的引數
     * @param name 使用者名稱
     * @param pwd 密碼
     * @return
     */
    @RequestMapping(value = "/add/{name}/{pwd}", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public String addUserByPathVariable(@PathVariable String name, @PathVariable String pwd){
        logger.debug("name:" + name + ",pwd:" + pwd);
        return "name:" + name + ",pwd:" + pwd;
    }
}
View Code

  該部分和個人github部分內容同