2. First MVC program
Hello,SpringMVC
2.1 configuration version
1. Create a new Moudle, springmvc-02-hello, and add web support!
2. Confirm that the dependency of spring MVC is imported!
3. Configure web.xml and register dispatcher Servlet
<?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"> <!--1.register DispatcherServlet--> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--Associate a springmvc Configuration file for:[servlet-name]-servlet.xml--> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc-servlet.xml</param-value> </init-param> <!--Startup level-1--> <load-on-startup>1</load-on-startup> </servlet> <!--/ Match all requests; (excluding.jsp)--> <!--/* Match all requests; (including.jsp)--> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
4. Write the spring MVC configuration file! Name: SpringMVC-servlet.xml: [servletname] - servlet.xml
Note that the name requirements here are in accordance with the official
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> </beans>
5. Add process mapper
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
6. Add processor adapter
<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>
7. Add view parser
<!--view resolver :DispatcherServlet Give it to him ModelAndView--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver"> <!--prefix--> <property name="prefix" value="/WEB-INF/jsp/"/> <!--suffix--> <property name="suffix" value=".jsp"/> </bean>
8. Write the business Controller that we want to operate, either implement the Controller interface or add annotations; we need to return a ModelAndView, load data and seal the view;
package com.kuang.controller; import org.springframework.web.servlet.ModelAndView;import org.springframework.web.servlet.mvc.Controller; import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse; //Note: let's import the Controller interface first public class HelloController implements Controller { public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { //ModelAndView models and views ModelAndView mv = new ModelAndView(); //Encapsulate the object and place it in ModelAndView mv.addObject("msg","HelloSpringMVC!"); //Encapsulate the view to jump to and put it in ModelAndView mv.setViewName("hello"); //: /WEB-INF/jsp/hello.jsp return mv; } }
9. Give your class to the spring IOC container and register the bean
<!--Handler--><bean id="/hello" class="com.kuang.controller.HelloController"/>
10. Write the jsp page to jump to, display the data stored in ModelandView, and our normal page;
<%@ page contentType="text/html;charset=UTF-8" language="java" %><html><head> <title>Kuangshen</title></head><body>${msg}</body></html>
11. Configure Tomcat startup test!
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-48nykbzx-163869362110) (E: \ desktop \ document \ javaweb\SpringMVC.assets\image-20211205175708225.png)]
Possible problems: visit 404, troubleshooting steps:
- Check the console output to see if there is any missing jar package.
- If the jar package exists and the display cannot be output, add lib dependency in the project release of IDEA!
- Restart Tomcat to solve the problem!
Summary: looking at this, it is estimated that most students can understand the principle, but we won't write it in actual development, otherwise we will be crazy. Why do we learn this thing? Let's look at an annotation version implementation, which is the essence of spring MVC. Just look at this figure.
2.2 annotated version
1. Create a new Moudle, springmvc-03-hello-annotation. Add web support!
2. Since Maven may have the problem of resource filtering, we will improve the configuration
<build> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> </resources> </build>
3. Introduce relevant dependencies in pom.xml file: mainly Spring framework core library, Spring MVC, servlet, JSTL, etc. we have introduced them in parent dependencies!
4. Configure web.xml
Note:
<?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"> <!--1.register servlet--> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--Specified by initialization parameters SpringMVC The location of the configuration file is associated--> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc-servlet.xml</param-value> </init-param> <!-- Start sequence: the smaller the number, the earlier the start --> <load-on-startup>1</load-on-startup> </servlet> <!--All requests will be rejected springmvc intercept --> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
/Difference from / *: < URL pattern > / < / url pattern > will not match. jsp, but only for the request we write; that is:. jsp will not enter the DispatcherServlet class of spring. < URL pattern > / * < / url pattern > will match *. jsp, and will enter the DispatcherServlet class of spring again when returning to the jsp view, resulting in no corresponding controller, so a 404 error is reported.
-
Pay attention to the version of web.xml. Keep the latest version!
-
Register DispatcherServlet
-
Associated spring MVC configuration file
-
The startup level is 1
-
The mapping path is / [do not use / *, it will 404]
5. Add Spring MVC configuration file
Add the springmvc-servlet.xml configuration file in the resource directory. The configuration form is basically similar to the Spring container configuration. In order to support annotation based IOC, the function of automatic package scanning is set. The specific configuration information 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" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- Automatically scan the package to make the annotations under the specified package effective,from IOC Unified container management --> <context:component-scan base-package="com.shuang.controller"/> <!-- Give Way Spring MVC Do not process static resources --> <mvc:default-servlet-handler /> <!-- support mvc Annotation driven stay spring Generally used in@RequestMapping Annotation to complete the mapping relationship To make@RequestMapping Note effective You must register with the context DefaultAnnotationHandlerMapping And one AnnotationMethodHandlerAdapter example These two instances are handled at the class level and method level, respectively. and annotation-driven Configuration helps us automatically complete the injection of the above two instances. --> <mvc:annotation-driven /> <!-- view resolver --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver"> <!-- prefix --> <property name="prefix" value="/WEB-INF/jsp/" /> <!-- suffix --> <property name="suffix" value=".jsp" /> </bean> </beans>
In the view parser, we store all views in the / WEB-INF / directory, which can ensure the view security, because the files in this directory cannot be accessed directly by the client.
-
Make IOC comments effective
-
Static resource filtering: HTML. JS. CSS. Pictures, videos
-
Annotation driven MVC
-
Configure view parser
6. Create Controller
Write a Java control class: com.kuang.controller.HelloController. Pay attention to the coding specification
package com.shuang.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class HelloController { //Real access address: project name / HelloController/hello @RequestMapping("/hello") public String hello(Model model){ //Encapsulate data //Add attributes msg and values to the model, which can be taken out and rendered in the JSP page model.addAttribute("msg","Hello,SpringMVCAnnotation!"); //web-inf/jsp/hello.jsp return "hello";//Will be processed by the view parser } }
-
@The Controller is used to automatically scan the Spring IOC container during initialization;
-
@RequestMapping is to map the request path. Here, because there are mappings on classes and methods, the access should be / HelloController/hello;
-
The purpose of declaring Model type parameters in the method is to bring the data in the Action to the view;
-
The result returned by the method is the name of the view Hello, plus the prefix and suffix in the configuration file to become WEB-INF/jsp/hello.jsp.
7. Create view layer
Create hello.jsp in the WEB-INF/ jsp directory. The view can directly take out and display the information brought back from the Controller;
The value or object stored in the Model can be retrieved through EL representation;
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>SpringMVC</title> </head> <body> ${msg} </body> </html>
8. Configure Tomcat run
Configure Tomcat, start the server and access the corresponding request path!
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-vgguz7si-163869362112) (E: \ desktop \ document \ JavaWeb \ springmvc. Assets \ image-202112051758170. PNG)]
OK, run successfully!
2.3 summary
The implementation steps are actually very simple:
- Create a new web project
- Import related jar packages
- Write web.xml and register DispatcherServlet
- Writing spring MVC configuration files
- The next step is to create the corresponding control class, controller
- Finally, improve the correspondence between the front-end view and the controller
- Test run commissioning
Three major components that must be configured to use spring MVC:
Processor mapper, processor adapter, view parser
Usually, we only need to manually configure the view parser, while the processor mapper and processor adapter only need to turn on the annotation driver, eliminating a large section of xml configuration
Let's review the principle~
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-uijjb4lw-163869362112) (E: \ desktop \ document \ javaweb\SpringMVC.assets\image-20211205175858987.png)]
Spring MVC execution principle
- DispatcherServlet represents the front controller and is the control center of the whole spring MVC. When the user sends a request, the DispatcherServlet receives the request and intercepts the request.
- We assume that the requested url is: http://localhost:8080/SpringMVC/hello ·
- As above, the url is divided into three parts:
- http://localhost:8080 Server domain name
- Spring MVC is a web site deployed on the server. hello represents the controller
- Through analysis, the above url is expressed as: request the hello controller of the spring MVC site located on the server localhost:8080.
- HandlerMapping is processor mapping. Dispatcher servlet call
- HandlerMapping,HandlerMapping finds HandIxr according to the request url.
- HandlerExecution refers to a specific Handler. Its main function is to find the controller according to the url. The controller found by the url above is: hello.
- HandlerExecution passes the parsed information to DispatcherServlet, such as parsing controller mapping. The HandlerAdapter represents a processor adapter that executes the Handler according to specific rules.
- The Handler lets the specific Controller execute.
- The Controller returns the specific execution information to the HandlerAdapter, such as ModelAndView. The HandlerAdapter passes the view logical name or model to the dispatcher servlet.
- DispatcherServlet calls the view resolver to resolve the logical view name passed by the HandlerAdapter.
The view parser passes the parsed logical view name to the dispatcher servlet.
1-4 servlet-mapping
5-8 servlet
10-12 servlet request forwarding and redirection
This article comes from Bili Bili Madness theory Study notes