My first Spring MVC program

1. Let me briefly talk about the concept of SpringMVC :

  • Spring MVC is a lightweight web framework based on the MVC design pattern provided by Spring for the presentation layer. It is currently one of the most mainstream MVC frameworks. It is the same as the Struts2 framework and belongs to the MVC framework, but its usage and performance are more excellent than Struts2.

2. Spring MVC has the following characteristics :

  1. It is part of the Spring framework and can easily utilize other functions provided by Spring.
  2. It is flexible and easy to integrate with other frameworks.
  3. Provides a front controller DispatcherServlet, so that developers do not need to develop additional controller objects.
  4. Can automatically bind user input, and can convert the data type correctly.
  5. A common validator is built-in, which can validate user input. If the verification fails, it will be redirected to the input form.
  6. Support multiple view technologies. It supports view technologies such as JSP, Velocity and FreeMarker.
  7. With the use of XML-based configuration files, there is no need to recompile the application after editing.

3. The position of SpringMVC in the three-tier architecture :

Insert picture description here


The first Spring MVC program

Step 1: Create a new web project:

  • In eclipse, create a new Web project named SpringMvc, add the JAR package needed to run the Spring MVC program in the lib directory of the project, and publish it to the classpath.

The necessary jar packages are as follows:

Insert picture description here

  • The four core JAR packages of Spring, the commons-logging JAR and two web-related JARs are added to the project. These two web-related JAR packages are the JAR packages required by the Spring MVC framework.

Step 2: Configure XML

  • In web.xml, configure Spring MVC's front controller DispatcherServlet

as follows:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://xmlns.jcp.org/xml/ns/javaee"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
	id="WebApp_ID" version="4.0">
	<display-name>SpringMvc</display-name>
	<servlet>
		<servlet-name>springmvc</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		
		<--当前Servlet的参数信息-->
		<init-param>
			<--contextConfigLocation是参数名称,该参数的值包含了SpringMVC的配置文件路径-->
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:springmvc-config.xml</param-value>
		</init-param>
		
		<--定义在Web应用启动是立即加载Servlet-->
		<load-on-startup>1</load-on-startup>
	</servlet>
	
	<servlet-mapping>
	    <--请求对应的Servlet名称-->
		<servlet-name>springmvc</servlet-name>
		<--监听当前域的所有请求-->
		<url-pattern>/</url-pattern>
	</servlet-mapping>
</web-app>

The third step: Write Controller :

  • In the src directory, create a com.itheima.controller package, and create the controller class FirstController in the package. This class needs to implement the Controller interface. After editing, it looks like this:
public class FirstController implements Controller {
    
    

	@Override
	public ModelAndView handleRequest(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception {
    
    
		// TODO Auto-generated method stub
		ModelAndView mav = new ModelAndView();
		// 添加模型数据,可以是任何的POJO对象
		mav.addObject("msg", "这是我的第一个Spring MVC程序");
		// 设置逻辑视图名,视图解析器会根据该名字解析到具体的视图页面
		mav.setViewName("/WEB-INF/jsp/first.jsp");
		// 返回ModelAndView 对象
		return mav;
	}
}

4. Step 4: Edit dispatcher-servlet.xml

  • In the src directory, create a profile springmvc-config.xml, web.xml above, beginning with the file name of the <servlet-name>element corresponding to the configuration of the dispatcher, which is Spring MVC mapping configuration file (format: xxx-servlet.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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<!--配置Handle,映射"/hello"请求 -->
	<bean name="/hello" class="com.itheima.controller.FirstController" />

	<!-- 处理器映射器,将处理器Handle的name作为url进行查找 -->
	<bean
		class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" />
	<!-- 处理器适配器,配置对处理器中handleRequest()方法的调用 -->
	<bean
		class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter" />
	<!-- 配置视图解析器 -->
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver" />
</beans>

Step 5: Prepare first.jsp

  • In the WEB-INF directory, create a jsp folder, and create a page file first.jsp in the folder, and use EL expressions on this page to get the information in msg, as shown below:
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	${
    
    msg}
</body>
</html>

Step 6: Deploy Tomcat and related environment :

  • Publish the SpringMvc project to Tomcat and start the Tomcat server. Visit the address in the browser: http://localhost:8080/SpringMvc/hello, the display effect is as follows:

Insert picture description here

So far the first Spring MVC program is completed ( ̄︶ ̄)↗

Let's talk about the workflow of Spring MVC:

The icons are as follows:
Insert picture description here

  1. Intercepted by DispatcherServlet: The user sends a request to the server through the browser, and the request will be sent by the Spring MVC front controller.
  2. After DispatcherServlet intercepts the request, it will call the HandlerMapping processor mapper.
  3. The processor mapper finds the processor of its body according to the request URL, generates the processor object and the processor interceptor (if any), and returns it to the DispatcherServlet
  4. DispatcherServlet will select the appropriate HandlerAdapter by returning the letter.
  5. HandlerAdapter will call and execute the Handler (processor), where the processor refers to the Controller class written in the program, also known as the back-end controller.
  6. After the Controller is executed, it will return a ModelAndView object, which will contain the name of the view or the name of the model and the view.
  7. HandlerAdapter returns the ModelAndView object to DispatcherServlet
  8. DispatcherServlet will select an appropriate ViewReslover (view resolver) based on the ModelAndView object.
  9. After ViewReslover is parsed, it will return a specific View to the DispatcherServlet.
  10. DispatcherServlet renders the View (that is, fills the model data into the view).
  11. The rendering result of the view will be returned to the client browser for display.

Guess you like

Origin blog.csdn.net/qq_43531669/article/details/108745445