Spring MVC learning notes

Spring MVC learning notes

Spring MVC overview

Spring MVC is also called Spring web mvc. It is a built-in MVC framework in spring. In spring 3 Publish after 0. SpringMVC

The framework solves the common problems in WEB Development (parameter receiving, file uploading, form verification, etc.), and is simple to use and has no difference from Spring

Seam integration. Support RESTful style URL requests. The loose coupling pluggable component structure is adopted, which is more scalable than other MVC frameworks

And flexibility.

Spring MVC principle

Before using spring MVC, we used servlets for Web development. However, when using Servlet development to receive request parameters,

Data sharing, page Jump and other operations are relatively complex. servlet is the standard for web development in java, since spring MVC is right

Servlet encapsulation, so it is obvious that the bottom layer of spring MVC is servlet, and spring MVC is deep encapsulation of servlet

Pack.

Spring MVC benefits

1. Based on MVC architecture, the functional division is clear. Solve the separation of page code and background code.

2. Easy to use. Spring MVC is also lightweight, and the jar is very small. An annotated can be developed without relying on specific interfaces and classes

Spring MVC project.

3. As part of the Spring framework, you can use Spring's IoC and AOP. It is convenient to integrate mybatis, hibernate, JPA, etc

Other frameworks.

4. Spring MVC annotations are powerful and easy to use.

MVC mode review

Model 1: jsp+javabean model - embed a lot of java code in jsp pages

Model 2: jsp+servlet+javabean model - the jsp page sends the request to the servlet, the servlet calls the javabean, and then the servlet responds to the user with the jsp page.

Model 2 is generally the current MVC mode, which we have been using.

Model view controller: Model View Controller

Model: JavaBeans in the model layer are responsible for data access and business processing

View: View JSP technology is responsible for collecting and displaying data

Controller: controller servlet Technology Intermediate scheduling

Operation of controller:

1. Accept the client's request (including the data carried in the request)

2. Process request: call the business logic in the model layer in the background

3. Page navigation: response after processing: JSP page

Getting started - steps

1 create maven project

2 pom. Add dependencies and plug-ins to XML files

<!--web project--> <packaging>war</packaging> <dependencies> <!--spring-webmvc rely on--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.2.13.RELEASE</version> </dependency> <!--springmvc Bottom or servlet,So you must add serlvet rely on--> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope><!--When the plug-in runs without scope, the plug-in will fail to start--> </dependency> </dependencies> <build> <plugins> <!-- Coding and compiling JDK edition -->
    <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.0</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <!--tomcat plug-in unit--> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <configuration> <path>/</path> <port>8080</port> </configuration> </plugin> </plugins> </build>

3 Create Spring and Spring MVC configuration files

We generally register all beans except the Controller in the Spring container, and register the Controller in the Spring container

Spring MVC container. So we add ApplicationContext. In the resources directory XML as spring configuration,

Add spring MVC XML as the configuration file of spring MVC.

3.1 create Spring configuration file ApplicationContext XML file

<?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 "> <! -- spring configuration file: all bean objects except the controller are scanned here -- > < context: component scan base package =" com kkb. dao,com. kkb. service"/> </beans>

3.2 create the spring MVC configuration file xml

<?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   http://www.springframework.org/schema/context/spring-context.xsd   http://www.springframework.org/schema/mvc   http://www.springframework.org/schema/mvc/spring-mvc.xsd "> <! -- springmvc configuration file: the bean objects of the controller are scanned here -- > < context: component scan base package =" com kkb. controller"/> </beans>

4 on the web Spring and spring MVC configuration in XML

<!--spring Configuration of--> <context-param> <!--contextConfigLocation: Indicates that it is used for loading Bean Configuration file for--> <param-name>contextConfigLocation</param-name> <!--appoint spring Location of the configuration file. This configuration file also has some default rules. Its configuration file name is called by default applicationContext.xml , If you put this configuration file in WEB-INF Directory, you don't need to specify the location of the configuration file, just specify the listener. This configuration is Spring integrate Web General configuration of environment; It is generally used to load the controller layer Bean(as dao,service Etc.) to facilitate communication with any other Web Framework integration. --> <param-value>classpath:applicationContext.xml</param-value> </context-param> <listener> <listener- class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!--SpringMVC Configuration of--> <!--Front end controller: all requests will pass through this controller and then be distributed to each sub controller through this controller. The front-end controller is essentially a Servlet,because SpringMVC The bottom layer is to use Servlet Written --> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet- class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- Read when creating front-end controller springmvc Profile startup ioc container --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <!-- Tomcat Create this object at startup --> <load-on-startup>1</load-on-startup> </servlet> <!-- Configure interception path url,All with.do The end requests will be intercepted and processed by the front-end controller --> <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <!-- SpringMVC Configuration resolution of: 1 servlet-class: Fully qualified name of the front-end controller, in spring-webmvc-5.2.5.RELEASE.jar In package org.springframework.web.servlet Lower 2 load-on-startup: Whether the tag is in Web Server (here is Tomcat)This is created at startup Servlet Instance, i.e. whether or not Web Call to execute this when the server starts Servlet of init()Method instead of creating it when it is actually accessed. The value is required to be an integer. A value greater than 0 means that the container loads and initializes the at startup servlet,The smaller the value, the smaller the value Servlet The higher the priority of is, the earlier it is created. If the value is less than 0 or omitted, it indicates that Servlet Only when it is actually used will it be created. The value is the same: the container will select the creation order 3 url-pattern: Can be written as / ,Can be written as*.do ,*.action,*.mvc And so on. Write here first*.do,The differences between different writing methods will be introduced later. 4, init-param: Expressed springmvc Name and location of the configuration file. If there is no configuration, the default is in the project WEB-INF Directory with name Servlet name-servlet.xml Configuration file for. If there is no configuration, the default rule is enabled: that is, if the configuration file is placed in the webapp/WEB-INF/ Directory, and the name of the configuration file is equal to DispatcherServlet Name of+ -servlet(That is, the configuration file path here is webapp/WEB- INF/dispatcherServlet-servlet.xml),If so, there is no need to add init-param Parameter, i.e. no manual configuration springmvc The framework will be loaded automatically. In general, the configuration file is placed under the class path, that is resources Directory. Therefore, when registering the front-end controller, you also need to set the lookup SpringMVC Configuration file path. among contextConfigLocation Properties: from DispatcherServlet Parent class of FrameworkServlet, In this class contextConfigLocation Property is used to configure springmvc The path and name of the. -->

5 create controller

package com.kkb.controller; import com.kkb.service.TeamService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; /*** ClassName: TeamController ** @author wanglina * @version 1.0 */ @Controller public class TeamController { @Autowired private TeamService teamService; @RequestMapping("hello.do") public ModelAndView add(){ System.out.println("TeamController----add---"); teamService.add(); ModelAndView mv=new ModelAndView();mv.addObject("teamName","Lakers");//Equivalent to request Setattrubuite ("teanname", "Lakers"); mv.setViewName("index");// In the future, it will be processed by the view parser of spring MVC and converted into a physical resource path, which is equivalent to request getRequestDispatcher("index.jsp"). forward(); // After being processed by the InternalResourceViewResolver object, the prefix is added to change to / JSP / index jsp return mv; } }
package com.kkb.service; import org.springframework.stereotype.Service; @Service public class TeamService { public void add(){ System.out.println("TeamService---- add-----"); } }

6 configure view parser

In spring MVC Add the configuration of the view parser to the XML configuration file

<!--view resolver --> <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/"></property> <property name="suffix" value=".jsp"></property> </bean> <mvc:annotation-driven/> <!--annotation-driven It is a short form, which can also be manually configured instead. The short form allows beginners to quickly apply the default configuration scheme. The annotation is automatically registered DefaultAnnotationHandlerMapping And AnnotationMethodHandlerAdapter Two bean,yes springMVC by@Controller Necessary to distribute user requests, solved@Controller Precondition configuration for annotation use. It also provides data binding support,@NumberFormatannotation support,@DateTimeFormat support,@Valid Support, read and write XML Support of( JAXB,Reading and writing JSON Support of( Jackson). We process the response ajax When requested, the json Support for (after configuration, added jackson of core and mapper After the package is, it can be automatically converted into a configuration file without writing a configuration file json).  -->

7. Compile index JSP page

Create a folder jsp under the webapp folder, and then add index.jsp to the jsp folder jsp page

8 test

9 analysis

When Spring and Spring MVC appear at the same time, there will be two containers in our project. One is the Spring container and the other is the Spring MVC container. The Spring container is loaded through the ContextLoaderListener and the Spring MVC container is loaded through the dispatcher servlet. The two containers are different

Keywords: Java Spring MVC

Added by dotnotwhat on Sun, 16 Jan 2022 06:45:30 +0200