51718633
As we all know, SPRINGMVC is used to process a page of some requests, and then return the data through the view back to the user, the previous few posts are used in the static data, in order to get a quick start Springmvc, in this blog post, I will summarize the parameters of how to receive the foreground page in Springmvc, that is, the parameter binding problem in SPRINGMVC.
1. Process of parameter binding
We can recall that in struts2, a member variable is defined in the action to receive the parameters passed in by the foreground, whereas in Springmvc, the data submitted by the receiving page is received through a method parameter. From the Key/value data requested by the client, the parameters are bound, the Key/value data is bound to the parameters of the Controller method, and then the parameter can be used in the controller. Take a look at this process:
So we know that SPRINGMVC provides a lot of converters to bind page parameters to the parameter of the Controller method, and I'll refer to the custom converter. After a general understanding of the process, let's start with a concrete summary.
2. Default Supported Types
SPRINGMVC, there is a supported default type of binding. That is, you can use these objects by defining objects of the default type directly on the controller method parameters.
- HttpServletRequest Object
- HttpServletResponse Object
- HttpSession Object
- Model/modelmap Object
During parameter binding, binding is done directly if the type above is encountered. That is, we can define these types of parameters directly in the parameter of the controller's method, and SPRINGMVC will automatically bind. Here to illustrate is the Model/modelmap object, model is an interface, MODELMAP is an interface implementation, the role is to populate the model data to the request domain, similar to Modelandview, about its use, I'm going to say it with the simple type parameter bindings below.
3. Simple type of binding
To summarize this or take the demand as an example, it is easier to understand, assuming there is a need: according to the product ID to modify the corresponding point of the product information. So the front page must pass in the ID of the product, and then SPRINGMVC the controller for processing, returning a page to modify the product information. About the front page of the things are very simple, I do not post code, the main section of the figure, the specific code at the end of the article.
The foreground page passes the parameters through the URL, and the request is edititems.action.
The following Edititems method is written in the controller:
@RequestMapping("/editItems")public String editItems(Model model, Integer id) throws Exception { //根据id查询对应的Items ItemsCustom itemsCustom = itemsService.findItemsById(id); model.addAttribute("itemsCustom", itemsCustom); //通过形参中的model将model数据传到页面 //相当于modelAndView.addObject方法 return "/WEB-INF/jsp/items/editItems.jsp";}
This is a very simple demo, as you can see from the code above that the model can be directly used as a parameter, SPRINGMVC binds it by default, and then uses the model to put the queried data into the request domain so that the data can be taken out of the foreground page.
It is important to note that in a simple type of binding, the parameter names in the method parameters must be the same as the name passed in by the foreground to complete the binding of the arguments. Then someone asked, if there is a special need (such as better readability?). ), the name of the parameter defined here is not the same, then what is the whole? Is there a way out? Yes! We can use annotation @requestparam to bind a simple type to a parameter, as follows:
Therefore, if you do not use @requestparam, request the parameter name passed in and the Controller method has the same formal parameter name before binding succeeds. If you use @requestparam, you do not have to restrict the request to pass in parameter names consistent with the Controller method's formal parameter names. The Required property in @requestparam Specifies whether the parameter must be passed in, and if set to True, an error will be given without an incoming parameter.
4. Binding of the Pojo type
4.1 Common Pojo types
Again to summarize the Pojo type of binding, continue the above case, when the page shows the product details, I made the changes, and then click Submit, the background should be my submitted parameters are all updated to the database in the items table, that is, The parameters that I submit are bound to the items object or to its extension object. Let's take a look at the properties in items:
As you can see, there are various types of attributes, and when we commit, we want to encapsulate all these properties in a pojo and then go to update the database.
Binding is simple, for basic types, you can bind data in a page to Pojo by requiring the Name property value of the input tag in the page to be the same as the property names in the controller's Pojo parameter. That is, the foreground page is passed in the name of the Pojo property to be encapsulated exactly the same name, and then you can put the Pojo as a formal parameter in the controller's method, as follows:
This allows you to encapsulate the different attribute values in the foreground table only son into the itemscustom. But run it will find an error, error message is unable to convert the string type to java.util.Date type, because there is a property in the above items is a date type of createtime. This requires that we define the converter ourselves, which is the focus of this section, and we define a date converter ourselves:
Need to implement the converter interface, here is the conversion of string type to date typePublicClassCustomdateconverterimplements converter<String, Span class= "Hljs-title" >date> { @Override public Date Span class= "Hljs-title" >convert (String source) {//implementation convert date string to date type (format Yyyy-mm-dd HH:mm:ss) SimpleDateFormat SimpleDateFormat = new SimpleDateFormat ( " Yyyy-mm-dd HH:mm:ss "); try {//turns directly back to return Simpledateformat.parse (source); } catch (parseexception e) {//TODO auto-generated Catch block E.printstacktrace (); } //if parameter binding fails to return null return null;}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
Once the converter is defined, the following configuration is required in Springmvc.xml:
Now, SPRINGMVC can convert the string type to the date type correctly based on the converter, and then encapsulate it into the itemscustom.
Here is a small episode: After modifying the product details submitted, there may be a Chinese garbled problem, expression submission is post mode, Springmvc about the post method of Chinese garbled problem can be configured in Web. XML in a filter to solve, as follows:
4.2. Pojo Type of packaging
What is the difference between this packing type Pojo and the ordinary Pojo above? Packaging type Pojo refers to the Pojo has another is also pojo properties, that is Pojo set Pojo, why design this pojo? As I mentioned in the previous blog post, this combination of design methods is useful for later program extensions, such as complex query conditions that need to be packaged into this type of wrapper.
So how do you bind it? There are two ways of thinking:
- Add the HttpServletRequest request parameter to the formal parameter to receive the query condition parameters through request.
- In the formal parameter, let the Pojo of the wrapper type receive the query condition parameter.
The first approach is similar to the original servlet, where the second method is used, and we pass in a wrapper type of Pojo. Take a look at the Pojo of this package type:
There is also a Itemscustom class in this wrapper Pojo, which inherits the items class and is used to extend related information in the user object related to items. So this itemscustom has the name attribute, what if we want to encapsulate the Name property passed in by the foreground into the name attribute in Itemscustom? This is the Pojo parameter binding problem for the wrapper type.
Very simple, at the front desk we can pass this way:
Then the controller in the method of the formal parameters of the package type of Pojo, that is, Itemsqueryvo, hit a breakpoint, you can see whether the value is passed in. As follows:
This can be based on the user passed in the parameters, the replication of the query operation.
5. Binding of collection types
5.1 Binding of arrays
The binding of arrays means that there are multiple data of the same type in the foreground, and we use array parameters in the controller to receive data from the foreground. Or a case to drive this part of the content, such as now we want to bulk delete goods, then we need to tick a few products, these products have ID number, in the controller, we need to get all these ID numbers and put into an array, The corresponding item in the database is then deleted by the ID number in the array. So how do you bind it? In fact, it is very simple, as follows:
The controller's method is defined as:
The parameters that correspond to the foreground pass are:
This allows you to bind multiple IDs passed in from the foreground to the array, and then we can get the ID of the item to delete from the array.
binding of the 5.2 list
Usually when you need to submit data in bulk, the data will be submitted to the binding list<pojo>
, such as: score input (input multi-course results, batch submission), here we assume that there is demand: bulk product modification, enter multiple product information on the page, to submit multiple product information to the Controller method, Update multiple product information at once.
So the idea is to add a new one in the extension class Itemsqueryvo List<ItemsCustom>
, and then save the information for the different items to the list, so modify the following:
Definition of the Controller method:
1, enter the bulk product modification page
2. Batch modification of product submission
So there should be two methods in the controller, as follows:
How does the foreground JSP page pass in the parameters? This is the problem we care about, because the data received in the background parameter is the wrapper class Itemsqueryvo. See below:
So we know that the foreground is passing parameters in a form similar to List[i].name. List[i] denotes the first itemscustom and then List[i]. The property represents the corresponding attribute in the I-itemscustom.
Bindings for 5.2 map
The binding of the map is actually the same as the binding of the list, and the first is to add a new map type attribute to the Pojo of the wrapper, such as (I would like to give an example, regardless of this example)
Public class QueryVo {private Map<String, Student> itemInfo = new HashMap<String, Student>(); //get/set方法..}
The key is that the foreground is not the same as the list when the reference, such as map is transmitted, such as:
<tr> < td> Student Information: </td> <td> name: <input Type= "text" name= "itemInfo[" name "]"/> Age: <input type= "text" name= "iteminfo[' price ']"/>. .. .. </td></ TR>
We can see that the parameter bindings for map come from the key in the map, and then value is automatically bound to the attribute of that object in the map. In the controller of the method, the formal parameters are directly used to receive QUERYVO, but also very simple.
About SPRINGMVC parameter binding basically summed up to this, in fact, the principle is similar, just for different types, binding way some difference, think more about writing, basic can master these.
Related reading: http://blog.csdn.net/column/details/spring-mvc.html
Learning Note Source: Https://github.com/eson15/SpringMVC_Study
Summary of parameter bindings in SPRINGMVC