preface
The main points of this article are as follows:
- Parameter binding
- The echo data
- File upload
Parameter binding
We use method parameters in the Controller to receive values, that is, to receive web values into the Controller for processing, this process is called parameter binding…
Parameter types supported by default
We can use request objects, Model objects, and so on. Not really…
The Controller method supports four parameter types by default, which is enough to support our daily development
- HttpServletRequest
- HttpServletResponse
- HttpSession
- Model
Parameter binding process
In general, we use custom parameter bindings such as the date-type conversions described above and some special requirements…. We don’t need a converter for normal parameter binding, SpringMVC does that for us…
Custom binding parameters [old method, all Action can be used]
In the previous article, we briefly explained how to convert strings to dates (using WebDataBinder)… That’s actually an older approach, we can use SpringMVC’s more recommended approach…
The last time we converted a string to a date, if we were using WebDataBinder, this conversion would only work for the current Controller… If you want all controllers to use WebBindingInitializer, you can use WebBindingInitializer
If multiple controllers need to register the same property editor, implement the PropertyEditorRegistrar interface and inject it into webBindingInitializer.
Implementing an interface
public class CustomPropertyEditor implements PropertyEditorRegistrar {
@Override
public void registerCustomEditors(PropertyEditorRegistry binder) {
binder.registerCustomEditor(Date.class, new CustomDateEditor(
new SimpleDateFormat("yyyy-MM-dd HH-mm-ss"), true)); }}Copy the code
Configuration converter
Inject into webBindingInitializer
<! -- Register property editor -->
<bean id="customPropertyEditor" class="cn.itcast.ssm.controller.propertyeditor.CustomPropertyEditor"></bean>
<! Customizing webBinder -->
<bean id="customBinder"
class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
<! -- propertyEditorRegistrars -->
<property name="propertyEditorRegistrars">
<list>
<ref bean="customPropertyEditor" />
</list>
</property>
</bean>
<! -- Annotation adapter -->
<bean
class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<! Inject a custom property editor and converter into webBindingInitializer -->
<property name="webBindingInitializer" ref="customBinder"></property>
</bean>
Copy the code
Custom parameter converter
The above method is the older object, now we usually implement the Converter interface to implement the custom parameter conversion… Let’s see what’s better about implementing Converter than the above
Configuring the Date Converter
public class CustomDateConverter implements Converter<String.Date> {
@Override
public Date convert(String source) {
try {
// Convert the date
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(source);
} catch (Exception e) {
e.printStackTrace();
}
return null; }}Copy the code
Configure to remove the string converter
public class StringTrimConverter implements Converter<String.String> {
@Override
public String convert(String source) {
try {
// Remove the whitespace from both sides of the string, or set it to null if it is empty
if(source! =null){
source = source.trim();
if(source.equals("")) {return null; }}}catch (Exception e) {
e.printStackTrace();
}
returnsource; }}Copy the code
From the above, we can see that we want to convert anything, directly implement the interface, and the interface is generic support, very easy to read…
Configuration converter
<! -- Converter -->
<bean id="conversionService"
class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="cn.itcast.ssm.controller.converter.CustomDateConverter"/>
<bean class="cn.itcast.ssm.controller.converter.StringTrimConverter"/>
</list>
</property>
</bean>
<! Customizing webBinder -->
<bean id="customBinder"
class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
<! Use Converter to convert parameters -->
<property name="conversionService" ref="conversionService" />
</bean>
<! -- Annotation adapter -->
<bean
class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<! Inject a custom property editor and converter into webBindingInitializer -->
<property name="webBindingInitializer" ref="customBinder"></property>
</bean>
Copy the code
If it’s based on < MVC: Annotation-driven >, we configure it like this
<mvc:annotation-driven conversion-service="conversionService">
</mvc:annotation-driven>
<! -- conversionService -->
<bean id="conversionService"
class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<! -- Converter -->
<property name="converters">
<list>
<bean class="cn.itcast.ssm.controller.converter.CustomDateConverter"/>
<bean class="cn.itcast.ssm.controller.converter.StringTrimConverter"/>
</list>
</property>
</bean>
Copy the code
@ RequestParam annotations
The parameter bindings we typically use follow the rule that the method parameter name should be the same as the name of the passed name property.
By default, SpringMVC will only help us with parameter binding if the name is the same…
If we use the @requestParam annotation, we can make the method parameter name different from the name attribute that was passed in…
This annotation has three variables
- Value [specifies what the name of the name attribute is]
- Required [Is this parameter required]
- Defaultvalue sets the defaultvalue
Example: Our method argument is called id, and the name attribute on the page is called item_id, which must be required
public String editItem(@RequestParam(value="item_id",required=true) String id) {}Copy the code
The Controller method returns the value
There are only a few types of Controller method return values, so let’s summarize them….
- void
- String
- ModelAndView
- Redirect to redirect
- Forward forward
The echo data
In fact, the data echo we now on the word is not strange…. We learned to echo data when we first used EL expressions, and we also had three loops of data echo problems when we did SSH projects…
Data echo on the page is essentially getting the value of the REqeUST field..
In our SpringMVC, we use the Model to bind data into the Request domain object
Typically we bind data to request domain objects using model.addattribute ()… SpringMVC also supports annotations
@ModelAttribute
annotations
We can put the requested parameters into the Model and echo them to the page
This usage is no different from the model.addattribute () approach, nor does it make annotations convenient…
If the data we want to display is public, then we can realize the convenience of annotation. We can extract the public attributes into methods and return the value.
So we don’t have to pass data to the page through the Model in every controller method.
SpringMVC file upload
When we used Struts2, we found the Struts2 file upload method much easier than the traditional file upload method…
Blog.csdn.net/hon_3y/arti…
Now that we’re learning about SpringMVC, let’s look at how SpringMVC actually uploads files…
Configuring a Virtual Directory
In this case, we’re not uploading images to our project catalog…
Why not upload the image directly to our project catalog?? Let’s think about it and do what we did before, upload files directly to our project directory, where we write our code… Often we need to back up our project directory.
It would be very difficult to process images if they were uploaded to the project directory…
Therefore, we need to configure the Tomcat virtual directory to solve the problem, put the uploaded files in the virtual directory…
It is also worth noting that Tomcat for Idea does not use the traditional configuration method, which is to modify the server. XML mode to configure virtual directories.
If you are interested, you can take a test:
Blog.csdn.net/hon_3y/arti…
Then I have found the corresponding solution on the Internet, that is, how to configure virtual directory on IDEA
Blog.csdn.net/LABLENET/ar…
Check whether the configuration is successful:
Quick start
Jar package used for file upload in SpringMVC
- Commons fileupload – 1.2.2. Jar
- Commons – IO – 2.4. The jar
Configuration file upload parser
<! -- File upload -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<! -- Set the maximum size of uploaded files to 5MB -->
<property name="maxUploadSize">
<value>5242880</value>
</property>
</bean>
Copy the code
Test the JSP
<%--
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"% >
<html>
<head>
<title>Test file upload</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/upload.action" method="post" enctype="multipart/form-data" >
<input type="file" name="picture">
<input type="submit" value="submit">
</form>
</body>
</html>
Copy the code
It should be noted that the name of the JSP property is “picture”, so the name of the Controller method parameter should also be “picture”, otherwise it will not get the corresponding file..
@Controller
public class UploadController {
@RequestMapping("/upload")
//MultipartFile Encapsulates the image file
public void upload(MultipartFile picture) throws Exception { System.out.println(picture.getOriginalFilename()); }}Copy the code
conclusion
- There are four arguments supported by business methods in SpringMVC by default
- request
- response
- session
- model
- Our parameter binding (automatic encapsulation of parameters) is done by our converter. These days, they usually use Converter
- In the previous chapter, we used the WebDataBinder method to convert the date format.This is only available for the current Action. There are two ways to make all actions available:
- Implement PropertyEditorRegistrar(the older way)
- Implement Converter(New Way)
- Parameter bindings follow the same rule: the method parameter name must be the same as the name of the passed name property
- We can use the @requestParam annotation to specify the name of the corresponding attribute, which also allows for parameter binding.
- You can also configure whether this parameter is required.
- The Controller method returns five values:
- void
- String
- ModelAndView
- Redirect to redirect
- Forward forward
- Inside the Model is binding the data to the Request domain object.
- The @ModelAttribute annotation can bind data to the Model (that is, to the request). If you often need to bind data to the Model, it is a good idea to use this annotation as a method.
- Idea configuring a virtual directory is essentially adding one more Deployment and configuring its application path
- SpringMVC’s file upload is to configure an upload parser that uses MultipartFile to receive the brought file.
If the article has the wrong place welcome to correct, everybody exchanges with each other. Students who are used to reading technical articles on wechat and want to get more Java resources can follow the wechat public account :Java3y