Section 01 – MVC ideas with Spring MVC
MVC is a software architecture pattern
- M:Model, or data Model, encapsulates and maps data, corresponding to Java Bean entity classes
- V:View, or View, a page that displays data, HTML, JSP, or FTL file
- C:Controller, which controls data processing logic and page hopping
The MVC flow is something like this
Spring MVC
Spring is one of the mainstream MVC frameworks. Spring MVC makes Java beans become controllers to handle requests through annotations, without implementing any interface, and supports THE FORM of REST-style URL, with loosely coupled pluggable component structure. More extensible and flexible than other MVC frameworks
Important Components:
- DispatcherServlet: Receives and forwards requests
- HandlerMapping: a processor mapper that finds execution class handlers on request and returns handlers to a DispatcherServlet
- HandlerAdapter: Processor adapter that executes the Handler sent by the DispatcherServlet and returns the ModelAndView to the DispatcherServlet.
- Handler: Executes the Handler method to return the ModelAndView to the HandlerAdapter, which then returns it to the DispatcherServlet
- ViewResolver: a view parser that parses the ModelAndView sent by the DispatcherServlet and returns the view
- View: render the View sent by the DispatcherServlet and return it to the DispatcherServlet and return it to the client for display
Section 02 – QuickStart
Create the Spring MVC project
Start by creating a Maven project spring-web-MVC and adding project dependencies
<properties>
<spring-version>5.3.13</spring-version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring-version}</version>
</dependency>
</dependencies>
Copy the code
Add Framework Support, add Web Framework Support, and select Create Web.xml
Open Project Structure, select Artifacts, first create a lib folder under WEB-INF, and then import the JAR packages on the right into the lib folder
Configure web. XML
<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">
<! --DispatchServlet-->
<servlet>
<servlet-name>springmvc</servlet-name>
<! The DispatcherServlet is used to intercept Http requests and invoke the corresponding Controller method according to the URL of the request to complete the processing of Http requests.
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<! --applicationContext.xml-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
<! Automatically create the Spring IOC container and initialize the DispatcherServlet on Web application startup
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<! --"/" stands for intercepting all requests,/* Intercepting all requests including JSP pages -->
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Copy the code
Create applicationContext. XML in the Resources directory and configure the package scan and view parser
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
<context:component-scan base-package="com.citi">
</context:component-scan>
<! Add /WEB-INF/pages/--> add/web-inf /pages/-->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
Copy the code
Configure Tomcat
Create a New Controller package and create the HelloController control class
@Controller
public class HelloController {
// Process the forward request
@RequestMapping("/hello")
public String hello(a){
System.out.println("In process....");
// Return to the page
//return "/WEB-INF/pages/success.jsp";
// Add a view parser to automatically concatenate the page address
return "success"; }}Copy the code
RequestMapping @requestMapping: Tell Spring MVC what request this method should handle, where the “/” can be omitted
Create a pages folder under web-INF to store the JSP files. Create a success.jsp file
<%@ page contentType="text/html; charset=UTF-8" language="java" %>
<html>
<head>
<title>Success</title>
</head>
<body>
success
</body>
</html>
Copy the code
Start Tomcat, the browser type http://localhost:8080/hello page shows success
HelloController runs the process: 1). The client (browser) clicks the link to send localhost:8080/ Hello request 2).Tomcat receives the request 3) 4). DispatchServlet checks which Controller class method of the @requestMapping annotation matches the request address. The front controller knows the target class and method and uses reflection to execute the target method 6). When the method completes execution, there is a return value that SpringMVC considers to be the page to go to 7). 8). The front-end controller forwards to the specific page according to the address
Applicationcontext.xml configuration file
The location of the configuration file is specified under the param-value tag in the web.xml configuration file. Spring MVC has a default configuration file.
Unregister the configuration file and start Tomcat
Error “Could not open ServletContext resource [/ web-INF/springmVC-servlet.xml]” the default configuration file is springmvc-servlet.xml Change the Servlet name to dispatcherServlet and start Tomcat again. You can see that the default configuration file name is the name of the dispatcherServlet Bean -servlet.xml
If you do not want to specify a configuration file, you need to configure a configuration file named [Servlet name-servlet.xml] in the WEB-INF directory. Spring MVC will automatically look for this file when Tomcat container starts and create a dispatchservlet-servlet.xml file in web-INF, Applicationcontext. XML in the resources directory. Delete applicationContext. XML and start Tomcat again
No more errors are reported and the page can be accessed normally
“/” and “/*”
The “/” of the url-parttern tag in the web.xml configuration file means to intercept all requests (excluding JSP pages), “/*” intercepts all requests including JSP pages, changes the “/” in the configuration to “/*”, restarts the container, and accesses /hello, 404 error occurs
The console reported the following error
Note “/” intercepts requests that do not include JSP pages. “/*” intercepts all requests, including JSP pages
Add index.html to the web directory, change “/*” to “/”, restart the container, and access index.html
The page cannot be accessed, the console reported an error, why?
First of all, there is a web. XML file in the conf folder of the Tomcat file, and the web. XML in the project inherits the web
In Tomcat, web. XML is equivalent to the parent class, which is configured with DefaultServlet, specifically for handling static resources. In the project, web. XML is a subclass, which is configured with “/”, which means that the subclass overwrites the parent class method. The “/” configuration of the defualtServlet in Tomcat’s web.xml is invalidated and can no longer handle HTML static resources.Default configuration class “/”
The project configured “/” not to block JSP requests to release JSPS to Tomcat, which has a JspServlet in its web.xml that handles *.jsp files
“/ * “simply blocks all requests, and “/” caters to REST-style urls
@ RequestMapping annotations
Spring MVC uses the @requestMapping annotation to indicate which URL requests xxController or methods can handle
- The @requestMapping definition provides the upper URL address for the @requestMapping URL on the method
- RequestMapping specifies the specific requests that a method can handle
Create a MappingController under the Controller package and test the @requestMapping annotation
Plus: No two methods can handle the same request, that is, no two methods must have the same value in RequestMapping
The @requestMapping annotation prefixes requests currently being processed by all methods on a class
@Controller
@RequestMapping("/mapping")
public class MappingController {
@RequestMapping("/handle")
public String handle(a){
String method = Thread.currentThread().getStackTrace()[1].getMethodName();
System.out.println(this.getClass().getSimpleName() + "Class" + method + "Method executing");
return "success"; }}Copy the code
The browser enter http://localhost:8080/mapping/handle
@requestMapping Other attributes
Method: Specifies the request method, which is null by default, meaning that any request method can handle it
Add methods to MappingController
@RequestMapping(value = "/handle_post_req", method = RequestMethod.POST)
public String handlePostReq(a){
String method = Thread.currentThread().getStackTrace()[1].getMethodName();
System.out.println(this.getClass().getSimpleName() + "Class" + method + "Method executing");
return "success";
}
Copy the code
Send a POST request as a form and add the form expression code to the body tag of the index.jsp page
<p>Send a POST request</p>
<form action="/mapping/handle_post_req" method="post">
<button type="submit">Send a POST request</button>
</form>
Copy the code
Restart Tomcat, click the button to send the POST request, and jump to the success.jsp page
Console output
And enter http://localhost:8080/mapping/handle_post_req in your browser, complains, suggests that the request does not support the GET method
Params: Specifies the request parameters
- Params is an array
- Params supports simple expressions that indicate “! , “! =”
- Params specifies that the request parameter must contain the specified name
Add code to the MappingController class
@RequestMapping(value = "/handle_params", params = {"username"})
public String handleParams(a){
String method = Thread.currentThread().getStackTrace()[1].getMethodName();
System.out.println(this.getClass().getSimpleName() + "Class" + method + "Method executing");
return "success";
}
Copy the code
Error 404 request does not carry parameters specified by paramsAdd username. The SUCCESS page is displayed
! Params indicates that the request must be modified without the params parameter
@RequestMapping(value = "/handle_params", params = {"! username"})
public String handleParams(a){
return "success";
}
Copy the code
Restart the tomcat, request to http://localhost:8080/mapping/handle_params? username=stark
Regulation parameter values, params = {” username = Peter “}, modify the code to restart Tomcat, enter http://localhost:8080/mapping/handle_params? again username=stark
The inputhttp://localhost:8080/mapping/handle_params?username=peter
You can also specify an unspecified value, such as params={“username! = Peter “}, specify multiple restrictions that must be met at the same time. Use “,” link between multiple parameters, and use “&” link between multiple parameters of URL, for example, params={“username=”stark”,password,! gender}
Headers, which specifies that the request header expression, like Params, is also an array
User-agent :Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; Rv :88.0) Gecko/20100101 Firefox/88.0 User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36
Add the code
@requestMapping (value = "/handle_headers",headers = {" user-agent =Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; The rv: 88.0) Gecko / 20100101 Firefox / 88.0 "})
public String handleHeaders(a){
return "success";
}
Copy the code
Restart Tomcat and access it in Google Chrome
Firefox
The other two attributes of @requestMapping
- Consumes: Specifies the type of content that is received
- Produces: Specifies the type of content returned by the browser
Section 03 – Fuzzy matching for @requestMapping
- ? : Supports matching one character
- * : Can match any character
- ** : Supports matching multi-layer paths
Create a New MatchController and test @requestMapping for fuzzy matching and wildcard usage
@Controller
public class MatchController {
@RequestMapping("/matc?" )
public String matchOne(a){
return "success"; }}Copy the code
“?” Match one character at a time, restart tomcat, enter http://localhost:8080/match
“?” Can represent any character, but an error is reported if more than one character is matched
* can match multiple characters
@RequestMapping("/matc*")
public String matchMore(a){
return "success";
}
Copy the code
Matches 0 or more characters
You can also match layer 1 paths
@RequestMapping("/matc*/layer")
public String matchOneLayer(a){
return "success";
}
Copy the code
“**” matches 0 or multiple layers
@RequestMapping("/match/**/layers")
public String matchMoreLayers(a){
return "success";
}
Copy the code
Section 04 – @pathVariable annotation
The @pathVariable annotation binds placeholder parameters in the URL to the input parameter of the controller’s handling method
Create a new PathVarController
@Controller
public class PathVarController {
// The path can have station characters, * is also a placeholder, but can not get the value of the variable at the position, {} can get the value of the variable
// the name of the PathVariable is specified by @pathvariable. The name of the PathVariable is consistent with the default parameter
@RequestMapping("/user/{id}")
public String userInfo(@PathVariable("id") String id){
System.out.println("The value of path parameter id is :" + id);
return "success"; }}Copy the code
Control it to print out the value of the variable in the pathCan occupy only one level of path, if you want to obtain two levels of path must define two placeholders
@RequestMapping("/user/{id}/{orderId}")
public String userInfoDetial(@PathVariable("id") String id, @PathVariable("orderId") String orderId){
System.out.println("The value of path parameter id is :" + id);
System.out.println("The path parameter orderId has the value :" + orderId);
return "success";
}
Copy the code
REST style URL
Representational State Transfer (REST) is a software architecture that is clear, standards-compliant, easy to understand, and extensible
- Resources: Resources on the network, such as text and image information, can be pointed to by a URI (Uniform resource Locator). Each resource has a specific URI and can be accessed by URI or resource
- Representation layers: Representations of resources, such as JSON format, XML format and TXT format
- State Transfer: Each request represents an interaction between the client and the server. HTTP protocol is a stateless protocol, all the states are stored in the server, the client want to operate the server, must pass some means, so that the state of the server changes, this transformation is built on the presentation layer. There are four HTTP operations: PUT, GET, POST, and DELETE