springmvc----參數綁定

springmvc學習記錄第二篇----參數綁定


記錄下來可以讓自己記得更牢,忘了也可以再看看。

springmvc參數綁定

1 類似servlet的直接用request接收參數

2 簡單類型

3 pojo類型

4  數組類型

5 map類型

6 list類型

大概要說的是以上五種類型的參數綁定。

進入正題

準備工作:

所有工作是在第一篇springmvc框架搭建的基礎上進行。

1 request接收參數

用HttpServletRequest接收參數,需要servlet-api jar包

在pom.xml中添加即可

<dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
    </dependency>

以下爲對應的測試類,方法

package com.soft.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

@Controller
public class TestParamController {

    @RequestMapping(value="/testParam01")
    public ModelAndView testParam01(HttpServletRequest request){
        // 通過HttpServletRequest進行參數綁定。
        String requestParam = request.getParameter("name");
        ModelAndView model = new ModelAndView();
        model.addObject("name",requestParam);
        model.setViewName("test/testParam");
        return model;
    }
}

testParam.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ page isELIgnored="false"%>
<html>
<head>
    <title>Title</title>
</head>
<body>

${name}
</body>
</html>
輸入請求進行測試

http://localhost:8080/testParam01?name=testParam

測試結果

idea  debug結果


頁面顯示


通過HttpServletRequest參數綁定完畢。

2 簡單類型參數綁定

2..1 傳入參數名跟方法參數列表名一致,就可以進行綁定

java代碼

   /**
     * 簡單類型參數綁定,只需要頁面傳入參數名跟參數列表中的名稱一致就可以綁定成功
     * @param paramInt   int類型參數
     * @param paramStr  String類型參數
     * @param paramChar  char類型參數
     * @return ModelAndView
     */
    @RequestMapping(value="/testParam02")
    public ModelAndView testParam02(int paramInt,String paramStr,char paramChar){
        ModelAndView model = new ModelAndView();
        // 將傳入綁定成功的參數在頁面顯示。
        model.addObject("paramInt",paramInt);
        model.addObject("paramStr",paramStr);
        model.addObject("paramChar",paramChar);
        model.setViewName("test/testParam");
        return model;
    }
jsp頁面接收參數代碼

int類型參數${paramInt}<br/>
String類型參數${paramStr}<br/>
char類型參數${paramChar}<br/>

測試結果:

idea dubug結果


頁面顯示結果:


測試鏈接:http://localhost:8080/testParam02?paramInt=1&paramStr=testStrParam&paramChar=A

簡單參數綁定測試完畢。關於測試鏈接,如果不想用這麼長的鏈接,可以自己用表單傳遞。效果一樣。

3 pojo類型

要點:pojo的屬性名跟傳入參數名一致就可以綁定。

3.1先定義一個pojo用戶參數綁定。

package com.soft.po;

/**
 * Created by xuweiwei on 2017/8/19.
 */
public class ParamVo {

    private String name;
    private String password;

    public String getName() {
        return name;
    }

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

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
測試pojo參數綁定方法。
    /**
     * pojo參數綁定,只需要頁面傳入參數名跟pojo中的屬性名一致就可以綁定成功
     * @return ModelAndView
     */
    @RequestMapping(value="/testParam03")
    public ModelAndView testParam03(ParamVo paramVo){
        ModelAndView model = new ModelAndView();
        // 將傳入綁定成功的參數在頁面顯示。
        model.addObject("paramVo",paramVo);
        model.setViewName("test/testParam");
        return model;
    }
jsp頁面顯示信息
<%-- pojo綁定參數顯示 --%>
ParamVo name  :${paramVo.name}<br/>
ParamVo password  :${paramVo.password}<br/>
測試參數地址:http://localhost:8080/testParam03?name=tom&password=123456

測試結果:

idea debug結果:



瀏覽器顯示結果:


4 數組類型參數綁定。

要點:頁面要綁定的屬性的name屬性,跟方法參數名一樣。

例如:

<form action="${pageContext.request.contextPath }/testParam04">
    <input type="text" name="arr" value="123"><br/>
    <input type="text" name="arr" value="321"><br/>
    <input type="text" name="arr" value="456"><br/>
    <input type="text" name="arr" value="567"><br/>
    <input type="submit" value="提交">
</form>
上面的name屬性爲arr,則接收參數的屬性名爲arr才能接收到頁面參數。

    /**
     * 數組參數綁定:頁面有一組name屬性爲arr。
     * @return ModelAndView
     */
    @RequestMapping(value="/testParam04")
    public ModelAndView testParam04(String[] arr){
        for(String str:arr){
            System.out.println(str);
        }
        ModelAndView model = new ModelAndView();
        // 將傳入綁定成功的參數在頁面顯示。
        model.addObject("arr",arr);
        model.setViewName("test/testParam");
        return model;
    }
注意上面的參數跟jsp form中input 的name屬性必須對上才能綁定成功

綁定成功後頁面回顯。jsp顯示用

<%-- 數組參數綁定後頁面顯示結果 --%>
<c:forEach items="${arr}" var="str">
    ${str}<br/>
</c:forEach>


jsp頁面輸入參數


點擊提交後,進入後臺action。

idea  debug


可以看到數組參數已經傳進來了。

然後頁面顯示。


好了數組參數綁定完畢。要點就是,頁面name屬性必須跟後臺接收參數的數組的名稱一致。


5 map參數綁定。

要點:map是一組組鍵值對。即  key/value。

map參數綁定,頁面name屬性要與map的可以對上就可以綁定。

頁面屬性寫法:

<form action="${pageContext.request.contextPath }/testParam05" method="post">
    姓名:<input type="text" name="mapParam['name']"><br/>
    年齡:<input type="text" name="mapParam['age']" ><br/>
    班級:<input type="text" name="mapParam['class']" ><br/>
    分數:<input type="text" name="mapParam['grade']" ><br/>
    <input type="submit" value="提交">
</form>
主要看name屬性的寫法。

mapParam對應vo中的map屬性名,['name']即對應着map中的一個name key,

vo

package com.soft.po;

import java.util.Map;

/**
 * Created by xuweiwei on 2017/8/19.
 */
public class ParamVo {

    private String name;
    private String password;

    public Map<String, Object> getMapParam() {
        return mapParam;
    }

    public void setMapParam(Map<String, Object> mapParam) {
        this.mapParam = mapParam;
    }

    Map<String,Object> mapParam;

    public String getName() {
        return name;
    }

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

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
action接收map參數

    /**
     * map參數綁定
     * @return ModelAndView
     */
    @RequestMapping(value="/testParam05")
    public ModelAndView testParam05(ParamVo paramVo){
        for(String str : paramVo.getMapParam().keySet()){
            System.out.println(paramVo.getMapParam().get(str));
        }
        ModelAndView model = new ModelAndView();
        // 將傳入綁定成功的參數在頁面顯示。
        model.addObject("mapParam",paramVo.getMapParam());
        model.setViewName("test/testParam");
        return model;
    }
頁面顯示map代碼:

<%-- 顯示map數據 --%>
<c:forEach items="${mapParam}" var="mapPar">
    ${mapPar.key}:${mapPar.value}<br/>
</c:forEach>
運行:

點擊提交進入後臺。

運行完後頁面展示:



好了map參數綁定完畢。主要注意寫法問題。

6 list參數綁定。

 jsp   list參數綁定寫法,因爲list本身也是個數組,所以寫法跟數組顯示。

<form action="${pageContext.request.contextPath }/testParam06" method="post">
    <c:forEach items="${students}" var="student" varStatus="sta">
        姓名:<input type="text" name="students[${sta.index}].name"><br/>
    </c:forEach>
    <input type="submit" value="提交">
</form>
需要注意的是name屬性的寫法。

students對應vo屬性[${sta.index}]對應list的下標,.name對應屬性。

vo定義

package com.soft.po;

import java.util.List;
import java.util.Map;

/**
 * Created by xuweiwei on 2017/8/19.
 */
public class ParamVo {

    private String name;
    private String password;

    List<Student> students;

    public List<Student> getStudents() {
        return students;
    }

    public void setStudents(List<Student> students) {
        this.students = students;
    }

    public Map<String, Object> getMapParam() {
        return mapParam;
    }

    public void setMapParam(Map<String, Object> mapParam) {
        this.mapParam = mapParam;
    }

    Map<String,Object> mapParam;

    public String getName() {
        return name;
    }

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

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
Student  vo

package com.soft.po;

/**
 * Created by xuweiwei on 2017/8/19.
 */
public class Student {

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
跳轉到list參數綁定頁面 action

    /**
     *
     * @return ModelAndView
     */
    @RequestMapping(value="/toListJsp")
    public ModelAndView toListJsp(){
        List<Student> students = new ArrayList<Student>();
        Student student = new Student();
        student.setName("xiaoming");
        Student student1 = new Student();
        student1.setName("xiaohong");
        Student student3 = new Student();
        student3.setName("xiaolan");
        students.add(student);
        students.add(student1);
        students.add(student3);
        ModelAndView model = new ModelAndView();
        model.addObject("students",students);
        model.setViewName("test/testListParam");
        return model;
    }
list參數綁定定義頁面代碼:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ page isELIgnored="false"%>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="${pageContext.request.contextPath }/testParam06" method="post">
    <c:forEach items="${students}" var="student" varStatus="sta">
        姓名:<input type="text" name="students[${sta.index}].name"><br/>
    </c:forEach>
    <input type="submit" value="提交">
</form>
</body>
</html>
獲取參數綁定action

    /**
     * map參數綁定
     * @return ModelAndView
     */
    @RequestMapping(value="/testParam06")
    public ModelAndView testParam06(ParamVo paramVo){
        ModelAndView model = new ModelAndView();
        // 將傳入綁定成功的參數在頁面顯示。
        model.addObject("listParam",paramVo.getStudents());
        model.setViewName("test/testParam");
        return model;
    }
顯示list數據jsp代碼

<%-- 顯示list數據 --%>
<c:forEach items="${listParam}" var="mapPar">
${mapPar.name}<br/>
</c:forEach>
頁面操作流程及結果:

提交到後臺後:

後臺執行完畢,前臺顯示:

到此list參數綁定完畢。主要就是name屬性的寫法以及跟vo參數的屬性名對應。

參數綁定到此告一段落。

弄這些也挺不容易。慢慢提高,慢慢進步。

下一步,傳遞json數據,以及源碼分析。



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章