JAVAEE take a closer look at the framework 05-Getting Started with Spring MVC

1. Integration of Spring and Web environment

1.1 Environmental integration

① Import coordinates

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>5.0.5.RELEASE</version>
</dependency>

② Configure the listener

<!--Spring的监听器(用来加载Spring的配置文件)-->
<listener>
	<listener-class>
       org.springframework.web.context.ContextLoaderListener
   </listener-class>
 </listener>
<!--全局参数,指定Spring配置文件所在位置-->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
</context-param>

1.2 Web environment using Spring

Use in normal environment (used in Servlet)

// 1.使用spring自带的工具类, 获取Spring的核心容器
ApplicationContext app = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
// 2.通过Spring核心容器的getBean方法, 获取指定的对象
AccountService as = app.getBean(AccountService.class);

Use in SpringMVC environment

@Autowired
private AccountService accountService; // 直接依赖注入即可

2. Introduction to SpringMVC

2.1 Overview of SpringMVC

SpringMVC is a lightweight Web framework that implements the MVC design model based on Java and is a follow-up product of SpringFrameWork.

SpringMVC has become one of the most mainstream MVC frameworks at present. It uses a set of annotations to make a simple Java class become a controller that processes requests without implementing any interfaces. It also supports RESTful programming style requests.

2.2 SpringMVC Quick Start

Demand: The client initiates the request, the server receives the request, executes the logic and performs the view jump.

2.2.1 Development steps

① Import coordinates

② Configure SpringMVC core controller DispathcerServlet

③ Configure SpringMVC core file springmvc.xml

④ Create Controller class

⑤ Use annotations to configure the mapped address of the business method in the Controller class

⑥The client initiates a request test

2.2.2 Code implementation

① Import coordinates

<!--Spring坐标-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.0.5.RELEASE</version>
</dependency>
<!--SpringMVC坐标-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.0.5.RELEASE</version>
</dependency>
<!--Servlet坐标-->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>provided</scope>
</dependency>
<!--Jsp坐标-->
<dependency>
    <groupId>javax.servlet.jsp</groupId>
    <artifactId>javax.servlet.jsp-api</artifactId>
    <version>2.3.0</version>
    <scope>provided</scope>
</dependency>

② Configure SpringMVC's core controller in web.xml

<servlet>
    <servlet-name>DispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
    <!--指定Springmvc的配置文件所在位置-->
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <!--让前端控制器随着项目的启动而加载-->
	<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>   
    <servlet-name>DispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

③ Create spring-mvc.xml and configure

<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context" 
    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 
    http://www.springframework.org/schema/mvc   
    http://www.springframework.org/schema/mvc/spring-mvc.xsd  
    http://www.springframework.org/schema/context   
    http://www.springframework.org/schema/context/spring-context.xsd">
    
    <!--配置注解扫描(SpringMVC只扫描自己的Controller)-->
    <context:component-scan base-package="com.ittest.controller"/>
</beans>

④ Create Controller and business method

public class QuickController {
	public String quickMethod(){
		System.out.println("quickMethod running.....");
		return "index";
	}
}

⑤ Configuration notes

@Controller
public class QuickController {
    
    //当前方法的访问路径是"quick"
	@RequestMapping("/quick")
	public String quickMethod(){
		System.out.println("quickMethod running.....");
        // 请求结束后, 跳转到success.jsp页面
        return "/success.jsp";
	}
}

⑥ Test address

http://localhost:8080/springmvcWeb/quick 

2.3 SpringMVC component analysis

Front controller: DispatcherServlet

DispatcherServlet is the center of SpringMVC's entire process control. All user requests need to reach the front-end controller first

Processor mapper: HandlerMapping

HandlerMapping is responsible for finding the execution flow corresponding to the path according to the user request path

Processor adapter: HandlerAdapter

After getting the "execution process" corresponding to the request path, the HandlerAdapter is responsible for calling the corresponding method for execution.

Processor: Handler

Responsible for the actual execution method

View resolver: View Resolver

Responsible for processing "results after method execution", especially jump pages, the view resolver is responsible for processing the page to be jumped

View: View

page

2.4 RequestMapping annotation analysis

effect

RequestMapping: used to set the request path of the method, when the browser's request path meets the requirements, execute the corresponding method

Attributes:

Value: Used to specify the requested URL. It has the same effect as the path attribute

Method: Used to specify the request method

position:

@Controller
@RequestMapping("/page")		//类的访问路径
public class PageController {

    @RequestMapping("/show")	//方法的访问路径
    public String show(){
        return "/success.jsp";
    }
    //如果类上没有RequestMapping, 则该方法的请求路径是 "/show"
    //如果类上也有RequestMapping, 则该方法的请求路径是 "/page/show"

}

2.5 Component scanning

In future development, a program will often include both Spring and Spring MVC, then this time will require them to scan their own.

Spring

<!--扫描整个com.ittest包-->
<context:component-scan base-package="com.ittest">
    <!--排除掉Controller注解,该注解交给SpringMVC处理,Spring不处理-->
    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

SpringMVC

<context:component-scan base-package="com.ittest.cotroller"/>

2.6 Page Jump (View Parser)

In the SpringMVC Controller, sometimes the return value will have repetitive content, at this time, we can extract the repeated part of the return value, then this is the front-end controller of SpringMVC

2.6.1 Case

** Code before configuring "View Parser": **

@RequestMapping("/show02")
public String show02(){
    return "/jsp/aaa.jsp";
}

@RequestMapping("/show03")
public String show03(){
    return "/jsp/bbb.jsp";
}

Extract "View Parser"

<!--配置内部资源视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <!--前缀(前边重复性内容)-->
    <property name="prefix" value="/jsp/"></property>
	<!--后缀(后边重复性内容)-->
    <property name="suffix" value=".jsp"></property>
</bean>

Controller code after configuring the view resolver

@RequestMapping("/show02")
public String show02(){
    return "aaa";
}

@RequestMapping("/show03")
public String show03(){
    return "bbb";
}

2.6.2 Matters needing attention

When a project is configured with a "view resolver", the return value of all Controller methods will be parsed by the "view resolver".

@RequestMapping("/show01")
public String show01(){
    return "/success.jsp";
    //如果项目配置了上边的"视图解析器",则当前方法的返回值,会被自动解析为"/jsp/success.jsp.jsp"
}

**solution: **

If you want the return value of the method not to be parsed by the "view resolver", you can prefix it with "forward" or "redirect"

@RequestMapping("/show01")
public String show01(){
    return "forward:/success.jsp";   //转发到success.jsp, 并且不允许视图解析器解析
    //return "redirect:/success.jsp";   //重定向到success.jsp, 并且不允许视图解析器解析
}
Published 78 original articles · praised 30 · visits 3638

Guess you like

Origin blog.csdn.net/ZMW_IOS/article/details/105102745