SpringMVC(2): 매개변수 바인딩

49103 단어 SSM

SpringMVC(2): 매개변수 바인딩


문서 목록

  • SpringMVC(二): 매개 변수 귀속
  • 1. 매개 변수 귀속 메커니즘
  • 2. @RequestParam 메모
  • 2.5 구축 환경
  • 3. 기본 데이터 유형 바인딩
  • 4. PoJo 유형 매개 변수 바인딩
  • 4.1 User 클래스
  • 4.2 프론트 데스크 페이지
  • 4.3 백그라운드 코드
  • 5. 그룹과 집합 형식
  • 5.1 솔리드 클래스
  • 5.2 index.jsp 페이지 부분 코드
  • 5.3 컨트롤러 코드
  • 6.servletApi
  • 7. 기타 유형
  • 7.1 index.jsp 페이지 부분 코드
  • 7.3 사용자 정의 유형 변환
  • 1. 매개 변수 귀속 메커니즘


    SpringMVC에서 요청을 제출한 데이터는 메소드 참조를 통해 수신됩니다.클라이언트가 요청한 키/value 데이터에서 매개 변수를 연결하여 키/value 데이터를 Controller의 인삼에 연결한 다음 Controller에서 이 인삼을 직접 사용할 수 있습니다.

    2. @RequestParam 메모

  • 작용: 일반적으로 전단 요청 함수 이름과 백엔드 파라미터 이름은 일치하지만 일치하지 않으면 요청에서 지정한 이름의 파라미터를 컨트롤러의 형참값에 부여해야 한다.
  • 속성:value: 요청 매개 변수의 이름입니다.required: 요청 매개 변수에 이 매개 변수를 제공해야 하는지 여부입니다.기본값: true제공하지 않으면 오류를 보고해야 한다는 뜻이다.
  • 프런트엔드 코드를 보여주고 요청 파라미터는accountId=10
  • <a href="account/findAccount?accountId=10">    </a>
    

    백엔드 코드 (인삼 이름은 id, 요청 파라미터 이름 accountId와 일치하지 않음)
    //    ,      
    @Controller
    @RequestMapping("/account")
    public class UserController {
        
        @RequestMapping("/findAccount")
        public String findAccount(\@RequestParam("accountId",required="true") Integer id){
            System.out.println("     。。"+id)
                return "success";
        }
    }
    

    2.5 구축 환경


    springmvc 환경을 구축하고pom을 설정합니다.xml,web.xml과spring 프로필, 다음 매개 변수 귀속 테스트는 기본적으로 이 몇 개의 파일이 있습니다.
  • pom.xml
  • 
    
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0modelVersion>
        <groupId>com.zmysnagroupId>
        <artifactId>springmvc01artifactId>
        <version>1.0-SNAPSHOTversion>
        <packaging>warpackaging>
    
        <properties>
            <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
            <maven.compiler.source>1.8maven.compiler.source>
            <maven.compiler.target>1.8maven.compiler.target>
        properties>
    
        <dependencies>
            <dependency>
                <groupId>org.springframeworkgroupId>
                <artifactId>spring-contextartifactId>
                <version>5.0.2.RELEASEversion>
            dependency>
            <dependency>
                <groupId>org.springframeworkgroupId>
                <artifactId>spring-webmvcartifactId>
                <version>5.0.2.RELEASEversion>
            dependency>
            <dependency>
                <groupId>javax.servletgroupId>
                <artifactId>servlet-apiartifactId>
                <version>2.5version>
            dependency>
            <dependency>
                <groupId>javax.servletgroupId>
                <artifactId>jsp-apiartifactId>
                <version>2.0version>
            dependency>
        dependencies>
    project>
    
  • web.xml
  • 
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns="http://java.sun.com/xml/ns/javaee"
       xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
       version="2.5">
    	
       <servlet>
          <servlet-name>DispatcherServletservlet-name>
          <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
          <init-param>
             <param-name>contextConfigLocationparam-name>
             <param-value>classpath:springmvc.xmlparam-value>
          init-param>
          <load-on-startup>1load-on-startup>
       servlet>
    
       <servlet-mapping>
            <servlet-name>DispatcherServletservlet-name>
          <url-pattern>*.dourl-pattern>
       servlet-mapping>
        
        
        <filter>
            <filter-name>characterEncodingFilterfilter-name>
            <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
            <init-param>
                <param-name>encodingparam-name>
                <param-value>UTF-8param-value>
            init-param>
            <init-param>
                <param-name>forceEncodingparam-name>
                <param-value>trueparam-value>
            init-param>
        filter>
        <filter-mapping>
            <filter-name>characterEncodingFilterfilter-name>
            <url-pattern>/*url-pattern>
        filter-mapping>
    web-app>
    
  • springmvc.xml
  • 
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:mvc="http://www.springframework.org/schema/mvc"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tool http://www.springframework.org/schema/tool/spring-tool.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
        
    	
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/pages/">property>
            <property name="suffix" value=".jsp">property>
        bean>
    
        
        <context:component-scan base-package="com.zmysna.controller">context:component-scan>
        
    	
        <mvc:annotation-driven>mvc:annotation-driven>
    
    beans>
    
  • hello.jsp 실행 처리 방법이 완성된 후 이동하는 페이지는 페이지 디렉터리에 있습니다.
  • 
    
    
        hello
    
    
        hello world!!!!!
    
    
    

    3. 기본 데이터 유형 바인딩


    참고:
  • 백엔드 파라미터가 기본 데이터 형식이고 백엔드 페이지에서 전달된 값이null 또는''이면 데이터 변환에 이상이 생길 수 있으므로 포장 유형을 최대한 사용한다.
  • 요청 매개 변수의 이름과 백엔드 매개 변수의 이름이 일치해야 합니다. @RequestParam으로 요청 매개 변수의 값을 컨트롤러에 지정해야 합니다.
  • //    ,      
    @Controller
    //           。             +        
    @RequestMapping("user")
    public class UserController {
        //     : http://localhost:8080/user/save?id=100&name=Jack
        @RequestMapping("save.do")
        public String save(Integer id, String name) {
            System.out.println(id); //100
            System.out.println(name);//jack
            return "success";
        }
    
        //     : http://localhost:8080/user/update?id=&name=Jack
        @RequestMapping("update.do")
        public String update(int id, String name) {
            System.out.println(id); //    
            System.out.println(username);
            return "success";
        }
    }
    

    4. PoJo 유형 매개 변수 바인딩


    참고: 요청 매개변수 이름은 객체의 속성과 일치해야 합니다. @RequestParam을 사용할 수 없으므로 일치해야 합니다.
    예: 페이지 매개 변수 바인딩 User 솔리드 클래스
    id는 user 대상의 속성입니다. name도 user 대상의 속성입니다.

    4.1 User 클래스

    public class User {
        private Integer id;
        private String usernamename;
        //....get/set    
    }
    

    4.2 프론트 데스크 페이지


    부분 코드, 매개 변수 id와username 제출

    4.3 백그라운드 코드

    @Controller
    @RequestMapping("/user")
    public class UserController {
     
        //       : http://localhost:8080/user/userMapping?id=100&username=Jack
        @RequestMapping(value = "/userMapping")
        private String userMapping(User user) {
            System.out.println(user);
            return "hello";
        }
    }
    

    결실
    user[id=100,username=Jack]
    

    5. 배열과 집합 유형


    참고:
    집합 유형의 요청 매개 변수는 POJO 실체 클래스에 POJO 속성으로 존재하고 요청 매개 변수의 이름은 실체 클래스의 집합 속성 이름과 같아야 한다.
    List 컬렉션의 요소에 값을 지정하고 아래 첨자를 사용합니다.
    키 값 쌍을 지정하려면 Map 컬렉션의 요소에 값을 지정합니다.
    수요: 프로세서 방법에 값을 부여하고 방법 매개 변수는 집합 속성이 있는 실체 클래스입니다.

    5.1 실체류

  • Address 클래스
  • public class Address{
      	private String province;
        private String city;
        //...get/set    
    }
    
  • User 클래스
  • package com.zmysna.entity;
    
    import java.util.List;
    import java.util.Map;
    
    public class User {
        private Integer id;
        private String name;
    
        
        private List<Addresss> Int;
        private Map<String,String> map;
    
    
       //...get/set    
    }
    

    5.2 index.jsp 페이지 부분 코드

    요청 매개 변수 가져오기: 3.요청 매개 변수를 대상의 집합에 봉인하다

    id:
    :
    :
    :
    list:
    list:
    list:
    list:
    map:
    map:
    map:
    map:

    5.3 컨트롤러 코드

    //         。
    @RequestMapping("/multiUser")
    private String multiUser(User user) {
        System.out.println(user);
        return "hello";
    }
    

    6.servletApi


    SpringMVC는 또한 원본 서브렛API 객체를 컨트롤러 메소드 매개변수로 사용할 수도 있습니다.지원되는 원래 서브렛API 객체는 다음과 같습니다.
    ​ HttpServletRequest ​ HttpServletResponse ​ HttpSession ​ java.security.Principal ​ Locale ​ InputStream ​ OutputStream ​ Reader ​ Writer
    우리는 상술한 대상을 제어의 방법 매개 변수에 직접 써서 사용할 수 있다
    servletapi 사용
    @RequestMapping(value = "/servletApi")
    private void servletApi(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws ServletException, IOException {
         //  
    //     request.getRequestDispatcher("/pages/hello.jsp").forward(request,response);
         //   
         `response.sendRedirect("/pages/hello.jsp");
    }
    

    7. 기타 유형


    매개 변수의 연결을 실현하기 위해spring은 기본적으로 일부 데이터 형식의 자동 변환을 실현합니다.사용자 정의 유형 변환을 실현하려면 클래스 구현 Converter 인터페이스를 정의하고 유형 변환기 공장(Conversion Service Factory Bean)을 설정할 수 있습니다.
    요구: 페이지의date 매개 변수 값 (문자열) 을 백엔드 참조에 봉합니다

    7.1 index.jsp 페이지 부분 코드

    날짜 2
    

    ###7.2 백그라운드 부분 코드
    @RequestMapping("/searchByDate2.do")
    private String searchByDate2(Date date) {
        System.out.println(date);
        return "hello";
    }
    

    7.3 사용자 정의 유형 변환

  • 변환 클래스 구현 Converter 커넥터
  • package com.zmysna.utils;
    
    
    import org.springframework.core.convert.converter.Converter;
    import org.springframework.util.StringUtils;
    
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    public class StringToDateConvert implements Converter<String, Date> {
        @Override
        public Date convert(String s) {
    
            try {
                if (StringUtils.isEmpty(s)) {
                    throw new RuntimeException("     ");
                }
                return new SimpleDateFormat("yyyy-MM-dd").parse(s);
            } catch (ParseException e) {
                throw new RuntimeException("         yyyy-MM-dd    !");
            }
        }
    }
    
  • springmvc.xml에서 설정
  •     <bean id="serviceFactoryBean"          class="org.springframework.context.support.ConversionServiceFactoryBean">
            <property name="converters">
                <set>
                    
                    <bean class="com.zmysna.utils.StringToDateConvert">bean>
                set>
            property>
        bean>
    	
        <mvc:annotation-driven conversion-service="serviceFactoryBean">mvc:annotation-driven>
    
    beans>
    

    좋은 웹페이지 즐겨찾기