springMVC(五)參數(shù)綁定

參數(shù)綁定

默認支持的參數(shù)

SpringMVC 有支持的默認參數(shù)類型,我們直接在形參上給出這些默認類型的聲明,就能直接使用了。如下:
  1 HttpServletRequest 對象
  2 HttpServletResponse 對象
  3 HttpSession 對象
  4 Model/ModelMap 對象

pojo類型綁定

需求:
根據(jù)學院編號查詢學院。

mybatis持久層

<resultMap id="facultyCustomMap" type="com.pesystem.vo.FacultyCustom" extends="com.pesystem.mapper.FacultyMapper.BaseResultMap"/>


<select id="selectFacultyByFacultyId" resultMap="facultyCustomMap">
        SELECT
          <include refid="com.pesystem.mapper.FacultyMapper.Base_Column_List" />
        from faculty where
          faculty_id = #{facultyCustom.facultyId}
    </select>

測試mapper層代碼

package com.pesystem.mapper;

import com.pesystem.vo.FacultyCustom;
import com.pesystem.vo.FacultyQueryVo;
import org.apache.log4j.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:springConfig/spring-dao.xml"})
public class FacultyCustomMapperTest {
    //獲取日志記錄器Logger,名字為本類類名
    private static Logger log = Logger.getLogger(String.valueOf(FacultyMapperTest.class));

    @Autowired
    private FacultyCustomMapper facultyCustomMapper;

    @Test
    public void testInsert(){
        FacultyQueryVo facultyQueryVo = new FacultyQueryVo();
        FacultyCustom facultyCustom = new FacultyCustom();
        facultyCustom.setFacultyId(3);
        facultyQueryVo.setFacultyCustom(facultyCustom);
        FacultyCustom facultyCustom1 = facultyCustomMapper.selectFacultyByFacultyId(facultyQueryVo);
        log.info(facultyCustom1);
    }
}

測試結果:

 INFO [main] - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
 INFO [main] - Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@7c16905e, org.springframework.test.context.support.DependencyInjectionTestExecutionListener@2a2d45ba, org.springframework.test.context.support.DirtiesContextTestExecutionListener@2a5ca609, org.springframework.test.context.transaction.TransactionalTestExecutionListener@20e2cbe0, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener@68be2bc2] INFO [main] - Loading XML bean definitions from class path resource [springConfig/spring-dao.xml]
 INFO [main] - Refreshing org.springframework.context.support.GenericApplicationContext@e45f292: startup date [Tue Aug 21 09:43:48 CST 2018]; root of context hierarchy
 INFO [main] - Loading properties file from class path resource [db.properties]
 INFO [main] - 3默認院系
 INFO [Thread-1] - Closing org.springframework.context.support.GenericApplicationContext@e45f292: startup date [Tue Aug 21 09:43:48 CST 2018]; root of context hierarchy

service層
接口和實現(xiàn)

public interface FacultyCustomService {
  
    public FacultyCustom selectFacultyByFacultyId(FacultyQueryVo facultyQueryVo);
}
    @Override
    public FacultyCustom selectFacultyByFacultyId(FacultyQueryVo facultyQueryVo){
        return facultyCustomMapper.selectFacultyByFacultyId(facultyQueryVo);
    }

這一層沒有什么處理所以就忽略測試

handler

    @RequestMapping("/selectFacultyById.action")
    public ModelAndView selectFacultyById(FacultyQueryVo facultyQueryVo){
        ModelAndView modelAndView = new ModelAndView();
        FacultyCustom facultyCustom = facultyCustomService.selectFacultyByFacultyId(facultyQueryVo);
        modelAndView.setViewName("selectFaculty");
        modelAndView.addObject("facultyCustom",facultyCustom);
        return modelAndView;
    }

前端jsp

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2018/8/20
  Time: 20:36
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<html>
<head>
    <title>綜合學院條件</title>
</head>
<script src="js/jquery-3.2.1.min.js"></script>
<script>
    $(document).ready(function(){
        $("#selectFacultiesByName").click(function(){
            path="${pageContext.request.contextPath}/faculty/selectFacultiesByName.action";
            $('#facultyForm').attr("action", path).submit();
        });
        $("#selectFacultyById").click(function(){
            path="${pageContext.request.contextPath}/faculty/selectFacultyById.action";
            $('#facultyForm').attr("action", path).submit();

        });
    });
</script>
<body>
<form id="facultyForm" action="${pageContext.request.contextPath}/faculty/selectFacultiesByName.action" method="get">
    <label>查詢條件</label><br/>
    <label>模糊查詢名字:</label><input type="text" name="facultyCustom.facultyName"><br>
    <input type="button" value="模糊查詢" name="selectFacultiesByName" id="selectFacultiesByName"><br>

    <label>精準id:</label><input type="text" name="facultyCustom.facultyId"><br>
    <input type="button" value="精準查詢" name="selectFacultyById" id="selectFacultyById">
</form>

</body>
</html>

結果頁面

<%@ page language="java" contentType="text/html;charset=UTF-8"
         pageEncoding="UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page isELIgnored="false" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <c:if test="${facultyCustom!=null}  ">
        <c:out value="${facultyCustom}"></c:out>
    </c:if>

</body>
</html>

測試結果
怎么都不能顯示結果,但是去掉判斷c:if之后,就能輸出??赏瞥鰲l件錯誤,發(fā)現(xiàn)原來是多了兩個空格,導致異常。

整理之后結果:


image.png

簡單類型綁定

需求:
根據(jù)學院編號查詢學院。(只需要傳入facultyId過來)

mapper只是controller輸入?yún)?shù)區(qū)別比較大,這里只用mapper的單表實現(xiàn)。就沒有測試,主要展示controller

controller

   @RequestMapping("/selectFacultyById2.action")
    public String selectFacultyById2(Model model, @RequestParam("facultyCustom.facultyId") Integer facultyId){
        Faculty faculty = facultyService.selectFacultyByFacultyId(facultyId);
        model.addAttribute("facultyCustom",faculty);
        return "selectFaculty";
    }

測試結果:


image.png

這里還發(fā)生了一個小插曲,傳入?yún)?shù)我用成了ModelAndView導致數(shù)據(jù)一直存入不進去,還是沒認真啊

這里最好使用@RequestParam因為一張form表單,我們很多時候有多種功能,如果pojo和簡單類型參數(shù)一起用,肯定需要@RequestParam注解,前端設置name最好優(yōu)先滿足pojo~~

自定義參數(shù)綁定

需求添加學生信息:

學生信息里面包括姓名學號生日等等。主要是使用生日完成自定義參數(shù)
表現(xiàn)層實現(xiàn):
普通的表單提交


image.png

controller層:
先不使用自定義的參數(shù)綁定


image.png

參數(shù)沒有綁定成功。
自定義參數(shù)綁定實現(xiàn)日期類型綁定
將String 轉(zhuǎn)為java.util.Date

向處理器適配器中注入自定義參數(shù)綁定組件

在controller包下面創(chuàng)建自定義參數(shù)綁定包,創(chuàng)建類。該類需要實現(xiàn)Converter<E,T>接口。注意導入的包

import org.springframework.core.convert.converter.Converter;

類創(chuàng)建詳細如下:

package com.pesystem.controller.converter;

import org.springframework.core.convert.converter.Converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class CustomDateConverter implements Converter<String,Date> {
    @Override
    public Date convert(String s) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            return simpleDateFormat.parse(s);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }
}

在處理器映射器中,我們需要注入

<mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
    <!--自定義參數(shù)綁定-->
    <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        <property name="converters">
            <list>
                <!--創(chuàng)建自定義綁定-->
                <bean class="com.pesystem.controller.converter.CustomDateConverter"/>
            </list>

        </property>
    </bean>

測試結果:

image.png

參數(shù)綁定--數(shù)組

需求同時查詢多個院系,只實現(xiàn)controller層,完成參數(shù)綁定即可。

數(shù)組和簡單類型參數(shù)綁定沒有太大區(qū)別,主要是controller層的形參用數(shù)組類型,前端用多選框?qū)⒍鄠€id傳過就可以了。

參數(shù)綁定--List

需求批量添加學院

擴展vo類

package com.pesystem.vo;

import com.pesystem.po.Student;

import java.util.List;

public class StudentQueryVo {
    private StudentCustom studentCustom;
    private List<Student> students;

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

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

    public StudentCustom getStudentCustom() {
        return studentCustom;
    }

    public void setStudentCustom(StudentCustom studentCustom) {
        this.studentCustom = studentCustom;
    }
}

controller層

    @RequestMapping("/addFaculties.action")
    public ModelAndView addFaculties(FacultyQueryVo facultyQueryVo){
        System.out.println(facultyQueryVo);
        return null;
    }

jsp
最主要就是設置name的時候一定要設置好下標,當然也可通過c:foreach或者js,jquery設置name的名字。只要數(shù)組名對應,下標不錯,屬性正確那么還是沒什么問題。

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2018/8/21
  Time: 17:33
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/faculty/addFaculties.action">
    <table>
        <tr>
            <td>學院名稱</td>
            <td><input type="text" name="faculties[0].facultyName"></td>
        </tr>
        <tr>
            <td>學院名稱</td>
            <td><input type="text" name="faculties[1].facultyName"></td>
        </tr>
    </table>
    <button type="submit" value="提交"/>
</form>
</body>
</html>

測試結果:


image.png
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,644評論 19 139
  • 1 Mybatis入門 1.1 單獨使用jdbc編程問題總結 1.1.1 jdbc程序 上邊使...
    哇哈哈E閱讀 3,417評論 0 38
  • 背著電腦出門上班好辛苦! 上午主要是對比了一下有無PMML的隨機森林分類性能,結果證明用了PMML后整個過程沒什么...
    真晝之月閱讀 115評論 0 0
  • 人總是在擁有的時候,不懂的珍惜 離開之后,便才意識一些人已不在 無論是親情·愛情·友情 都有一個保質(zhì)期 都有一個保...
    Aunique閱讀 174評論 0 0
  • 翻了許多典籍 找不到任何先例 別人眼里的秦晉 自己心中的秘密 我們有些關系 只是在我心里 該是怎樣的心情 理解你的...
    安靜的復蘇918閱讀 256評論 0 0

友情鏈接更多精彩內(nèi)容