SpringMVC 獲取請求參數


1.獲取Request response對象

在SpringMVC的注解開發中,可以選擇性的接收Request和Response對象來使用

2.獲取request對象請求參數

a.通過request對象獲取

通過request對象獲取請求參數時,類型不一致時需要手動轉換。int age = Integer.parseInt(request.getParameter("age"));

    /**
     * 獲取request 和 response
     */
    @RequestMapping("/hello3.action")
    public String hello3(HttpServletRequest request,
            HttpServletResponse response,
            Model model){
        String username = request.getParameter("username");
        int age = Integer.parseInt(request.getParameter("age"));
        // 獲取某個請求頭信息
        String al = request.getHeader("Accept-Language");
        System.out.println(al);
        System.out.println(username + "~~" + age);
        model.addAttribute("msg","hello springmvc~");
        return "hello";
    }

訪問:http://localhost/SpringMVC2/hello3.action?username=cjj&age=18

b.直接接收請求參數

可以在Controller方法中直接接收請求參數相同否認方法形參,可以直接得到請求參數的值。

WebRoot目錄下創建一個from表單

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  </head>
  
  <body>
    <form action="${pageContext.request.contextPath}/hello4.action" method="POST">
        <table>
            <tr>
                <td>用戶名</td>
                <td><input type="text" name="username"/></td>
            </tr>
            <tr>
                <td>密碼</td>
                <td><input type="text" name="password"/></td>
            </tr>
            <tr>
                <td>年齡</td>
                <td><input type="text" name="age"/></td>
            </tr>
            <tr>
                <td colspan="2"><input type="submit" value="提交"/></td>
            </tr>
        </table>    
    
    </form>
  </body>
</html>
from.jsp
    /**
     * 快速獲得請求參數
     */
    @RequestMapping("/hello4.action")
    public String hello4(String username, String password, int age, Model model){
        System.out.println(username+"--"+password+"--"+age);
        model.addAttribute("msg", "hello springmvc ~~");
        return "hello";
    }

訪問:http://localhost/SpringMVC2/from.jsp

點擊提交,跳轉到:http://localhost/SpringMVC2/hello4.action

控制台輸出:

c.自動封裝請求參數信息到bean

SpringMVC框架可以自動將請求參數封裝到bean中,要求bean中必須提供屬性的setXxx方法,且bean的屬性名和請求參數的名字必須一致,才可以自動設置。

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  </head>
  
  <body>
    <form action="${pageContext.request.contextPath}/hello5.action" method="POST">
        <table>
            <tr>
                <td>用戶名</td>
                <td><input type="text" name="username"/></td>
            </tr>
            <tr>
                <td>密碼</td>
                <td><input type="text" name="password"/></td>
            </tr>
            <tr>
                <td>年齡</td>
                <td><input type="text" name="age"/></td>
            </tr>
            <tr>
                <td colspan="2"><input type="submit" value="提交"/></td>
            </tr>
        </table>    
    
    </form>
  </body>
</html>
form.jsp
package cn.tedu.springmvc.beans;

public class User {
    private String username;
    private String password;
    private int age;
    
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}
User.java
    /**
     * 封裝請求參數到bean
     */
    @RequestMapping("/hello5.action")
    public String hello5(User user, Model model){
        System.out.println(user);
        model.addAttribute("msg", "hello springmvc~~");
        return "hello";
    }

訪問:http://localhost/SpringMVC2/from.jsp

頁面跳轉:http://localhost/SpringMVC2/hello5.action

控制台輸出:

d.處理復雜類型

如果自動封裝的bean中存在復雜類型,只要該復雜類型的屬性同樣具有setXxx方法,

則可以在請求參數中包含[bean中復雜類型].[屬性]的方法為該復雜類型的參數復制,

從而實現自動封裝bean的過程中處理其中復雜類型。

package cn.tedu.springmvc.beans;

public class User {
    private String username;
    private String password;
    private int age;
    private Dog dog;
    
    public Dog getDog() {
        return dog;
    }
    
    public void setDog(Dog dog) {
        this.dog = dog;
    }
    
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "User [username=" + username + ", password=" + password
                + ", age=" + age + ", dog=" + dog + "]";
    }
}
User.java
package cn.tedu.springmvc.beans;

public class Dog {
    private String name;
    private int age;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "Dog [name=" + name + ", age=" + age + "]";
    }
}
Dog.java
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  </head>
  
  <body>
    <form action="${pageContext.request.contextPath}/hello5.action" method="POST">
        <table>
            <tr>
                <td>用戶名</td>
                <td><input type="text" name="dog.name"/></td>
            </tr>
            <tr>
                <td>年齡</td>
                <td><input type="text" name="dog.age"/></td>
            </tr>
            <tr>
                <td colspan="2"><input type="submit" value="提交"/></td>
            </tr>
        </table>    
    
    </form>
  </body>
</html>
from.jsp
    /**
     * 封裝請求參數到bean
     */
    @RequestMapping("/hello5.action")
    public String hello5(User user, Model model){
        System.out.println(user);
        model.addAttribute("msg", "hello springmvc~~");
        return "hello";
    }

e.請求參數中的名稱和屬性名不同的處理@RequParam

可以通過@RequestParam來修飾Controller方法中用來接收請求參數的形參,

有如下屬性可以配置:

value來指定將哪個請求參數復制給當前形參

將required聲明為true,則請求參數中必須有該屬性,如果沒有客戶端將收到400

 

defaultValue可以設定當前形參的默認值

public String hello5(User user, @RequestParam(value="hobby",required=true)String[] hobbys, Model model){

f.請求參數中存在多個同名值

如果請求參數中存在多個同名值

 

此時直接獲取,會得到一個用逗號分隔的字符串

    /**
     * 接收同名的多值請求參數
     */
    @RequestMapping("/hello6")
    public String hello6(String like,Model model){
        System.out.println(like);
        model.addAttribute("msg", "hello springmvc~~");
        return "hello";
    }

訪問

控制台輸出:

也可以修改Controller方法的形參為數據類型,則直接接收到一個數組

    /**
     * 接收同名的多值請求參數
     */
    @RequestMapping("/hello6")
    public String hello6(String[] like,Model model){
        System.out.println(Arrays.toString(like));
        model.addAttribute("msg", "hello springmvc~~");
        return "hello";
    }

 訪問

控制台輸出

g.請求參數中的中文亂碼修改

SpringMVC提供了過濾器用來解決全站亂碼

  <!-- 配置SpringMVC亂碼解決過濾器 -->
  <filter>
      <filter-name>characterEncodingFilter</filter-name>
      <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
      <init-param>
          <param-name>encoding</param-name>
          <param-value>utf-8</param-value>
      </init-param>
  </filter>
  <filter-mapping>
      <filter-name>characterEncodingFilter</filter-name>
      <url-pattern>/*</url-pattern>
  </filter-mapping>

這種方式只能解決POST提交的亂碼,對GET方式提交的亂碼無效!

此時只能手動進行編解碼,解決GET方式請求參數亂碼

也可以直接修改Tomcat中鏈接器的配置來使tomcat默認采用指定編碼處理請求參數

但是這種方式不建議大家使用,因為生產環境下不一定允許修改此項。

h.日期數據的處理

在SpringMVC中解析頁面提交的參數時,日期默認格式是yyyy/MM/dd,並不符合中國人平常的使用習慣,

此時可以配置適配器自己來指定格式

  /**
     * 日期格式處理
     * @throws UnsupportedEncodingException 
     */
    @RequestMapping("/hello8.action")
    public String hello8(Date birthday,Model model) throws UnsupportedEncodingException{
        System.out.println(birthday);
        model.addAttribute("msg", "hello springMvc4,hello World4~");
        return "hello";
    }
    
    public void InitBinder(ServletRequestDataBinder binder){
        binder.registerCustomEditor(Date.class, 
                new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),true));
    }
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  </head>
  
  <body>
    <form action="${pageContext.request.contextPath}/hello8.action" method="POST">
        <table>
            <tr>
                <td>用戶名</td>
                <td><input type="text" name="username"/></td>
            </tr>
            <tr>
                <td>年齡</td>
                <td><input type="text" name="age"/></td>
            </tr>
            <tr>
                  <td>狗名</td>
                  <td><input type="text" name="dog.name"/></td>
              </tr>
              <tr>
                  <td>狗齡</td>
                  <td><input type="text" name="dog.age"/></td>
              </tr>
            <tr>
                  <td>出生日期</td>
                  <td><input type="text" name="birthday"/></td>
              </tr>
            <tr>
                <td>愛好</td>
                  <td>
                      <input type="checkbox" name="like" value="zq"/>足球
                      <input type="checkbox" name="like" value="lq"/>籃球
                      <input type="checkbox" name="like" value="pq"/>排球
                      <input type="checkbox" name="like" value="qq"/>鉛球
                  </td>            
            </tr>
            <tr>
                <td colspan="2"><input type="submit" value="提交"/></td>
            </tr>
        </table>    
    
    </form>
  </body>
</html>
form.jsp

訪問

控制台輸出:

i.SpringMVC文件上傳

(1)准備上傳表單

文件上傳表單必須滿足如下三個條件

a)表單必須是POST提交的

b)表單必須是enctype=“multipart/form-data”

c)文件上傳必須有name屬性

(2)在配置文件中配置文件上傳工具

 

 (3)在Controller中實現文件上傳

    /**
     * 文件上傳
     * @throws IOException 
     */
    @RequestMapping("/hello9.action")
    public String hello9(MultipartFile fx, Model model) throws IOException{
        System.out.println(fx.getOriginalFilename());
        FileUtils.writeByteArrayToFile(new File("E://"+fx.getOriginalFilename()), fx.getBytes());
        
        model.addAttribute("msg", "hello springmvc ~~");
        return "hello";
    }

j.RESTul風格的請求參數處理

(1)RESTul風格的請求

普通get請求:

RESTFul風格的請求:

 

(2)SpringMVC對RESTFul風格的請求的我處理

    /**
     * RESTFul支持
     */
    @RequestMapping("/hello10/{username}/{age}.action")
    public String hello10(@PathVariable String username, @PathVariable int age, Model model){
        System.out.println(username+"~"+age);
        model.addAttribute("msg", "hello springmvc~~");
        return "hello";
    }

 訪問

 

控制台輸出

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


免責聲明!

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



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