Spring MVC learning record: annotation learning of spring MVC

Since you want to learn spring, you need to learn annotations. Spring MVC also has corresponding annotations.

1, Spring MVC common annotations.

(1) Annotation of binding url

① @ RequestMapping can be used in classes or methods

Attribute: value/path: indicates the binding url

method: the default value is GET/POST. The default value is a collection: RequestMethod []

② @ ResponseBody @ can be used on a class to indicate that all methods in the class return JSON data, or it can be used on a method to indicate that this method returns JSON data

Use case:

springmvc.xml configuration:

<?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:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">


    <!--Configure processor
       Processor based bean of name As requested by the processor url
    -->
    <bean name="/user.do" class="com.fs.controller.UserHandler"/>
    <!--Configure processor mapper-->
    <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>

    <!--Configure processor adapter
       class:
        method public boolean supports(Object handler) {
                return handler instanceof Controller;
            }
           SimpleControllerHandlerAdapter: Can only handle implementations Controller Interface processor
    -->
    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>

    <!--If the front and back of the view parser are separated, There is no need to configure the view parser-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- Logical view name: user:
           prefix +Logical view name+suffix
           WEB-INF/jsp/user.jsp
         -->
        <!--prefix: prefix-->
        <property name="prefix" value="WEB-INF/jsp/"></property>
        <!--suffix: suffix-->
        <property name="suffix" value=".html"></property>
    </bean>

    <!--Open annotated processor adapter annotated processor mapper-->
    <mvc:annotation-driven/>
    <mvc:default-servlet-handler/>
    <context:component-scan base-package="com.fs.controller"/>

</bean>

Import dependency:

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
    </dependency>

    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>1.7.25</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
    </dependency>

    <!--Servlet-api-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.0.1</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.1</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.11.4</version>
    </dependency>
  </dependencies>

  <build>
    <finalName>springmvc-helloworld</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>

Configure web xml:

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <!--Global initialization parameters-->
  <!--   <context-param>
         <param-name></param-name>
         <param-value></param-value>
     </context-param>-->
  <!--Configure front-end controller
      When starting,Create a springmvc container(spring)
       Default loaded profile: Default profile: WEB-INF/{servlet-name}.xml      WEB-INF/springmvc.xml

       springmvc Creation timing: At the first request
         Set this Servlet(DispatcherServlet) Created at server startup:
           to configure: load-on-startup   The smaller the non negative integer number, Start first

  -->
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!--Servlet Initialization parameters for, Only in this Servlet obtain-->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <!--Requested path
        1)    /*  Wrong writing, because, /* All requests go through the front-end controller, Via front end controller, according to url Find processor
                        jsp page.Via front end controller, query jsp of url Processor for, I can't find it, Error reporting processor not found
        2)  /   Restfull Style writing, All requests go through the front-end controller,divide.jsp Ending url, Static resources(css,js,html,picture..)
                      Via front end controller, according to url Find processor, Static resources need to be filtered later
        3) *.do/*.action       with.do perhaps.action Ending url Through front-end control
        -->

    <url-pattern>/</url-pattern>
  </servlet-mapping>

</web-app>

Write a test class Controller:

If @ RequestMapping("/a") is added to the class, then @ RequestMapping("/test1") is added to the method

The path to access this port is: localhost:xxxx/a/test1

@Controller
//You can not write, so you only need to access the RequestMapping path on the method
//@RequestMapping("/user")
public class test{
    //Only get methods are processed
    @GetMapping("/test1")
    @ResponseBody
    public User test1(){
        User user = new User();
        user.setUsername("admin");
        user.setPassword("123456");
        return user;
    }

}

Then we go to the access port test:

JSON data returned after successful access

The binding url also has other annotations, but it is also based on @ RequestMapping():

@ PostMapping("/test1") post request
@ GetMapping("/test1") get request
@ DeleteMapping("/test1") delete request
@ PutMapping("/test1") put request
@ PatchMapping("/test1") patch request

(II) transmission of parameters

If the test1 method needs to pass in the parameters String username and String password:

    @GetMapping("/test1")
    @ResponseBody
    public User test1(String username,String password){
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        return user;
    }

There are two situations for accepting parameters:

① When the parameter name passed in by the current end is consistent with the parameter name received by the back end:

Spring MVC will automatically match the parameter name matched by the back end according to the parameter name passed in by the front end

② When the parameter name passed in by the current end is inconsistent with the parameter name received by the back end:

Then we need to use an annotation: @ RequestParam()

This annotation has three common parameters:

1) Name: request parameter name, which maps the specified request parameter name to the formal parameter
2) required: default value: true = required. If true, it means necessary. If the front end does not pass the parameter: Throw: 400 if false, it is not necessary. If the front end does not pass the data, the parameter value is null.
3) defaultValue: default value

For example, the parameter name used by our back-end is "username", but the parameter name passed in by our mapped front-end is "name"

    @GetMapping("/test1")
    @ResponseBody
    public User test1(@RequestParam("name") String username, String password){
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        return user;
    }

Then we modify the parameter passed in from the front end to name:

③ Similarly, spring MVC will automatically map the parameter names in the entity class according to the parameter names passed in from the front end:

For example, I regard the User object as the received parameter:

@Data
public class User {
    private String username;
    private String password;
}
    @GetMapping("/test1")
    @ResponseBody
    public User test1(User user){
        return user;
    }

Then, the front end passes in the parameters username and password. The result is:

④@PathVariabl()

It is used to map the template variables in the request URL to the parameters of the function processing method, that is, take the variables in the uri template as parameters. For example:

 @RequestMapping(value="/test1/username/{username}/password/{password}",method = RequestMethod.GET)  
     public String getLogin(@PathVariable("username") String username,  
         @PathVariable("password") String password){  
         User user = new User();
         user.setUsername(username);
         user.setPassword(password);
         return user;  
     }  

⑤@CookieValue

Function: used to obtain the value in the Cookie;

Parameter: Value: parameter name; required: required; defaultValue: default value

@RequestMapping("/test")
    public String testCookieValue(@CookieValue("username") String username) {
        return username;
    }

⑥@SessionAttributes

@ SessionAttributes puts the value in the session scope and writes it on the top of class.   

@ SessionAttributes in addition to specifying the attributes to be placed in the session through the attribute name (value attribute value),

You can also specify which model attributes need to be placed in the session (types attribute value) through the object type of model attributes, for example:

@SessionAttributes(value = {"user"}, types = {String.class})
@Controller
public class test{
    
     //@SessionAttributes
     //In addition to specifying the attribute to be placed in the session through the attribute name (value attribute value),
     //You can also specify which model attributes need to be placed in the session through the object type of the model attribute (the value of the types attribute).
     //Note: this annotation can only be placed on the class, not on the method
    @RequestMapping("/test1")
    public String test(Map<String, Object> map) {
        User user = new User("username","password");
        map.put("user", user);
        map.put("test", "Chongqing");
        return "success";
    }
}

So the common annotations of spring MVC are over here. Of course, this is not over yet. Spring MVC also provides a lot of annotations, so interested partners can go to the official documents for query!

Keywords: Java Spring Back-end

Added by ysu on Fri, 10 Dec 2021 17:08:03 +0200