1. The role of SpringMVC framework
MVC = Model (data Model) + View (View) + Controller (Controller). The idea of MVC is that each project should have at least three core roles, which are used to deal with different problems. Among them, Model represents data processing, such as adding, deleting, modifying and checking data. View represents the interface of the software, and Controller represents the Controller, which is used to receive requests submitted by the client to the server and provide the client with response results after processing the requests.
This thinking may vary in different technical areas, for example in some client software development, MVP, MVVP, etc.
The SpringMVC framework is based on the Spring framework, so in SpringMVC, the functions of the Spring framework are used, such as creating objects and managing objects through the Spring framework, and some annotations in the Spring framework are also used.
The SpringMVC framework mainly solves the problem of V-C interaction, namely: After the client submits the request to the server, it must be the server side controller to receive the request, SpringMVC solved the problem of how to receive the request (including the parameters in the request, etc.), when the server is finished processing the request, should give the client the response result, SpringMVC also solved the problem of how to respond! In fact, SpringMVC framework has nothing to do with “M” at all, so in the learning process of SpringMVC, data addition, deletion, modification and checking related database technology are not considered at all.
2. Why use the SpringMVC framework
…
3. SpringMVC HelloWorld
[Case Objective]
After writing the project, run the project, open a browser, and type http://localhost:8080/ project name /hello.do to see what you expect to see displayed.
[Preparation]
Find the Servers panel in Eclipse, and if Tomcat is not currently configured, click the link in that panel to start adding Tomcat!
If the Servers panel is not shown in Eclipse, open it by clicking the ShowView Other option on the Window menu and typing Servers in the pop-up dialog.
In the dialog box for adding Tomcat, select the Tomcat version in combination with the existing Tomcat version on the machine. Then, browse to the Tomcat folder on the machine in the second interface of the dialog box to complete the configuration.
After the configuration is complete, Tomcat will appear in the Servers panel, and a project named Servers will also appear in the project list. This project represents the configuration of Tomcat. Tomcat must be on during use, if closed, Tomcat will not start!
【 Create a project 】
To Create a new Maven Project, select Create a simple Project, set Group Id to cn.tedu, Artifact Id to Springmvc01, and Packaging must select WAR.
If the project you are creating is a client project, launched through the main() method of a class, you should select JAR; If you are creating a server-side project that needs to run on Tomcat, select WAR.
In Eclipse, war projects created by default report errors because the web.xml file is missing from the project, but war projects don’t necessarily need that file! You can add the following configuration in pom.xml:
<properties>
<failOnMissingWebXml>false</failOnMissingWebXml>
</properties>
Copy the code
Of course, the above configuration can also be combined with the configuration of the development and compilation version as follows:
<properties>
<failOnMissingWebXml>false</failOnMissingWebXml>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
Copy the code
And, go ahead and add the spring-webMVC dependency to pop.xml:
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.5. RELEASE</version>
</dependency>
</dependencies>
Copy the code
Finally, right-click the project point and select Properties. In the pop-up project Properties dialog box, select Targeted Runtimes on the left and Tomcat on the right.
Using the SpringMVC framework to handle requests
First, create the cn.tedu.spring package in the project to store related files.
Then, define a class (class name can be customized), inherited from AbstractAnnotationConfigDispatcherServletInitializer class:
package cn.tedu.spring;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class SpringMvcInitializer extends
AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protectedClass<? >[] getRootConfigClasses() {// TODO Auto-generated method stub
return null;
}
@Override
protectedClass<? >[] getServletConfigClasses() {// TODO Auto-generated method stub
return null;
}
@Override
protected String[] getServletMappings() {
// TODO Auto-generated method stub
return null; }}Copy the code
Since AbstractAnnotationConfigDispatcherServletInitializer is an abstract class, so, inheritance, need to rewrite the three abstract methods:
getRootConfigClasses()
In a simple SpringMVC project, where you may not need to write any Spring environment configuration, this method returnsnull
Later, if you integrate MyBatis framework or other frameworks, you may need to write relevant configurations;getServletConfigClasses()
: Gets the SpringMVC configuration class, which can be customized and must be implementedWebMvcConfigurer
Interface;getServletMappings()
: gets the path to the request being processed by the framework, assuming all the.do
Requests with the suffix need to be processed by the SpringMVC framework, which can be configured as*.do
.
For example, the above method could be rewritten as:
package cn.tedu.spring;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class SpringMvcInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protectedClass<? >[] getRootConfigClasses() {return null;
}
@Override
protectedClass<? >[] getServletConfigClasses() {return new Class[] { SpringMvcConfigurer.class };
}
@Override
protected String[] getServletMappings() {
return new String[] { "*.do"}; }}Copy the code
The SpringMvcInitializer class above works just like web.xml does! For example, later, when a Filter component is needed in a project, you can add configuration to this class as well!
Next, configure the component scan before the declaration of the SpringMVC configuration class SpringMvcConfigurer:
package cn.tedu.spring;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@ComponentScan("cn.tedu.spring")
public class SpringMvcConfigurer implements WebMvcConfigurer {}Copy the code
Note: In a SpringMVC project, component scanning must be configured before the SpringMVC configuration class, not just before the Spring configuration class!
In native Java EE technology, the controller class is a custom Servlet class that needs to be inherited from HttpServlet! In the SpringMVC project, the controller class does not need to inherit from a specific class or implement any interface, except that:
- Must be placed in the package scanned by the component;
- You must add
@Controller
Annotation.
If you need the SpringMVC framework to handle a request for a path, you need to customize the method in the controller class, and then write code inside the method to handle it.
- Before the method declaration
@RequestMapping
Annotations to configure which path requests to process; - You should use
public
Permissions; - The return value type is used temporarily
String
Type; - The name of the method can be customized;
- The argument list for the method is temporarily empty.
For example, it could be designed as:
package cn.tedu.spring;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HelloController {
// http://localhost:8080/springmvc01/hello.do
@RequestMapping("hello.do")
public String hello(a) {
System.out.println("HelloController.hello()");
return ""; }}Copy the code
Finish to the above steps, the project can be deployed to Tomcat, start Tomcat, after input test http://localhost:8080/springmvc01/hello.do in the browser, the browser should prompt a 404 error, however, In the Eclipse console, you should see the output statement from the hello() method above!
Finally, if you want to be able to output custom content to the browser after a visit, you can add the @responseBody annotation before the method declaration and write the desired content back into the string returned by hello(). Such as:
package cn.tedu.spring;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class HelloController {
@RequestMapping("hello.do")
@ResponseBody
public String hello(a) {
System.out.println("HelloController.hello()");
return "<font color=red>Hello</font>, <font color=blue>SpringMVC</font>!!!"; }}Copy the code