SpringMVC 獲取請求參數

1.獲取Request response對象

在SpringMVC的註解開發中,能夠選擇性的接收Request和Response對象來使用html

2.獲取request對象請求參數

a.經過request對象獲取

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

    /**
     * 獲取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=18web

b.直接接收請求參數

能夠在Controller方法中直接接收請求參數相同否定方法形參,能夠直接獲得請求參數的值。spring

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.jsptomcat

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

控制檯輸出:app

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.jspjsp

頁面跳轉: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";
    }

 訪問

 

控制檯輸出

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

相關文章
相關標籤/搜索