SpringMVC data binding principle

What is Data Binding?

The HTTP request parameter is bound to a business method parameter Handler

This parameter is very important. web project is actually interactive, client between the client sends a request with the server, the server responds to the request.
When the client sends a request parameter is the need to carry over. For example details of the query programs, the foreground program will pass the id background, the background in a database to retrieve the id of the course through all the details, and then package the result into a model data set, then the model data back to the front desk to make a response, which is the complete process.
springmvc operation before acquisition parameters: serlvet among doget and dopost method is used to handle such requests.
 These two methods have default parameter list of parameters, is httpservletrequest type of request objects, acquired by the request parameter objects
but by this request objects have a problem, come up with are the string types, such as the front desk pass over a type int id, then we come up from behind the scenes after the request object to, it is a string type, so you need to do a data type conversion, to convert the string to an int. If you want to add a course, you need to enter the relevant properties in the front page, such as its input id, name and price. After the form is submitted form will be passed as parameters to the background. Background business method, followed by the request object out these parameters, or it needs to be encapsulated into a program object.
That requires a series of repeated operations by native manner, cumbersome steps including the data type conversion and packaging.
If you use springmvc framework, springmvc framework will help us achieve these series of steps, you do not need to go write.
springmvc among business layer framework, what needs to be in the parameter list to define what, if that to get an int id, then the parameter list to define a parameter of type, springmvc framework will automatically http request parameters will take int bound to them out of the parameter
If the add operation to do a course, which would in the parameter list, a program type of object definitions, SpringMVC framework will automatically come up, which encapsulates the object from among the parameters of the request. springmvc framework will help us to complete this operation. We directly get ready, the desired results in business methods to complete the follow-up of the business logic operations can be.


So how springmvc framework underlying implementation of such a process it?
By HandlerAdapter HttpMessageConverter to invoke component to complete the binding data, to bind to the data type of a business method which Handler parameter list.
Through the process of: sending a request over the distal end is captured DispatcherServlet, DispatcherServlet Handler will be mapped to the request, and then to call HandlerAdapter, HandlerAdapter before executing business method, calls HttpMessageConverter component, the http request out parameter data type conversion and a package and a series of steps, the results of the final bound directly assigned parameter lists among the business methods Handler
so that we can directly take the packaged business methods, the parameter ready to complete the subsequent service logical operations. That in springmvc framework, the need to complete some additional processing parameters, springmvc framework will automatically help us to complete.

Common data types: basic data types, packaging, array, object collections (List, Set, Map), JSON

Here are some examples of the main code:

springmvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<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/mvc
       http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">

    <context:component-scan base-package="com.lzy"></context:component-scan>

    <mvc:annotation-driven>
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

    <!--配置视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--配置前缀-->
        <property name="prefix" value="/"></property>
        <!--配置后缀-->
        <property name="suffix" value=".jsp"></property>
    </bean>

</beans>

Control layer:

package com.lzy.controller;

import com.lzy.dao.CourseDAO;
import com.lzy.entity.Course;
import com.lzy.entity.CourseList;
import com.lzy.entity.CourseMap;
import com.lzy.entity.CourseSet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class DataBindController {

    //测试基本数据类型的绑定
    @RequestMapping(value = "/baseType")
    @ResponseBody
    //@ResponseBody注解:直接返回结果给客户端,不跳转jsp页面
    //@RequestParam注解:将http请求的id绑定到形参当中
    public String baseType(@RequestParam(value = "id") int id) {
        //直接返回拼接的字符串给客户端
        return "id:" + id;
    }

    //测试包装类的绑定
    @RequestMapping(value = "/packageType")
    @ResponseBody
    public String packageType(@RequestParam(value = "id") Integer id) {
        return "id:" + id;
    }

    //测试数组
    //第一步 拼接字符串
    //第二步 遍历数组
    @RequestMapping(value = "/arrayType")
    @ResponseBody
    public String arrayType(String[] name) {
        //拼接字符串使用StringBuffer
        StringBuffer sbf = new StringBuffer();
        //遍历数组
        for (String item : name) {
            sbf.append(item).append(" ");
        }
        //将string类型的值返回给前端
        return sbf.toString();
    }

    @Autowired
    private CourseDAO courseDAO;

    //测试对象
    @RequestMapping(value = "/pojoType")
    //由于返回的是ModelAndView,ModelAndView里带有视图信息,直接返回视图即可,这时候就不需要添加@ResponseBody了
    public ModelAndView pojoType(Course course) {
        //保存对象
        courseDAO.add(course);
        //响应
        ModelAndView modelAndView = new ModelAndView();
        //添加视图信息
        modelAndView.setViewName("index");
        //添加模型数据
        modelAndView.addObject("courses", courseDAO.getAll());
        return modelAndView;
    }

    //测试list集合
    @RequestMapping(value = "/listType")
    public ModelAndView listType(CourseList courseList) {
        for (Course course : courseList.getCourses()) {
            courseDAO.add(course);
        }
        //响应
        ModelAndView modelAndView = new ModelAndView();
        //添加视图信息
        modelAndView.setViewName("index");
        //添加模型数据
        modelAndView.addObject("courses", courseDAO.getAll());
        return modelAndView;
    }

    //测试Map集合
    @RequestMapping(value = "/mapType")
    public ModelAndView mapList(CourseMap courseMap){
        for(String key:courseMap.getCourses().keySet()){
            Course course = courseMap.getCourses().get(key);
            courseDAO.add(course);
        }
        //响应
        ModelAndView modelAndView = new ModelAndView();
        //添加视图信息
        modelAndView.setViewName("index");
        //添加模型数据
        modelAndView.addObject("courses", courseDAO.getAll());
        return modelAndView;
    }

    //测试Set集合
    @RequestMapping(value = "/setType")
    public ModelAndView setType(CourseSet courseSet){
        for(Course course:courseSet.getCourses()){
            courseDAO.add(course);
        }
        //响应
        ModelAndView modelAndView = new ModelAndView();
        //添加视图信息
        modelAndView.setViewName("index");
        //添加模型数据
        modelAndView.addObject("courses", courseDAO.getAll());
        return modelAndView;
    }

    //测试json
    @RequestMapping(value = "/jsonType")
    public Course jsonType(@RequestBody Course course){
        course.setPrice(course.getPrice()+100);
        return course;
    }
}


 

Guess you like

Origin blog.csdn.net/qq_41937388/article/details/90690555
Recommended