SpringMVC(2): 매개변수 바인딩
49103 단어 SSM
SpringMVC(2): 매개변수 바인딩
문서 목록
1. 매개 변수 귀속 메커니즘
SpringMVC에서 요청을 제출한 데이터는 메소드 참조를 통해 수신됩니다.클라이언트가 요청한 키/value 데이터에서 매개 변수를 연결하여 키/value 데이터를 Controller의 인삼에 연결한 다음 Controller에서 이 인삼을 직접 사용할 수 있습니다.
2. @RequestParam 메모
<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 프로필, 다음 매개 변수 귀속 테스트는 기본적으로 이 몇 개의 파일이 있습니다.
<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-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>
<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
hello world!!!!!
3. 기본 데이터 유형 바인딩
참고:
// ,
@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 실체류
public class Address{
private String province;
private String city;
//...get/set
}
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.요청 매개 변수를 대상의 집합에 봉인하다
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 사용자 정의 유형 변환
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 !");
}
}
}
<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>
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
ssm에서 ansible 해 본 메모 (그냥 메모)SSM EC2에 SSM 에이전트를 넣고 EC2를 SSM의 관리하에 놓습니다. SSM 관리형 인스턴스에서 볼 수 있다면 OK 참고 링크 S3 버킷 생성 Ansible 템플릿을 zip으로 만들어 S3에 배치하기 위해. ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.