Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to solve the problem of parameter binding in SpringMVC

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "how to solve the parameter binding problem in SpringMVC". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to solve the parameter binding problem in SpringMVC".

1. The process of parameter binding

We can recall that in struts2, the parameters coming from the foreground are received by defining a member variable in Action, while in springmvc, the data submitted by the receiving page is received through method parameters. The key/value data requested from the client, through parameter binding, binds the key/value data to the formal parameter of the controller method, which can then be used in controller. Take a look at this process:

So we know that springmvc provides a number of converters to bind page parameters to the formal parameters of the controller method, and I'll talk about custom converter below. After roughly understanding the process, let's make a specific summary.

two。 Types supported by default

In springmvc, there are supported default types of bindings. That is, you can use objects of the default type by defining them directly on the formal parameters of the controller method.

HttpServletRequest object HttpServletResponse object HttpSession object Model/ModelMap object

During the parameter binding process, bind directly if you encounter the above type. In other words, we can define these types of parameters directly in the formal parameters of the controller method, and the springmvc will bind automatically. What I want to explain here is the Model/ModelMap object. Model is an interface, and ModelMap is an interface implementation that populates Model data into the request field, similar to ModelAndView. I'll talk about its use with simple type parameter binding below.

3. Binding of simple types

To sum up, let's take the demand as an example, which is easier to understand. Suppose there is a demand now: modify the corresponding product information according to the id of the product. So the foreground page must be sent to the id of the product, and then the controller of springmvc will process it and return a page that modifies the product information. Things about the foreground page are very simple, I will not post the code, the main part of a screenshot, the specific code has a download address at the end of the article.

The foreground page passes the parameters through url, requesting editItems.action.

The following is the editItems method in controller:

@ RequestMapping ("/ editItems") public String editItems (Model model, Integer id) throws Exception {/ / query the corresponding Items ItemsCustom itemsCustom = itemsService.findItemsById (id) according to id; model.addAttribute ("itemsCustom", itemsCustom); / / transfer model data to the page through the model in the formal parameter / / equivalent to modelAndView.addObject method return "/ WEB-INF/jsp/items/editItems.jsp";}

This is a very simple demo, you can see from the above code that model can be directly used as a parameter, springmvc will bind it by default, and then use model to put the queried data into the request field, so that the data can be extracted from the foreground page.

It should be noted that in the binding of a simple type, the parameter name in the method parameter must be the same as the name passed in the foreground to complete the binding of the parameter. Then someone has to ask, if there are special needs (such as better readability? ), the parameter names defined here are just different, so how to fix it? Is there a solution? Yes! We can use the annotation @ RequestParam to bind parameters to simple types, as follows:

Therefore, if you do not use @ RequestParam, the request input parameter name is required to be the same as the formal parameter name of the controller method before the binding can be successful. If you use @ RequestParam, you don't have to restrict that the parameter name passed in by request is the same as the formal parameter name of the controller method. Specify whether the parameter must be passed through the required attribute in @ RequestParam. If it is set to true, an error will be reported if no parameter is passed in.

4. Binding of pojo type 4.1 normal pojo type

Then summarize the binding of the pojo type, continue the above case, when the page shows the product details, I made changes, and then click submit, the backend should update all these parameters I submitted to the items table of the database, that is to say, the parameters I submitted should be bound to the Items object or its extension object. Let's take a look at what attributes are available in Items:

As you can see, there are various types of properties, and when we submit them, we need to encapsulate them all in a pojo, and then update the database.

Binding is simple. For basic types, the name attribute value of the input tag in the page is required to be the same as the attribute name in the pojo parameter of controller, and the data in the page can be bound to pojo. In other words, the name passed in from the foreground page should be exactly the same as the pojo attribute name to be encapsulated, and then the pojo can be put into the controller method as a formal parameter, as follows:

This allows you to encapsulate the different attribute values passed in the foreground form into ItemsCustom. But after running it, you will find that the error message is that the String type cannot be converted to the java.util.Date type, because one of the attributes in the above Items is the createtime of type Date. This requires us to define our own converters, which is the focus of this section. Let's define a date converter ourselves:

/ / you need to implement the Converter interface. Here, convert the String type to the Date type public class CustomDateConverter implements Converter {@ Override public Date convert (String source) {/ / convert the date string to the date type (format is yyyy-MM-dd HH:mm:ss) SimpleDateFormat simpleDateFormat = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss") Try {/ / directly returns return simpleDateFormat.parse (source);} catch (ParseException e) {/ / TODO Auto-generated catch block e.printStackTrace ();} / / returns null return null;} if parameter binding fails

Once you have defined the converter, you need to configure it in springmvc.xml as follows:

Now that springmvc can convert the String type to the Date type correctly according to this converter, and then encapsulate it in ItemsCustom.

Here is a small episode: if you modify the product details and submit, there may be Chinese garbled problem. The expression and submission are all in post mode. The Chinese garbled problem in post mode in springmvc can be solved by configuring a filter in web.xml, as follows:

4.2. Pojo type of packaging

What is the difference between this packaging type pojo and the ordinary pojo above? The wrapper type pojo means that there is another attribute in pojo that is also pojo, that is, pojo sets pojo. Why would you design this kind of pojo? As I mentioned in the previous blog post, this combined design method is useful for later program expansion, such as complex query conditions that need to be packaged into this type of wrapper.

So how do you bind it? There are two ideas:

Add the HttpServletRequest request parameter to the parameter, and receive the query condition parameter through request. Let the wrapper type pojo receive the query condition parameters in the parameter.

The first method is similar to the original servlet. Using the second method, we pass in a wrapper type pojo. Take a look at the pojo of this wrapper type:

There is also an ItemsCustom class in the wrapper pojo, which inherits the Items class and is used to extend the relevant information in the User object associated with Items. So there is a name attribute in this ItemsCustom. If we want to encapsulate the name attribute passed from the foreground into the name attribute in the ItemsCustom, how do we pass it in? This is the problem of pojo parameter binding for wrapper types.

Quite simply, we can pass it on in this way at the front desk:

Then pass the parameter of the method in controller to the pojo of the wrapper type, namely ItemsQueryVo, and hit a breakpoint to see if the value has been passed in. As follows:

In this way, the query operation can be copied according to the parameters passed by the user.

5. Binding of collection type 5.1 array

Array binding refers to multiple data of the same type coming from the foreground, and we use array parameters in controller to receive the data from the foreground. For example, if we want to delete items in batches, we need to check several items, all of which have id numbers. In controller, we need to get all these id numbers and put them in an array, and then delete the corresponding items in the database one by one according to the id numbers in the array. So how do you bind it? In fact, it is also very simple, as follows:

The method of controller is defined as:

The parameters passed in the foreground are:

This allows you to bind multiple id passed in from the foreground to an array, and then we can take out the id of the item to be deleted from the array.

5.2 binding of List

Usually, when you need to submit data in batches, you will bind the submitted data to list, for example: score entry (enter multiple course scores, batch submission). Here we assume that there is a need: batch product modification, enter multiple product information on the page, and submit multiple product information to the controller method, that is, update multiple product information at a time.

So the idea is to add a new List to the extension class ItemsQueryVo, and then store the information of different products in this List, so modify it as follows:

Definition of the controller method:

1. Go to the batch product modification page

2. Batch modification and submission of goods

So there should be two methods in controller, as follows:

How do you pass parameters in the foreground jsp page? This is our concern, because the wrapper class ItemsQueryVo is used to receive data in the background parameters. Look at the following:

So we know that the foreground passes parameters in a form similar to list [I]. Name. List [I] denotes the first ItemsCustom, and then list [I]. Attribute represents the corresponding attribute in the I th ItemsCustom.

5.2 binding of Map

The binding of Map is actually similar to that of List. First of all, a new attribute of type Map is added to the wrapped pojo, such as (I'll give a random example, which has nothing to do with this example).

Public class QueryVo {private Map itemInfo = new HashMap (); / / get/set method..}

The key is that when passing parameters in the foreground, it is different from List. Map is passed in this way, such as:

Student information: name: age:. .. ..

We can see that the parameter binding of Map comes from the key in Map, and then value is automatically bound to the properties of that object in Map. In the method in controller, the parameter can be received directly using QueryVo, which is also very simple.

Thank you for reading, the above is the content of "how to solve the parameter binding problem in SpringMVC". After the study of this article, I believe you have a deeper understanding of how to solve the problem of parameter binding in SpringMVC, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report