Springmvc "parameter binding, data echo, File upload"

Source: Internet
Author: User

Objective

The main points of this article are as follows:

    • Parameter binding
    • Data echo
    • File Upload
Parameter binding

We use the method parameter in the controller to receive the value, that is, the Web side of the value to receive the controller processing, this process is called parameter binding ...

Default supported parameter types

From the above usage, we can find that we can use the request object, model object and so on, in fact, can you just write the parameters on the line??? It's not really ...

The Controller method supports 4 parameter types by default, and these 4 are sufficient to support our daily development

    • HttpServletRequest
    • HttpServletResponse
    • HttpSession
    • Model
Binding Process for parameters

In general, we need to use a custom parameter binding is the above mentioned date type conversion and some special requirements .... For the usual parameter binding, we do not need to use the converter, SPRINGMVC has helped us to do this job ...

Custom binding Parameters "old way, all action can be used"

In the previous article we have briefly explained how to convert a string into a date type "using the Webdatabinder method" ... In fact that is an older method, we can use SPRINGMVC more recommended way ...

The last time you convert a string to a date type, if you use the Webdatabinder method, the conversion can only be used in the current controller ... If you want all controllers to be able to use, then we can use the Webbindinginitializer method

If you want multiple controllers to register the same property editor together, you can implement the Propertyeditorregistrar interface and inject it into the webbindinginitializer.

Implementing interfaces

publicclassimplements PropertyEditorRegistrar {    @Override    publicvoidregisterCustomEditors(PropertyEditorRegistry binder) {        binder.registerCustomEditor(Date.classnewCustomDateEditor(                new SimpleDateFormat("yyyy-MM-dd HH-mm-ss"true));            }}
Configuring Converters

Injected into the Webbindinginitializer.

    <!--registering a property editor --    <beanid="Custompropertyeditor"class="Cn.itcast.ssm.controller.propertyeditor.CustomPropertyEditor"></bean>            <!--custom Webbinder --    <beanid="Custombinder"class="Org.springframework.web.bind.support.ConfigurableWebBindingInitializer">            <!--propertyeditorregistrars for property editor --         <propertyname="Propertyeditorregistrars">            <list>                <refbean="Custompropertyeditor" />            </list>        </property>    </bean>    <!--Note Adapter --    <beanclass="Org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">        <!--Inject custom property editors, custom converters, and Webbindinginitializer in the        <propertyname="Webbindinginitializer"ref="Custombinder"></property>    </bean>
Custom parametric Converters "new ways, Ways of advocating"

The above is an older object, and now we are generally implementing the converter interface to implement the custom parameter conversion ... Let's see what it's like to achieve converter.

Configure Date Converters

publicclassimplements Converter<String, Date> {    @Override    publicconvert(String source) {        try {            //进行日期转换            returnnew SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(source);                    catch (Exception e) {            e.printStackTrace();        }        returnnull;    }}

Configuring the Remove String Converter

public   Stringtrimconverter implements  converter<string, string> { @Override  public  String convert  (String source) {try  {//remove whitespace on both sides of the string if null after removal set to null  if (Source!=null ) {Source = Source. (); if  (source. equals  ())                {return  null ; }}} catch  (Exception e) {e.printstack        Trace  ();    } return  source; }}

From the above can be drawn, we want to convert what content, directly implement the interface, the interface is support generics, reading is very convenient ...

Configuring Converters
    <!--Converters --    <beanid="Conversionservice"class="Org.springframework.format.support.FormattingConversionServiceFactoryBean">        <propertyname="Converters">            <list>                <beanclass="Cn.itcast.ssm.controller.converter.CustomDateConverter"/>                <beanclass="Cn.itcast.ssm.controller.converter.StringTrimConverter"/>            </list>        </property>    </bean>    <!--custom Webbinder --    <beanid="Custombinder"class="Org.springframework.web.bind.support.ConfigurableWebBindingInitializer">        <!--using Converter for parameters        <propertyname="Conversionservice"ref="Conversionservice" />    </bean>    <!--Note Adapter --    <beanclass="Org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">        <!--Inject custom property editors, custom converters, and Webbindinginitializer in the        <propertyname="Webbindinginitializer"ref="Custombinder"></property>    </bean>    

If it's based on <mvc:annotation-driven> that, we're configuring it.

<mvc:annotation-drivenconversion-service="Conversionservice"></mvc:annotation-driven><!--conversionservice --    <beanid="Conversionservice"class="Org.springframework.format.support.FormattingConversionServiceFactoryBean">        <!--Converters --        <propertyname="Converters">            <list>                <beanclass="Cn.itcast.ssm.controller.converter.CustomDateConverter"/>                <beanclass="Cn.itcast.ssm.controller.converter.StringTrimConverter"/>            </list>        </property>    </bean>
@RequestParam annotations

The parameter bindings we use generally have the following rules: The method parameter name is the same as the Name property passed over.

In the default case, only the name is the same, SPRINGMVC will help us with parameter binding ...

If we use it @RequestParam注解 , we can make the method parameter name different from the Name property passed over ...

The note has three variables

    • Value "Specifies what the Name property is."
    • Required "If you must have this parameter"
    • DefaultValue setting default values

Example: Our method parameter is called the ID, and the page comes over the Name property named ITEM_ID, you must need this parameter

publiceditItem(@RequestParam(value="item_id",required=true) String id) {}
Controller method return value

The return value of the Controller method is actually several types, let's summarize ....

    • void
    • String
    • Modelandview
    • REDIRECT Redirection
    • Forward forwarding
Data echo

In fact, the data echo our present words are no stranger .... We have just used the EL expression when we have learned the data echo, when doing the SSH project also has three laps problem data echo ...

The data echo on the page is essentially getting the value of the Reqeust field ...

In our Springmvc, we use model to bind data in the request domain object.

In general, we use the Model.addattribute () method to bind data to the request domain object ... In fact, SPRINGMVC also supports annotations in the way

@ModelAttributeAnnotations

We can put the requested parameters in the model and echo back to the page

The above usage and the Model.addattribute () way is no difference, also can not reflect the convenience of the annotation ...

And if the data we're going to echo is public, then we'll be able to appreciate the convenience of annotations, and we'll extract the properties of the public needs display into a method and return the return value to the line.

Then we don't have to use the model to upload data to a page in every controller method.

Springmvc File Upload

When we use STRUTS2, we feel that the Struts2 file upload method is more useful than the traditional file upload method ...

http://blog.csdn.net/hon_3y/article/details/71091593

Since we are learning SPRINGMVC, then we also see how Springmvc actually uploaded the file ...

Configure the virtual directory

In this case, we are not uploading the images to our engineering catalogue ...

Then why not upload the pictures directly to our engineering catalogue??? We think carefully, according to our previous practice, directly upload files to the engineering directory, and our engineering directory is where we write code ... Often we need to back up our engineering catalog.

If the pictures are uploaded to the project directory, it is very difficult to deal with the picture ...

Therefore, we need to configure the virtual directory of Tomcat to solve, put the uploaded files on the virtual directory ...

It is also worth noting that theidea used by Tomcat does not use the traditional configuration, that is, modify the Server.xml way to configure the virtual directory, it does not seem to support this approach ...

Interested students can go to test:

http://blog.csdn.net/hon_3y/article/details/54412484

So I have found a solution on the Internet, that is, if you configure the virtual directory on idea

http://blog.csdn.net/LABLENET/article/details/51160828

To detect whether the configuration was successful:

Quick Start

Jar package required for file upload in Springmvc

    • Commons-fileupload-1.2.2.jar
    • Commons-io-2.4.jar

Config file Upload parser

    <!-- 文件上传 -->    <bean id="multipartResolver"          class="org.springframework.web.multipart.commons.CommonsMultipartResolver">        <!-- 设置上传文件的最大尺寸为5MB -->        <property name="maxUploadSize">            <value>5242880</value>        </property>    </bean>

The JSP tested

<%--Created by IntelliJ idea. USER:OZC DATE:2017/8/11 time:9:56 To change this template use File | Settings | File templates.--%><%@ page contenttype= "Text/html;charset=utf-8" language= "java"%>    <title>Test File Upload</title><body><formaction="${pagecontext.request.contextpath}/upload.action"method="POST"enctype="Multipart/form-data" >    <inputtype="File"name="Picture">    <inputtype="Submit"value="Submit"></form></body>

It is worth noting that the name property of the JSP is written in the picture, then the controller method parameter names are also to write the picture, otherwise, the corresponding file is not obtained.

@Controllerpublicclass UploadController {    @RequestMapping("/upload")    //MultipartFile该对象就是封装了图片文件    publicvoiduploadthrows Exception {        System.out.println(picture.getOriginalFilename());    }}

Summarize
  • There are four parameters supported by default for business methods in SPRINGMVC
    • Request
    • Response
    • Session
    • Model
  • Our parameter bindings (auto-encapsulation parameters) are bound by our converters. It's usually a converter converter.
  • In the previous chapter we used the Webdatabinder approach to transform the date format, which was only available for the current action. There are two ways we want all action to work:
    • Implementation of Propertyeditorregistrar (older way)
    • Implementation of converter (new way)
  • Parameter bindings have rules to follow: The method parameter name is the same as the Name property passed over
    • We can use @requestparam annotations to specify the names of the corresponding Name property, which is also possible to implement parameter binding.
    • It is also possible to configure whether the parameter is required.
  • There are 5 return values for the Controller method:
    • void
    • String
    • Modelandview
    • REDIRECT Redirection
    • Forward forwarding
  • Inside the model is the binding of data to the request domain object.
  • @ModelAttribute annotations can bind data to model (that is, request), it is good to extract a method to use this annotation if it is often necessary to bind to the data in the model.
  • Idea to configure a virtual target is to add more than one deployment, and then configure its application path
  • Springmvc file upload is to configure an upload parser, using Multipartfile to receive the files brought over.

If the article is wrong, welcome to correct, we communicate with each other. accustomed to look at technical articles, want to get more Java resources of students, can pay attention to the public number: Java3y

Springmvc "parameter binding, data echo, File upload"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.