Getting started with Spring MVC: the first Spring MVC program

Overview of Spring MVC

      Spring MVC provides a lightweight Web framework that implements the Web MVC design pattern. It is the same as the Struts framework. It belongs to the MVC framework, but its use and performance are better than Struts.
Spring MVC has the following characteristics:
(1) It is Spring Part of the framework, you can easily use other functions provided by Spring
(2) Flexible and easy to integrate with other frameworks
(3) Provide a front controller DispatcherServlet, so that developers do not need to develop additional controller objects
(4) Automatically bind user input, and can correctly convert the data type
(5) Built-in common validator, can verify the user input if the verification fails, then it will be redirected to the input form
(6) Support for internationalization Display multiple languages ​​according to the user area
(7); support multiple view technologies. It supports view technologies such as JSP Velocity FreeMarker
(8) use base XML configuration files, after editing, there is no need to recompile the application

Spring MVC workflow

The source of the picture: Java ee Enterprise Application Development Tutorial

The complete execution process of the Spring MVC program is as follows:
(1) The user sends a request to the server through the browser, and the request will be intercepted by the Spring MVC front controller DispatcherServlet
(2) DispatcherServlet intercepted After the request, it will call the HandlerMapping processor mapper
(3) The processor mapper finds the specific processor according to the request URL, generates the processor object and the processor interceptor (if any), and returns it to DispatcherServlet
(4) DispatcherServlet Will select the appropriate HandlerAdapter (processor adapter) by returning the information
(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 view name or model and view name
(7) HandlerAdapter ModelAndView object returned to DispatcherServlet
(8) DispatcherServlet will select a suitable ViewReslover (view) based on the ModelAndView object Parser)
(9) ViewReslover After parsing, it will return a specific View (view) to the DispatcherServlet
(10) DispatcherServlet View for rendering (that is, to fill the model data into the view)
(11) View rendering results will be returned to the client browser for display

The first Spring MVC program

The project structure diagram is as follows:
Note:
1. web.xml should be placed in the WEB-INF directory
2. springMVC-config.xml should be placed in the src directory.
Generally named like this, the figure is to distinguish different configurations
Insert picture description here
web.xml

<?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_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>spirngmvc_01</display-name>
  
  <!-- 配置前端过滤器 -->
  <servlet>
  	<servlet-name>springmvc</servlet-name>
  	<!--servlet-class中的值是spring-webmvc包提供的类,即前端控制器,用于控制所有请求 -->
  	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  	
  	<!-- 初始化时加载文件(springmvc-anno.xml) -->
  	<init-param>
  		<param-name>contextConfigLocation</param-name>
  		<param-value>classpath:springmvc-anno.xml</param-value>
  	</init-param>
  	<!--  表示容器在启动时立即加载 Servlet,数值越小,加载越快 -->
  	<load-on-startup>1</load-on-startup>
  	
  </servlet>
  
  <!-- 配置servlet映射  servlet-name取值与servlet的servlet-name一致-->
  <servlet-mapping>
  	<servlet-name>springmvc</servlet-name>
  	<url-pattern>/</url-pattern>
  </servlet-mapping>

</web-app>

springmvc-anno.xml (annotation)

<?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-4.3.xsd
	   http://www.springframework.org/schema/context 
  http://www.springframework.org/schema/context/spring-context-4.3.xsd">
	<!-- 指定需要扫描的包 -->
	<context:component-scan base-package="com.controller" >
	 
	       <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>  
	       
	</context:component-scan>
	<!-- 定义视图解析器 -->
	<bean id="viewResolver" class=
    "org.springframework.web.servlet.view.InternalResourceViewResolver">
	     <!-- 设置前缀 -->
	     <property name="prefix" value="/WEB-INF/jsp/" />
	     <!-- 设置后缀 -->
	     <property name="suffix" value=".jsp" />
	</bean>
</beans>  

springmvc-xml.xml (non-annotation)

<?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">
        <!-- 配置Handel,映射"/hello"请求 -->
        
        <bean name="/hello" class="com.controller.FirstController"/>
        <!-- 处理映射器将bean的name作为url进行查找,需要在配置Handel时指定name(即url) -->
        
        <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
        
        <!-- SimpleControllerHandlerAdapter是一个处理器适配器,所有处理器适配器都要实现HandlerAdapter接口,-->
        <!--通过适配器实现对handlReqeust的调用 -->
        
        <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>
        
        <!-- 视图解析器 -->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"/>
</beans>

controller class

package com.controller;

import java.lang.annotation.Annotation;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
//import org.springframework.web.servlet.mvc.Controller;


//1、基于注解
@Controller
@RequestMapping(value="/hello")
public class FirstController {
	
	@RequestMapping(value="/firstController")
	public String handleRequest(HttpServletRequest request,
			HttpServletResponse response, Model model) throws Exception {
		// 向模型对象中添加数据
		model.addAttribute("msg", "hello,这是我的第一个Spring MVC程序,基于annotation");
		// 返回视图页面
		return "first";
	}

}

//1、继承Controller类
//public class FirstController implements Controller{
//
//	@Override
//	public ModelAndView handleRequest(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception {
//		
//		ModelAndView mav = new ModelAndView();
//		
//		mav.addObject("msg", "hello,这是我的第一个Spring MVC程序,基于xml");
//		mav.setViewName("/WEB-INF/jsp/first.jsp");
//		return mav;
//	}
//}

View (jsp)

<%@ page language="java" contentType="text/html; charset=UTF-8"
     pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
         "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>入门程序</title>
</head>
	<body>
	     ${msg}
	</body>
</html>

Publish the project to Tomcat, start the Tomcat server, and then enter http://localhost:8080/project name/hello/firstController in the browser (based on annotations)

Use annotations or inherit the controller class
1. The springMVC.xml file is different
2. The classpath in the web.xml file should be changed accordingly,
3. The url entered in the browser should also be changed accordingly

Guess you like

Origin blog.csdn.net/m0_46267375/article/details/106670294
Recommended