Spring MVC framework Foundation

1. Spring integrated Web environment

Disadvantages: the application context object is obtained through new ClasspathXmlApplicationContext, but it must be written every time the Bean is obtained from the container. Such disadvantages are that the configuration file is loaded many times and the application context object is created many times

Solution: in the Web project, you can use the ServletContextListener to listen to the startup of the Web application. When the Web application starts, we can load the Spring configuration file, create the application context object ApplicationContext, and store it in the largest domain ServletContext domain, In this way, the application context ApplicationContext object can be obtained from the domain at any location

Therefore, when we need to obtain the Bean in the IOC container, we only need to:

  1. Configuring the ContextLoaderListener listener
  2. Get application context using WebApplicationContextUtils

2. Spring MVC component parsing

2.1 execution process

  1. The user sends a request to the front-end controller DispatcherServlet
  2. The dispatcher servlet receives a request to call the handler mapping processor mapper
  3. The processor mapper finds the specific processor (which can be found according to Xml configuration and annotation), generates the processor object and the processor interceptor (if any) and returns it to the dispatcher servlet
  4. Dispatcher servlet calls HandlerAdapter processor adapter
  5. The HandlerAdapter calls the specific processor (back-end Controller) through adaptation
  6. The Controller returns ModelAndView after execution
  7. The HandlerAdapter returns the Controller execution result ModelAndView to the dispatcher servlet
  8. DispatcherServlet passes ModelAndView to viewrestrover view parser
  9. The viewrestrover returns a specific View after parsing
  10. The dispatcher servlet renders the View according to the View (that is, fills the View with model data), and the dispatcher servlet responds to the user

2.2 component analysis

  1. Front end controller: dispatcher Servlet
    • When the user's request reaches the front-end controller, it is equivalent to C in MVC mode. Dispatcher servlet is the center of the whole process control. It calls other components to process the user's request. The existence of dispatcher servlet reduces the coupling between components
  2. Processor mapper: HandlerMapping
    • Find the Handler, that is, the processor, according to the user's request. Spring MVC provides different mappers to implement different mapping methods, such as configuration file mode, implementation interface mode, annotation mode, etc
  3. Processor adapter: HandlerAdapter
    • HandlerAdapter is used to execute relevant processor handlers according to specific rules according to the processor Handler information found by the mapper
  4. Processor: Handler
    • It is the specific service controller to be written in our development. The dispatcher servlet forwards the user request to the Handler, and the Handler processes the specific user request
  5. View resolver: ViewResolver
    • The ViewResolver generates a View from the processing results. The ViewResolver first resolves the logical View name into a physical View name, that is, a specific page address, and then generates a View object. Finally, it renders the View and displays the processing results to the user through the page

2.3 annotation analysis

@RequestMapping

Function: used to establish the correspondence between the request URL and the request processing method

Location:

  • Class, request the first level access directory of the URL. If it is not written here, it is equivalent to the root directory of the application
  • Method, the second level access directory of the request URL and the first level directory marked with @ ReqquestMapping on the class form an access virtual path

Parameters:

  • value: used to specify the URL of the request
  • Method: used to specify the method of the request
  • params: used to specify conditions that restrict request parameters
    • params={"username"} indicates that the request parameter must have username
    • params={"age!18"} indicates that the request parameter age cannot be 18

Using Spring mvc annotation configuration requires the introduction of mvc namespace. At the same time, because Spring mvc is based on Spring container, it is necessary to store the Controller in Spring container during Spring mvc operation (Spring container and Spring mvc container are parent-child containers, and Spring mvc can access resources in Spring container, not vice versa)

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

2.4 XML configuration parsing

View parser: suffix before modification

  • Prefix: prefix
  • Suffix: suffix
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/views/"/>
    <property name="suffix" value=".jsp"/>
</bean>

3. Spring MVC data response

3.1 data response mode

  1. Page Jump
    • Returns a string directly
    • Return via ModelAndView object
  2. Write back data
    • Returns a string directly
    • Returns an object or collection

3.2 page Jump

Directly return string: this method will splice the returned string with the pre suffix of the view parser and jump

Return ModelAndView object:

@RequestMapping("/test")
public ModelAndView testMethod(){
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.setViewName("redirect:index.jsp");
    return modelAndView;
}

@RequestMapping("/test")
public ModelAndView testMethod(){
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.setViewName("forward:/WEB-INF/views/index.jsp");
    return modelAndView;
}

In addition to new ModelAndView, you can also add ModelAndView in the parameter category to make spring MVC inject automatically

Store data to the request field:

  1. The request object injected through the spring MVC framework is set by the setAttribute() method

    @RequestMapping("/test")
    public String testMethod(HttpServletRequest request){
        request.setAttribute("name","zhangsan");
        return "index";
    }
    
  2. Set through the addObject() method of ModelAndView

    @RequestMapping("/test")
    public ModelAndView testMethod(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("forward:/WEB-INF/views/index.jsp");
        modelAndView.addObject("name","lisi");
        return modelAndView;
    }
    

3.3 updating data

Use the Response object:

The response object injected through the spring MVC framework uses response getWriter(). Print ("hello world") writes back data. At this time, view jump is not required, and the return value of the business method is void

@RequestMapping("/test")
public void testMethod(HttpServletResponse response) throws IOException {
    response.getWriter().print("Hello World");
}

Directly return string:

Return the string to be written back directly, but at this time, you need to inform the spring MVC framework through the @ ResponseBody annotation that the string returned by the method is not a jump, but directly returned in the http response body

@RequestMapping("/test")
@ResponseBody
public String testMethod() throws IOException {
    return "Hello SpringMVC";
}

Return object or collection:

If we need to return a POJO, we are generally used to returning a string in Json format. At this time, we need to use jackson tool for conversion

Spring MVC helps us to convert and write back json strings to objects or collections, configure message conversion parameters for the processor adapter, and specify the use of jackson to convert objects or collections. Therefore, spring MVC XML is configured as follows:

<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    <property name="messageConverters">
    	<list>
    		<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
        </list>
     </property>
</bean>

After configuration, we only need to return the json string:

@RequestMapping("/test")
@ResponseBody public User testMethod() throws IOException {
    User user = new User();
    user.setUsername("Think not envy immortals");
    user.setAge(18);
    return user;
}

Adding @ ResponseBody to the method can return a string in json format, but this configuration is cumbersome and there are many configured codes. Therefore, we can use mvc annotation driven instead of the above configuration:

<mvc:annotation-driven/>

4. Spring MVC obtains request data

The format of client request parameters is: name = value & name = value & name = value

To obtain the requested parameters, the server sometimes needs to encapsulate the data. Spring MVC can receive the following types of parameters:

  • Basic type parameters
  • POJO type parameters
  • Array type parameter
  • Set type parameter

4.1 obtaining basic type parameters

The parameter name of the business method in the Controller should be consistent with the name of the request parameter, and the parameter value will be mapped and matched automatically

@RequestMapping("/test")
@ResponseBody
public void testMethod(String username,int age) throws IOException {
    System.out.println(username);
    System.out.println(age);
}

4.2 obtaining POJO type parameters

The property name of the POJO parameter of the business method in the Controller is consistent with the name of the request parameter, and the parameter value will be mapped and matched automatically

// Request address: http://localhost:8080/test?username=apple&age=18
@Data
public class User {
    private String username;
    private int age;
}
@RequestMapping("/test")
@ResponseBody
public void testMethod(User user) throws IOException {
    System.out.println(user);
}

4.3 get array type parameters

The name of the business method array in the Controller is consistent with the name of the request parameter, and the parameter values will be mapped and matched automatically

// Request address: http://localhost:8080/test?strs=111&strs=222&strs=333
@RequestMapping("/test")
@ResponseBody
public void testMethod(String[] strs) throws IOException {
    System.out.println(Arrays.asList(strs));
}

4.4 get set type parameters

When obtaining set parameters, you need to wrap them in a POJO, that is, create a VO object with list < user > userlist member variables inside. The form can be as follows:

<form action="${pageContext.request.contextPath}/test" method="post">
    <input type="text" name="userList[0].username"><br>
    <input type="text" name="userList[0].age"><br>
    <input type="text" name="userList[1].username"><br>
    <input type="text" name="userList[1].age"><br>
    <input type="submit" value="Submit"><br>
</form>

When submitting with ajax, you can specify the content type as json, so using @ RequestBody in the method parameter position can directly receive the collection data without using POJO for packaging

@RequestMapping("/test")
@ResponseBody
public void testMethod(@RequestBody List<User> userList) throws IOException {
    System.out.println(userList);
}

Release the specified resource:

It is not loaded into the jquery file because the URL pattern of the DispatcherServlet, the front-end controller of spring MVC, is configured as /, which means that all resources are filtered. We can specify the release of static resources in the following two ways:

<mvc:resources mapping="/js/**" location="/js/"/> 

<mvc:default-servlet-handler/>

Note the first method above:

  • /The page will not be intercepted, only the path will be intercepted
  • /*Is a page that blocks all folders, excluding subfolders
  • /**It is a page that intercepts all folders and subfolders inside

4.5 request data garbled

When post requests, the data will be garbled. We can set a filter to filter the encoding

<filter>
    <filter-name>CharacterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

4.6 parameter binding annotation

When the requested parameter name is inconsistent with the business method parameter name of the Controller, the binding displayed through the @ RequestParam annotation is required

<form action="${pageContext.request.contextPath}/test" method="post">
    <input type="text" name="name"><br>
    <input type="submit" value="Submit"><br>
</form>
@RequestMapping("/test")
@ResponseBody
public void testMethod(@RequestParam("name") String username) throws IOException {
    System.out.println(username);
}

@Parameters of RequestParam:

  • value: the name of the request parameter
  • required: whether the specified request parameters must be included. The default is true. If there is no such parameter during submission, an error will be reported
  • defaultValue: when no request parameter is specified, the specified default value is used for assignment

4.7 get Restful style parameters

Restful is a software architecture style and design style, not a standard. It only provides a set of design principles and constraints. It is mainly used for the software of client and server interaction. The software designed based on this style can be more concise, hierarchical and easier to implement the cache mechanism

Restful style requests use [url + request method] to indicate the purpose of a request. The four verbs in the HTTP protocol indicating the operation method are as follows:

  • GET: used to GET resources
  • POST: used to create a new resource
  • PUT: used to update resources
  • DELETE: used to DELETE resources

The hello in the above url address / user/hello is the request parameter to be obtained. In spring MVC, placeholders can be used for parameter binding. The address / user/hello can be written as / user/{id}, and the placeholder {id} corresponds to the value of Hello. In the business method, we can use the @ PathVariable annotation to match and obtain placeholders

// Request address: http://localhost:8080/test/zhangsan
@RequestMapping("/test/{name}")
@ResponseBody
public void testMethod(@PathVariable(value = "name",required = true) String name){
    System.out.println(name);
}

4.8 custom type converter

Spring MVC provides some common type converters by default. For example, the string submitted by the client is converted to int type for parameter setting, but not all data types provide converters. If not provided, custom converters are required. For example, custom converters are required for date type data

Development steps of custom type converter:

  1. Define the Converter class to implement the Converter interface

    public class DateConverter implements Converter<String,Date>{
        @Override
        public Date convert(String source) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            try {
                Date date = format.parse(source);
                return date;
            } catch (ParseException e) {
                e.printStackTrace();
            }
            return null;
        }
    }
    
  2. Declare the converter in the configuration file

    <bean id="converterService" class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters">
            <list>
                <bean class="com.example.converter.DateConverter"/>
           </list>
        </property>
    </bean>
    
  3. Reference the converter in < annotation driven >

    <mvc:annotation-driven conversion-service="converterService"/>
    

4.9 get Servlet related API s

Spring MVC supports using the original servlet API object as the parameter of the controller method for injection. The common objects are as follows:

  • HttpServletRequest
  • HttpServletResponse
  • HttpSession

4.10 get request header

1. @RequestHeader annotation

Equivalent to request Getheader (name) method. The annotation has the following properties:

  • value: the name of the request header
  • required: whether this request header must be carried
@RequestMapping("/test")
@ResponseBody
public void testMethod(@RequestHeader(value = "User-Agent",required = false) String headerValue){
    System.out.println(headerValue);
}

2. @CookieValue annotation

Use this annotation to obtain the value of the specified Cookie. The annotation has the following properties:

  • value: Specifies the name of the Cookie
  • required: do you have to carry this Cookie
@RequestMapping("/test")
@ResponseBody
public void testMethod(@CookieValue(value = "JSESSIONID",required = false) String jsessionid){
    System.out.println(jsessionid);
}

4.11 file upload

Three elements of file upload

  • Form item type = "file"

  • The form is submitted by post

  • The enctype attribute of the form is a multi part form, and enctype = "multipart / form data"

File upload principle

  • When the form is modified to a multipart form, request Getparameter() will fail

  • enctype = "application/x-www-form-urlencoded", the format of form body content is: key = value & key = value & key = value

  • When the enctype value of the form is mutilpart / form data, the content of the request body becomes multi part:

    Single file upload steps

  1. Import Commons fileUpload and Commons IO coordinates

  2. Profile upload parser

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!--Total size of uploaded files-->
        <property name="maxUploadSize" value="5242800"/>
        <!--Upload the size of a single file-->
        <property name="maxUploadSizePerFile" value="5242800"/>
        <!--Encoding type of uploaded file-->
        <property name="defaultEncoding" value="UTF-8"/>
    </bean>
    
  3. Write file upload code

    @RequestMapping("/test")
    @ResponseBody
    public void testMethod(String name,MultipartFile uploadFile) throws IOException {
        //Get file name
        String originalFilename = uploadFile.getOriginalFilename();
        //Save file
        uploadFile.transferTo(new File("C:\\upload\\"+originalFilename));
    }
    

Multi file upload steps

To upload multiple files, you only need to change the page to multiple file upload items and change the method parameter MultipartFile type to MultipartFile []

@RequestMapping("/test")
@ResponseBody
public void testMethod(String name,MultipartFile[] uploadFiles) throws IOException {
    for (MultipartFile uploadFile : uploadFiles){
        String originalFilename = uploadFile.getOriginalFilename();
        uploadFile.transferTo(new File("C:\\upload\\"+originalFilename));
    }
}

Keywords: Java Spring Framework Spring MVC

Added by phpcoder24july on Fri, 14 Jan 2022 04:50:56 +0200