Home Java javaTutorial SpringMVC Learning Series (4) Data Binding-1

SpringMVC Learning Series (4) Data Binding-1

Mar 03, 2017 am 10:52 AM
springmvc data binding

In series (SpringMVC Learning Series (SpringMVC Learning Series (4) Data Binding-1) Data Binding-1) we introduced how a request is mapped to an action. The next step is of course how to obtain the data in the request, which leads to the content of this article - data binding.

First take a look at the annotations for binding data:

SpringMVC Learning Series (SpringMVC Learning Series (4) Data Binding-1) Data Binding-1.@RequestParam, binds a single request data, which can be the data in the URL, the data submitted by the form or the uploaded file ;
SpringMVC Learning Series (SpringMVC Learning Series (4) Data Binding-1) Data Binding-1.@PathVariable, bind URL template variable value;
SpringMVC Learning Series (SpringMVC Learning Series (4) Data Binding-1) Data Binding-1.@CookieValue, bind cookie data;
SpringMVC Learning Series (4) Data Binding-1.@RequestHeader, bind request header data;
5.@ModelAttribute , bind data to Model;
6.@SessionAttributes, bind data to Session;
7.@RequestBody, used to process content whose Content-Type is not application/x-www-form-urlencoded, for example application/json, application/xml, etc.;
8.@RequestPart, binds "multipart/data" data, and can enter object conversion according to the data type;

Let's see how to use it:

SpringMVC Learning Series (SpringMVC Learning Series (4) Data Binding-1) Data Binding-1.@RequestParam:

In order to verify file binding we need to do the following first:

a. Put commons-fileupload-SpringMVC Learning Series (SpringMVC Learning Series (4) Data Binding-1) Data Binding-1.SpringMVC Learning Series (SpringMVC Learning Series (4) Data Binding-1) Data Binding-1.SpringMVC Learning Series (SpringMVC Learning Series (4) Data Binding-1) Data Binding-1.jar and commons-io- SpringMVC Learning Series (SpringMVC Learning Series (4) Data Binding-1) Data Binding-1.SpringMVC Learning Series (4) Data Binding-1.jar Two jar packages were added to our project.

b. Configure the springservlet-config.xml file in our project to support file upload. The content is as follows:


<!-- 支持上传文件 -->  <bean>  
    <!-- 设置上传文件的最大尺寸为SpringMVC Learning Series (SpringMVC Learning Series (4) Data Binding-1) Data Binding-1MB -->  
    <property>  
        <value>SpringMVC Learning Series (SpringMVC Learning Series (4) Data Binding-1) Data Binding-10SpringMVC Learning Series (4) Data Binding-18576</value>  
    </property>
    <property> 
        <value>UTF-8</value> 
    </property></bean>
Copy after login


maxUploadSize is used to limit the maximum size of uploaded files, or it can be left unset, which means there is no limit to the size of uploaded files. defaultEncoding is used to set the encoding format of uploaded files and is used to solve the problem of garbled Chinese names of uploaded files.

Let’s see how to use it:

Add a DataBindController, which has two paramBind actions corresponding to get and post requests respectively:

package com.demo.web.controllers;import javax.servlet.http.HttpServletRequest;import org.springframework.stereotype.Controller;import org.springframework.web.bind.ServletRequestUtils;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.multipart.MultipartFile;import org.springframework.web.multipart.MultipartHttpServletRequest;import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping(value = "/databind")public class DataBindController {

    @RequestMapping(value="/parambind", method = {RequestMethod.GET})    public ModelAndView paramBind(){
        
        ModelAndView modelAndView = new ModelAndView();  
        modelAndView.setViewName("parambind");  
        return modelAndView;
    }
    
    @RequestMapping(value="/parambind", method = {RequestMethod.POST})    public ModelAndView paramBind(HttpServletRequest request, @RequestParam("urlParam") String urlParam, @RequestParam("formParam") String formParam, @RequestParam("formFile") MultipartFile formFile){        
        //如果不用注解自动绑定,我们还可以像下面一样手动获取数据
         String urlParamSpringMVC Learning Series (SpringMVC Learning Series (4) Data Binding-1) Data Binding-1 = ServletRequestUtils.getStringParameter(request, "urlParam", null);
        String formParamSpringMVC Learning Series (SpringMVC Learning Series (4) Data Binding-1) Data Binding-1 = ServletRequestUtils.getStringParameter(request, "formParam", null);
        MultipartFile formFileSpringMVC Learning Series (SpringMVC Learning Series (4) Data Binding-1) Data Binding-1 = ((MultipartHttpServletRequest) request).getFile("formFile"); 
        
        ModelAndView modelAndView = new ModelAndView();  
        modelAndView.addObject("urlParam", urlParam);  
        modelAndView.addObject("formParam", formParam);  
        modelAndView.addObject("formFileName", formFile.getOriginalFilename());  
        
        modelAndView.addObject("urlParamSpringMVC Learning Series (SpringMVC Learning Series (4) Data Binding-1) Data Binding-1", urlParamSpringMVC Learning Series (SpringMVC Learning Series (4) Data Binding-1) Data Binding-1);  
        modelAndView.addObject("formParamSpringMVC Learning Series (SpringMVC Learning Series (4) Data Binding-1) Data Binding-1", formParamSpringMVC Learning Series (SpringMVC Learning Series (4) Data Binding-1) Data Binding-1);  
        modelAndView.addObject("formFileNameSpringMVC Learning Series (SpringMVC Learning Series (4) Data Binding-1) Data Binding-1", formFileSpringMVC Learning Series (SpringMVC Learning Series (4) Data Binding-1) Data Binding-1.getOriginalFilename());  
        modelAndView.setViewName("parambindresult");  
        return modelAndView;
    }
        
}
Copy after login


Add two views, parabind.jsp and parabindresult.jsp, in the views folder. The contents are as follows:


##

nbsp;html PUBLIC "-//WSpringMVC Learning Series (SpringMVC Learning Series (4) Data Binding-1) Data Binding-1C//DTD HTML SpringMVC Learning Series (4) Data Binding-1.0SpringMVC Learning Series (SpringMVC Learning Series (4) Data Binding-1) Data Binding-1 Transitional//EN" "http://www.wSpringMVC Learning Series (SpringMVC Learning Series (4) Data Binding-1) Data Binding-1.org/TR/htmlSpringMVC Learning Series (4) Data Binding-1/loose.dtd"><meta><title>Insert title here</title>
    
Copy after login
          
          
             
  


nbsp;html PUBLIC "-//WSpringMVC Learning Series (SpringMVC Learning Series (4) Data Binding-1) Data Binding-1C//DTD HTML SpringMVC Learning Series (4) Data Binding-1.0SpringMVC Learning Series (SpringMVC Learning Series (4) Data Binding-1) Data Binding-1 Transitional//EN" "http://www.wSpringMVC Learning Series (SpringMVC Learning Series (4) Data Binding-1) Data Binding-1.org/TR/htmlSpringMVC Learning Series (4) Data Binding-1/loose.dtd"><meta><title>Insert title here</title>
    自动绑定数据:

    ${urlParam}
    ${formParam}
    ${formFileName}



    手动获取数据:

    ${urlParamSpringMVC Learning Series (SpringMVC Learning Series (4) Data Binding-1) Data Binding-1}
    ${formParamSpringMVC Learning Series (SpringMVC Learning Series (4) Data Binding-1) Data Binding-1}
    ${formFileNameSpringMVC Learning Series (SpringMVC Learning Series (4) Data Binding-1) Data Binding-1}
Copy after login


Run the project, enter the content, and select the upload file:

SpringMVC Learning Series (SpringMVC Learning Series (4) Data Binding-1) Data Binding-1

Submit to view the results:

SpringMVC Learning Series (SpringMVC Learning Series (4) Data Binding-1) Data Binding-1

You can see that the bound data has been obtained.

Above we demonstrated how to bind data to a single variable, but in actual applications we usually need to obtain the model object. Don’t worry, we don’t need to bind data to individual variables and then compare them. When assigning a value to a model, you only need to add the model to the corresponding action parameters (there is no need to specify annotations for binding data here). Spring MVC will automatically convert the data and bind it to the model object. Everything is as simple as that. The test is as follows:

添加一个AccountModel类作为测试的model:


package com.demo.web.models;public class AccountModel {    
    private String username;    private String password;    
    public void setUsername(String username){        this.username=username;
    }    public void setPassword(String password){        this.password=password;
    }    
    public String getUsername(){        return this.username;
    }    public String getPassword(){        return this.password;
    }
}
Copy after login

在DataBindController里面添加SpringMVC Learning Series (SpringMVC Learning Series (4) Data Binding-1) Data Binding-1个modelAutoBind的action分别对应get和post请求:


@RequestMapping(value="/modelautobind", method = {RequestMethod.GET})public String modelAutoBind(HttpServletRequest request, Model model){
    
    model.addAttribute("accountmodel", new AccountModel());    return "modelautobind";
}

@RequestMapping(value="/modelautobind", method = {RequestMethod.POST})public String modelAutoBind(HttpServletRequest request, Model model, AccountModel accountModel){
    
    model.addAttribute("accountmodel", accountModel);    return "modelautobindresult";
}
Copy after login


在views文件夹中添加modelautobind.jsp和modelautobindresult.jsp SpringMVC Learning Series (SpringMVC Learning Series (4) Data Binding-1) Data Binding-1个视图用于提交数据和展示提交的数据:

modelautobind.jsp:

nbsp;html PUBLIC "-//WSpringMVC Learning Series (SpringMVC Learning Series (4) Data Binding-1) Data Binding-1C//DTD HTML SpringMVC Learning Series (4) Data Binding-1.0SpringMVC Learning Series (SpringMVC Learning Series (4) Data Binding-1) Data Binding-1 Transitional//EN" "http://www.wSpringMVC Learning Series (SpringMVC Learning Series (4) Data Binding-1) Data Binding-1.org/TR/htmlSpringMVC Learning Series (4) Data Binding-1/loose.dtd"><meta><title>Insert title here</title>
    
              用户名:
        密 码:
             
  
Copy after login

modelautobindresult.jsp :

nbsp;html PUBLIC "-//WSpringMVC Learning Series (SpringMVC Learning Series (4) Data Binding-1) Data Binding-1C//DTD HTML SpringMVC Learning Series (4) Data Binding-1.0SpringMVC Learning Series (SpringMVC Learning Series (4) Data Binding-1) Data Binding-1 Transitional//EN" "http://www.wSpringMVC Learning Series (SpringMVC Learning Series (4) Data Binding-1) Data Binding-1.org/TR/htmlSpringMVC Learning Series (4) Data Binding-1/loose.dtd"><meta><title>Insert title here</title>
    用户名:${accountmodel.username}
    密 码:${accountmodel.password}
Copy after login


运行测试:

SpringMVC Learning Series (SpringMVC Learning Series (4) Data Binding-1) Data Binding-1

用户名 输入AAA 密码 输入BBB,提交:

SpringMVC Learning Series (4) Data Binding-1

可以看到结果显示正确,说明自动绑定成功。

注:

SpringMVC Learning Series (SpringMVC Learning Series (4) Data Binding-1) Data Binding-1.关于@RequestParam的参数,这是一个@RequestParam的完整写法@RequestParam(value="username", required=true, defaultValue="AAA")。

value表示要绑定请求中参数的名字;

required表示请求中是否必须有这个参数,默认为true这是如果请求中没有要绑定的参数则返回SpringMVC Learning Series (4) Data Binding-10SpringMVC Learning Series (4) Data Binding-1;

defaultValue表示如果请求中指定的参数值为空时的默认值;

要绑定的参数如果是值类型必须要有值否则抛异常,如果是引用类型则默认为null(Boolean除外,默认为false);

 

SpringMVC Learning Series (SpringMVC Learning Series (4) Data Binding-1) Data Binding-1.在刚才添加的SpringMVC Learning Series (SpringMVC Learning Series (4) Data Binding-1) Data Binding-1个action中可以看到返回类型和以前的不一样了由ModelAndView变成了String,这是由于Spring MVC 提供Model、ModelMap、Map让我们可以直接添加渲染视图需要的模型数据,在返回时直接指定对应视图名称就可以了。同时Map是继承于ModelMap的,而Model和ModelMap是继承于ExtendedModelMap的。

 

SpringMVC Learning Series (SpringMVC Learning Series (4) Data Binding-1) Data Binding-1. In the view modelautobind.jsp you just added, you can see form:formform:input and other tags, these are the form tags provided by Spring MVC. With the help of these tags, we can easily bind the model data to the form (of course you can also choose to continue to use the native HTML form tags). To use Spring MVC just needs to add a reference to the view @ taglib prefix="form" uri="http://www.php.cn/" %>That’s it, about Spring The specific content of MVC form tags will be introduced in future articles.

The above is the content of Data Binding-SpringMVC Learning Series (SpringMVC Learning Series (4) Data Binding-1) Data Binding-1 of SpringMVC Learning Series (SpringMVC Learning Series (4) Data Binding-1). For more related content, please pay attention to the PHP Chinese website (www. php.cn)!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement data binding function in SwiftUI using MySQL How to implement data binding function in SwiftUI using MySQL Jul 30, 2023 pm 12:13 PM

How to use MySQL to implement data binding function in SwiftUI. In SwiftUI development, data binding can realize automatic updating of interface and data, improving user experience. As a popular relational database management system, MySQL can store and manage large amounts of data. This article will introduce how to use MySQL to implement data binding function in SwiftUI. We will make use of Swift's third-party library MySQLConnector, which provides connections and queries to MySQL data.

Comparison and difference analysis between SpringBoot and SpringMVC Comparison and difference analysis between SpringBoot and SpringMVC Dec 29, 2023 am 11:02 AM

SpringBoot and SpringMVC are both commonly used frameworks in Java development, but there are some obvious differences between them. This article will explore the features and uses of these two frameworks and compare their differences. First, let's learn about SpringBoot. SpringBoot was developed by the Pivotal team to simplify the creation and deployment of applications based on the Spring framework. It provides a fast, lightweight way to build stand-alone, executable

Detailed explanation of data binding functions in Vue documentation Detailed explanation of data binding functions in Vue documentation Jun 20, 2023 pm 10:15 PM

Vue is an open source JavaScript framework mainly used for building user interfaces. The core of Vue is data binding, which provides a convenient and efficient way to achieve two-way binding between data and views. Vue's data binding mechanism is handled through some special functions. These functions can help us automatically bind the data in the template to the corresponding properties in the JavaScript object, so that when the properties in the JavaScript object are modified, the data in the template will also automatically

How to use the v-once directive to implement one-time rendering of data binding in Vue How to use the v-once directive to implement one-time rendering of data binding in Vue Jun 11, 2023 pm 01:56 PM

Vue is a popular front-end JavaScript framework that provides many instructions to simplify the data binding process. One of the very useful instructions is v-once. In this article, we will delve into the use of the v-once directive and how to implement data-bound one-time rendering in Vue. What is the v-once instruction? v-once is a directive in Vue. Its function is to cache the rendering results of elements or components so that their rendering process can be skipped in subsequent updates.

Vue error: v-model cannot be used correctly for two-way data binding. How to solve it? Vue error: v-model cannot be used correctly for two-way data binding. How to solve it? Aug 19, 2023 pm 08:46 PM

Vue error: v-model cannot be used correctly for two-way data binding. How to solve it? Introduction: Two-way data binding is a very common and powerful feature when developing with Vue. However, sometimes we may encounter a problem, that is, when we try to use v-model for two-way data binding, we encounter an error. This article describes the cause and solution of this problem, and provides a code example to demonstrate how to solve the problem. Problem Description: When we try to use v-model in Vue

What are the differences between SpringBoot and SpringMVC? What are the differences between SpringBoot and SpringMVC? Dec 29, 2023 am 10:46 AM

What is the difference between SpringBoot and SpringMVC? SpringBoot and SpringMVC are two very popular Java development frameworks for building web applications. Although they are often used separately, the differences between them are obvious. First of all, SpringBoot can be regarded as an extension or enhanced version of the Spring framework. It is designed to simplify the initialization and configuration process of Spring applications to help developers

Detailed explanation of v-model function in Vue3: application of two-way data binding Detailed explanation of v-model function in Vue3: application of two-way data binding Jun 18, 2023 am 10:25 AM

With the continuous development of front-end technology, Vue, as a popular front-end framework, is also constantly updated and iterated. The latest version, Vue3, introduces many new features, making it more convenient and flexible to use. Among them, the v-model function is one of the new features worth mentioning in Vue3. It can achieve two-way data binding, that is to say, when using the v-model function, it can not only easily realize communication between parent and child components, but also automatically bind the data input by the user to the data in the component.

Vue Development Notes: Avoid Common Mistakes and Pitfalls Vue Development Notes: Avoid Common Mistakes and Pitfalls Nov 23, 2023 am 10:37 AM

Vue Development Notes: Avoid Common Mistakes and Pitfalls Introduction: Vue.js is a popular JavaScript framework that is widely used to build modern interactive front-end applications. Although Vue.js provides a simple, flexible and efficient development method, you may still encounter some common errors and pitfalls during the development process. This article will introduce some common Vue development considerations to help developers avoid these mistakes and traps and improve development efficiency and code quality. Note 1: Reasonable use of v-if and

See all articles