(Java) SpringMVC study notes (2)

foreword

Continue to learn the SpringMVC video tutorial , and strive to complete the set goals in the next three days

SpringMVC framework construction

This step took me all morning, and I reported a 404 error. I had no choice but to create the project from scratch . point, resulting in an explosion )

When studying, you must maintain an open-minded attitude of asking for advice, and don't aim too high

The first step is to create a project

insert image description here
insert image description here
insert image description here
insert image description here
insert image description here
insert image description here
insert image description here

The second step pom.xml file configuration

Modify the packaging method ==>war

Introduce related dependencies
insert image description here
insert image description here

The complete source code is as follows

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.atguigu.mvc</groupId>
    <artifactId>springMVC-demo1</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <dependencies>
        <!-- SpringMVC -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.1</version>
        </dependency>

        <!-- 日志 -->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.3</version>
        </dependency>

        <!-- ServletAPI -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>

        <!-- Spring5Thymeleaf整合包 -->
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring5</artifactId>
            <version>3.0.12.RELEASE</version>
        </dependency>
    </dependencies>


</project>

The third step web.xml file configuration

Create a webapp under src/mainthe directory, pay attention to whether there is a blue dot

insert image description here
insert image description here

The default location of the SpringMVC core configuration file is under WEB-INF, and the default name is the value of the servlet-name tag - servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    
    <!-- 注册前端控制器DispatcherServlet -->
    <servlet>
        <servlet-name>DispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <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>DispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

The fourth step is SpringMVC core configuration file configuration

The browser sends a request to the server through the view (html file). If the request path matches the value of the annotation @RequestMapping, the annotated method is the method for processing the request. After processing, it returns a String string, which is the view name

insert image description here

<?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.xsd
                          http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd" >


    <!-- 自动扫描包 -->
    <context:component-scan base-package="com.atguigu.mvc.controller"/>

    <!-- 配置Thymeleaf视图解析器 -->
    <bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
        <property name="order" value="1"/>
        <property name="characterEncoding" value="UTF-8"/>
        <property name="templateEngine">
            <bean class="org.thymeleaf.spring5.SpringTemplateEngine">
                <property name="templateResolver">
                    <bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">

                        <!-- 视图前缀 -->
                        <property name="prefix" value="/WEB-INF/templates/"/>

                        <!-- 视图后缀 -->
                        <property name="suffix" value=".html"/>
                        <property name="templateMode" value="HTML5"/>
                        <property name="characterEncoding" value="UTF-8" />
                    </bean>
                </property>
            </bean>
        </property>
    </bean>


</beans>

The fifth step is to test whether the construction is successful

insert image description here
insert image description here
insert image description here
insert image description here
insert image description here
insert image description here
insert image description here

Precautions

The following three points must be paid attention to:
import depends on
web.xml configuration
core file configuration

I made /WEB-INF/templates/a mistake in the path of the core configuration file. There should be other mistakes. In short, novices should be modest and cautious
insert image description here

@RequestMapping annotation

Function of @RequestMapping annotation

As you can see from the annotation name, the function of the @RequestMapping annotation is to associate the request with the controller method that processes the request and establish a mapping relationship

When SpringMVC receives the specified request, it will find the corresponding controller method in the mapping relationship to process the request

Note: It must be guaranteed that the request address processed by RequestMapping is unique

insert image description here

Location of @RequestMapping annotation

insert image description here

@RequestMapping represents a class: set the initial information of the request path of the mapping request
@RequestMapping identifies a method: set the specific information of the request path of the mapping request

package com.atguigu.mvc.controller;

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

@Controller
@RequestMapping("/test")
public class RequestMappingController {
    
    
	
	//此时请求映射所映射的请求的请求路径为:/test/testRequestMapping
    @RequestMapping("/testRequestMapping")
    public String success(){
    
    
        return "success";
    }
}

insert image description here
insert image description here

thymeleaf automatically @{}configures the context path for curly braces

The browser resolves /to an absolute path, which is http://localhost:8080/

insert image description here
insert image description here
insert image description here
insert image description here

Practical scene

Because the value in RequestMapping cannot be the same, otherwise the request path is the same, and the processing methods will conflict

The solution is to change the request path. At this time, the value in RequestMapping is the same.

For example, there are user modules and order modules, both of which have lists, and the requests are absolute paths plus listparameters

then there will be a conflict

diagram

user ====> list
order ====> list

solution

user ===> /user/list
order ===> /order/list

Add a layer of directory to the request through the @RequestMapping identification class to distinguish different businesses

The @RequestMapping identification class usually handles the method identified by the value attribute value of the same @RequestMapping in the controllers of different modules

The value attribute in @RequestMapping

The value attribute of the @RequestMapping annotation matches the request mapping through the request address of the request

The value attribute of the @RequestMapping annotation is an array of string types , indicating that the request mapping can match requests corresponding to multiple request addresses

The value attribute of the @RequestMapping annotation must be set , at least matching the request mapping through the request address

insert image description here
insert image description here
insert image description here
insert image description here
insert image description here

The method attribute of @RequestMapping

The method attribute of the @RequestMapping annotation matches the request mapping by the request method (get or post) of the request

The method attribute of the @RequestMapping annotation is an array of RequestMapping types , indicating that the request mapping can match requests in multiple request modes

If the request address of the current request satisfies the value attribute of the request mapping, but the request method does not satisfy the method attribute, the browser will report a 405 errorRequest method 'POST' not supported

get request is generally used to obtain data (it can also be used to submit data, but usually used to obtain data)
post request is generally used to submit data
reason

Get will put the request parameters in the url (request path), which has poor privacy and security, and the length of the request data is limited, but the transmission speed is fast. The post request has no length limit, and the request
data is placed in the request body

When the method attribute value is not set, the request mapping is not matched based on the request method
insert image description here
insert image description here

When the value of the method attribute is set RequestMethod=GET, the request method does not match, and a 405 error is reported
insert image description here
insert image description here

When the method attribute value is set RequestMethod.GET,RequestMethod.POSTto match the POST request
insert image description here

insert image description here

1. For controller methods that process specified request methods, SpringMVC provides @RequestMapping derived annotations

  • Mapping that handles get requests —> @GetMapping
  • Mapping for processing post requests —> @PostMapping
  • Mapping that handles put requests —> @PutMapping
  • Mapping for processing delete requests —> @DeleteMapping

example show
insert image description here
insert image description here

2. Commonly used request methods are get, post, put, delete

  • At that time, the current browser only supported get and post. If a string of other request methods (put or delete) was set for the method when the form was submitted, it would be processed according to the default request method get
  • To send put and delete requests, you need to pass the filter HiddenHttpMethodFilter provided by spring, which will be mentioned in the restful section

insert image description here

insert image description here

The params attribute of @RequestMapping

The params attribute of the @RequestMapping annotation matches the request mapping through the request parameters of the request

The params attribute of the @RequestMapping annotation is an array of string types, and the matching relationship between request parameters and request mapping can be set through four expressions

  • "param": The request that the request mapping matches必须携带param请求参数
  • "!param": Requests that the request mapping matches必须不能携带param请求参数
  • "param=value": The request matched by the request mapping must carry the param request parameter and the parameter value is value
  • "param!=value": The request matched by the request mapping must carry the param request parameter and the parameter value cannot be value

The example is as follows

insert image description here
insert image description here
insert image description here
insert image description here
insert image description here
insert image description here
insert image description here

insert image description here
insert image description here
insert image description here
insert image description here
insert image description here
insert image description here
insert image description here

headers attribute of @RequestMapping

  • The headers attribute of the @RequestMapping annotation matches the request mapping through the request header information.
    The headers attribute of the @RequestMapping annotation is an array of string types. The matching relationship between the request header information and the request mapping can be set through four expressions
    "header": Requirements The request matched by the request mapping must carry the header request header information
    "!header": it is required that the request matched by the request mapping must not carry the header request header information
    "header=value": the request matched by the request mapping must carry the header request header information And the value is value
    "header!=value": The request matched by the request mapping must carry header request header information and the value is not value
  • If the current request satisfies the value and method attributes of the @RequestMapping annotation, but does not satisfy the headers attribute, the page displays a 404 error, that is, the resource is not found

example
insert image description here

insert image description here
insert image description here

summary

  • After the request, the page responds with a 400 error, focusing on the request parameters in the request
  • After the request, the page responds with a 404 error, focusing on the request header and request path in the request
  • After the request, the page responds with a 405 error, focusing on the method of sending the request

Ant-style paths

Spring MVC supports Ant-style URL path mapping. The so-called Ant style is actually a wildcard style . Wildcards can be used in the processor mapping path to associate the accessed URL paths.

?: represents any single character

insert image description here
insert image description here
insert image description here
insert image description here
insert image description here
insert image description here
insert image description here
insert image description here

/In the URL, it represents the path separator and ?the parameter splicing character. It is said to represent any single, first single, and then add quotation marks arbitrarily

*: Indicates any 0 or more characters

insert image description here
insert image description here

insert image description here

**: Indicates any one or more layers of directories

insert image description here
insert image description here
insert image description here
insert image description here
insert image description here
insert image description here
insert image description here

Note: When using, only /**/xxx can be used

SpringMVC supports placeholders in the path (emphasis)

In addition to supporting Ant-style URL path mapping, Spring MVC also supports RESTful-style path mapping

Original method: /deleteUser?id=1

Rest method: /deleteUser/1

The placeholders in the SpringMVC path are often used in the restful style, and some data is transmitted to the server through the path in the request path

You can use the placeholder (xxx) to represent the transmitted data in the value attribute of the corresponding @RequestMapping annotation, and assign the data represented by the placeholder to the formal parameter of the controller method through the @PathVariable annotation

Example comprehension:

insert image description here
insert image description here
insert image description here
insert image description here
insert image description here

Obtaining the value corresponding to the placeholder is relatively simple, which is to bind the value represented by the placeholder and the formal parameter through the @PathVaribale annotation, that is, assign the data represented by the placeholder to the controller parameter

The placeholder must match the value, the relationship between the two is similar to the relationship between name and value

Brief description: Through the key-value mapping relationship, use the key to obtain the value, and then bind the key to the formal parameter, so that when the key has its corresponding value, it will be passed to the formal parameter, that is, the controller (server side)

  • In the RESTful style, the four verbs of GET, POST, PUT and DELETE correspond to four basic request operations in the HTTP request, as follows:
  • GET: used to obtain resources
  • POST: used to create new resources
  • PUT: used to update resources
  • DELETE: used to delete resources

summary

In this part, the biggest problem encountered was when building Spring MVC, which was fortunately solved.

Then there is the learning and mastering of some knowledge points. Generally speaking, it is not too difficult whether it is understanding or practice.

Follow Shang Silicon Valley to learn Spring MVC, you have to cheer up, before learning mybatis and spring are 1.5 times faster, learning Spring MVC is a little newer and the video does not contain subtitles, and Mr. Yang has no pee in the whole process, so even if the original double speed, you can Let's get together and learn~

Guess you like

Origin blog.csdn.net/lion_no_back/article/details/128308852