【Spring】—Annotation of Spring MVC

Annotations for Spring MVC

1.DispatcherServlet

Full name of DispatcherServlet:

org.Springframework.web.servlet.DispatcherServlet

It acts as a front controller in the program.

[Example] When using DispatcherServlet, you only need to configure it in the web.xml file of the project, and its configuration code is as follows.

	<servlet>
        <!--配置前端过滤器-->
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--初始化时加载配置文件-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-config.xml</param-value>
        </init-param>
        <!--表示容器在启动时立即加载Servlet -->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

In the above code, <load-on-startup>both element and <init-param>element are optional. If <load-on-startup>the value of the element is 1, the Servlet will be loaded immediately when the application starts; if <load-on-startup>the element does not exist, the application will load the Servlet when the first Servlet is requested. If <init-param>the element exists and the path of the Spring MVC configuration file is configured through its sub-elements, the application will load the configuration file under the configuration path when it starts; if it is not configured through the element, the application will default <init-param>to the WEB-INF directory to find Configuration files named as follows.

servletName-servlet.xml

servletName refers to the name of the DispatcherServlet deployed in web.xml, which is springmvc in the configuration code in web.xml above, and -servlet.xml is a fixed way of writing the name of the configuration file, so the application will be in WEB-INF Find springmvc-servlet.xml under.

2. Controller annotation type

The org.springframework.stereotype.Controller annotation type is used to indicate that the instance of the Spring class is a controller, and its annotation form is @Controller. This annotation does not need to implement the Controller interface when it is used, just add the @Controller annotation to the controller class, and then find the controller marked with the annotation through Spring's scanning mechanism.

[Example] An example of using the @Controller annotation in a controller class is as follows.

package com.ssm.controller;
import org.springframework.stereotype.Controller;
......
//Controller注解
@Controller
public class ControllerTest{
    
    
......
}

In order to ensure that Spring can find the controller class, it is also necessary to add corresponding scanning configuration information in the Spring MVC configuration file, as follows.

(1) Introduced in the declaration of the configuration file spring-context.

(2) Use <context: component-scan>elements to specify the class package that needs to be scanned.

The complete configuration file is as follows.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.3.xsd">
    <!--  指定需要扫描的包  -->
    <context:component-scan base-package="com.ssm.controller"/>
</beans>

<context: component-scan>The attribute base-package of the element specifies that the class package to be scanned is com.ssm.controller. At runtime, all annotated classes under this package and its subpackages will be processed by Spring. Compared with the way of implementing the Controller interface, the way of using annotations is obviously simpler. At the same time, the implementation class of the Controller interface can only handle a single request action, while the annotation-based controller can handle multiple request actions at the same time , which is more flexible in use. Therefore, the annotation-based form is usually used in actual development.

Notice

When using the annotation method, the operation of the program needs to rely on Spring's AOP package, so you need to add spring.aop-4.3.6 RELEASE.jar to the lib directory, otherwise an error will be reported when the program is running.

3. RequestMapping annotation type

(1) Use of @RequestMapping annotation

After Spring finds the corresponding controller class through the @Controller annotation, it also needs to know how each request is processed inside the controller, which requires the use of org.springframework.web.bind.annotation.RequestMappingannotation types. RequestMapping is used to map a request or a method, and its annotation form is @RequestMapping, which can be annotated on a method or a class.

(1) marked on the method

When marked on a method, the method will become a request processing method, which will be called when the program receives the corresponding URL request.

[Example] An example of using the @RequestMapping annotation to mark a method is as follows.

package com.ssm.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

......
//Controller注解
@org.springframework.stereotype.Controller
public class AnnotationControllerTest {
    
    
    //@RequestMapping注解标注再方法上
    @RequestMapping(value="/annotationController")
    public ModelAndView handleRequest(HttpServletRequest arg0, HttpServletResponse arg1)throws Exception{
    
    
        ......
        return m;
    }

}

After using the @RequestMapping annotation, the handleRequest() method in the above code can be http://localhost:8080/chapter11/annotationControlleraccessed through the address.

(2) Mark on the class

When marked on a class, all methods in the class will be mapped to class-level requests, which means that all requests processed by the controller will be mapped to the path specified by the value attribute value.

//Controller注解
@Controller

//@RequestMapping注解标注再方法上
@RequestMapping(value = "/controll")
public class AnnotationControllerTest {
    
    
    @RequestMapping(value="/annotationController")
    public ModelAndView handleRequest(HttpServletRequest arg0, HttpServletResponse arg1)throws Exception{
    
    
        ......
        return m;
    }

}

Since the @RequestMapping annotation is added to the class, and its value attribute value is "/control", the request path of the above code method will become http://localhost:8080/chapter11/control/annotationController. If the class contains other methods, then "/control" also needs to be added to the request path of other methods.

(2) Attributes of @RequestMapping annotation

In addition to specifying the value attribute, the @RequestMapping annotation can also specify some other attributes, as shown in the table.

insert image description here
All attributes are optional, but its default attribute is value. When value is its only attribute, the attribute name can be omitted. For example, the following two annotations have the same meaning.

@RequestMapping(value="/annotationController")
@RequestMapping("/annotationController")

(3) Combined annotations

The @RequestMapping annotation and its attributes have been explained in detail above, and the combined annotation was introduced in Spring 4.3 to help simplify the mapping of commonly used HTTP methods and better express the semantics of the annotated methods. Its combined annotations are as follows.

  • @GetMapping: Matches requests in GET mode.
  • @PostMapping: Matches requests in POST mode.
  • @PutMapping: Matches PUT requests.
  • @DeleteMapping: Matches DELETE requests.
  • @PatchMapping: Match requests in PATCH mode.

Take @GetMapping as an example, the composite annotation is @RequestMapping(method=RequestMethod.GET)an abbreviation for Http Get, which maps Http Get to a specific processing method. In actual development, the traditional @RequestMapping annotation is used as follows.

@RequestMapping(value="/user/{id}",method = RequestMethod.GET)
    public String selectUserById(string id){
    
    
        ......
    }

After using the new annotation @GetMapping, the method attribute can be omitted to simplify the code. The usage is as follows.

  @GetMapping(value="/user/{fid}")
    public String selectUserById(string id){
    
    
        ......
    }

(4) The parameter type and return type of the request processing method

In the controller class, each request processing method can have multiple parameters of different types, and a return result of multiple types. The parameters of the handleRequest() method before are the two parameter types of HttpServletRequest and HttpServletResponse corresponding to the request. In addition, other parameter types can also be used. For example, if you need to access the HttpSession object in the request processing method, you can add HttpSession as a parameter, and Spring will correctly pass the object to the method. The usage example is as follows.

 @RequestMapping(value="/annotationController")
    public ModelAndView (httpSession session)
    {
    
    
        ......
        return m;
    }

In the request processing method, the parameter types that can appear are as follows.

javax.servlet.ServletRequest/javax.servlet.http.HttpServletRequest
javax.servlet.ServletResponse/javax.servlet.http.HttpServletResponse 
javax.servlet.http.HttpSession 
org.springframework.web.context.request.WebRequest或 
org.springframework.web.context.request.NativeWebRequest 
java.util.Locale
java.util.TimeZone (Java 6+)/java.time.Zoneld(on Java 8) 
java.io.InputStream/java.io.Reader 
Java.io.OutputStream/java.io.Writer 
org.springframework.http.HttpMethod 
java.security.Principal
@PathVariable@MatrixVariable@RequestParam@RequestHeader@RequestBody、 
@RequestPart@SessionAttribute@RequestAttribute注解 
HttpEntity<?> 
java.util.Map/org.springframework.ui.Model/lorg.springframework.ui.ModelMap 
org.springframework.web.servlet.mvc.support.RedirectAttributes 
org.springframework.validation.Errors/org.springframework.validation.BindingResult 
org.springframework.web.bind.support.SessionStatus 
org.springframework.web.util.UriComponentsBuilder

Notice

The org.springframework.ui.Model type is not a Servlet API type, but a Spring MVC type that contains a Map object. If the Model parameter is added to the method, Spring MVC will create a Model object every time the request processing method is called and pass it to the method as a parameter.

In the entry case, the request processing method returns a ModelAndView type of data. In addition to this type, request handler methods can return other types of data. Common method return types supported by Spring MVC are as follows.

 ModelAndView 
 Model 
 Map 
 View 
 String 
 void 
 HttpEntity<?>ResponseEntity<?> 
 Callable<?> 
  DeferredResult<?>

Among the return types listed above, the common return types are ModelAndView, String and void. Among them, Model data can be added to the ModelAndView type, and the view can be specified; the return value of the String type can jump to the view, but cannot carry data; and the void type is mainly used in asynchronous requests, it only returns data, and does not jump to the view .

Since the ModelAndView type fails to achieve decoupling between data and views, during development, the return type of the method usually uses String. Since the return value of the String type cannot carry data, how to bring the data into the view page in the method? This uses the Model parameter type explained above, through which the attributes that need to be displayed in the view can be added.

The sample code for the method that returns the String type is as follows.

 @RequestMapping(value="/annotationController")
    public String handleRequest(HttpServletRequest arg0, HttpServletResponse arg1,
                                Model model)throws Exception{
    
    
        model.addAttribute("msg","第一个Spring MVC程序");
        return "/WEB-INF/jsp/welcome.jsp";
   }

In the above method code, a parameter of Model type is added, and the required data can be added through the addAttribute() method of the parameter instance. In addition to returning the view page in the above code, the String type can also perform reset redirection and request forwarding. The specific methods are as follows.

(1) redirect reset

For example, after modifying user information, the implementation code for redirecting the request to the user query method is as follows.

@RequestMapping(value="/update")
    public String update(HttpServletRequest request, HttpServletResponse response,
                                Model model){
    
    
        //复位向请求路径
        return "redirect: queryUser";
   }

(2) forward request forwarding

For example, when the user performs a modification operation, the implementation code forwarded to the user modification page is as follows.

    @RequestMapping(value="/toEdit")
    public String toEdit(HttpServletRequest request, HttpServletResponse response,
                         Model model){
    
    
        //复位向请求路径
        return "forward: editUser";
    }

4. ViewResolver (view resolver)

The view resolver in Spring MVC is responsible for parsing the view. You can define a ViewResolver in the configuration file to configure the view resolver. The configuration example is as follows.

    <!--定义视图解析器-->
    <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--设置前缀-->
        <property name="prefix" value="/WEB-INF/jsp/" />
        <!--设置后缀-->
        <property name="suffix" value=".isp" />
    
    </bean>

In the above code, a view resolver whose id is viewResolver is defined, and the prefix and suffix properties of the view are set. After this setting, the view path defined in the method will be simplified. For example, the logical view name in the entry case only needs to be set to "welcome" instead of "/WEB-INF/jsp/welcome.jsp", and the view resolver will automatically add the prefix and suffix when accessing.

Guess you like

Origin blog.csdn.net/weixin_45627039/article/details/131258309