springMVC学习笔记——异常页面显示、运行流程、spring与springMVC整合

异常页面显示

可以通过在 springMVC 的配置文件中,配置异常信息解析器SimpleMappingExceptionResolver,实现对指定的异常进行页面跳转。

springMVC 配置文件:

<!-- 配置异常解析器 -->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
	<property name="exceptionMappings">
		<props>
			<!-- key为异常的全类名,prop标签内为发生该异常后要跳转到的页面名称,即视图名称,最终根据视图解析器跳转到最终页面 -->
			<prop key="java.lang.NullPointerException">NullPointException</prop>
			<!-- 可以配置多个异常 -->
			<!-- <prop key=""></prop> -->
		</props>
	</property>
</bean>

控制层:

@Controller
public class TestException {
	@RequestMapping("/exception")
	public String myException() {
		//模拟空指针异常
		String str = null;
		System.out.println(str.charAt(0));
		return "success";
	}
}

页面:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>NullPointerException</title>
</head>
<body>
	<h3>请求异常,请稍后重试!</h3>
</body>
</html>

运行流程

在这里插入图片描述

  1. 用户向服务器发送请求,请求被SpringMVC 前端控制器 DispatcherServlet捕获;
  2. DispatcherServlet对请求URL进行解析,得到请求资源标识符(URI):
    判断请求URI对应的映射
    ①不存在:
    再判断是否配置了mvc:default-servlet-handler:
    如果没配置,则控制台报映射查找不到,客户端展示404错误
    如果有配置,则执行目标资源(一般为静态资源,如:JS,CSS,HTML)
    ②存在:
    执行下面流程
  3. 根据该URI,调用HandlerMapping获得该Handler配置的所有相关的对象(包括Handler对象以及Handler对象对应的拦截器),最后以HandlerExecutionChain对象的形式返回;
  4. DispatcherServlet 根据获得的Handler,选择一个合适的HandlerAdapter。
  5. 如果成功获得HandlerAdapter后,此时将开始执行拦截器的preHandler(…)方法【正向】
  6. 提取Request中的模型数据,填充Handler入参,开始执行Handler(Controller)方法,处理请求。在填充Handler的入参过程中,根据你的配置,Spring将帮你做一些额外的工作:
    ①HttpMessageConveter: 将请求消息(如Json、xml等数据)转换成一个对象,将对象转换为指定的响应信息
    ②数据转换:对请求消息进行数据转换。如String转换成Integer、Double等
    ③数据根式化:对请求消息进行数据格式化。 如将字符串转换成格式化数字或格式化日期等
    ④数据验证: 验证数据的有效性(长度、格式等),验证结果存储到BindingResult或Error中
  7. Handler执行完成后,向DispatcherServlet 返回一个ModelAndView对象;
  8. 此时将开始执行拦截器的postHandle(…)方法【逆向】
  9. 根据返回的ModelAndView(此时会判断是否存在异常:如果存在异常,则执行HandlerExceptionResolver进行异常处理)选择一个适合的ViewResolver(必须是已经注册到Spring容器中的ViewResolver)返回给DispatcherServlet,根据Model和View,来渲染视图
  10. 在返回给客户端时需要执行拦截器的AfterCompletion方法【逆向】
  11. 将渲染结果返回给客户端

spring 与 springMVC 整合

底层实现原理

  1. 如何加载 spring 配置文件?
    通过 ServletContextListener 监听器,在项目启动时就加载 spring 配置文件。
  2. 如何避免扫描组件时,spring 与 springMVC 重复创建同一个对象?
    spring 扫描除了 @Controller 注解以外的全部注解,springMVC 只扫描控制层的包。
  3. 在控制层或其他位置,想要单独获取某一个 bean 对象时,如何获取?
    将加载 spring 配置文件的类对象(如 ClassPathXmlApplicationContext 对象)保存到 ServletContext 域中,在想要获取对象的位置,只需要获取该域对象,调用 getBean() 方法即可。

监听器

public class MyListener implements ServletContextListener{

@Override
public void contextDestroyed(ServletContextEvent sce) {
	
}

@Override
public void contextInitialized(ServletContextEvent sce) {
	ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
	ServletContext servletContext = sce.getServletContext();
	servletContext.setAttribute("applicationContext", context);
}

web.xml

<listener>
	<listener-class>com.mcc.springMVC.MyListener</listener-class>
</listener>

springMVC 配置文件

<!-- 开启组件扫描 -->
<context:component-scan base-package="com.mcc.springMVC.webController"></context:component-scan>

<!-- 视图解析器 -->
<bean id="view" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
	<property name="prefix" value="/WEB-INF/view/"></property>
	<property name="suffix" value=".jsp"></property>
</bean>

<!-- 开启MVC驱动 -->
<mvc:annotation-driven/>

<!-- 使用Tomcat默认处理器 -->
<mvc:default-servlet-handler/>

spring 配置文件

<context:component-scan base-package="com.mcc.springMVC">
	<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

控制层

@RequestMapping("/teacher")
public String testTeacher(HttpSession session) {
	ServletContext context = session.getServletContext();
	ApplicationContext applicationContext = (ApplicationContext)context.getAttribute("applicationContext");
	Teacher teacher = applicationContext.getBean("teacher", Teacher.class);
	teacher.settName("MCC");
	System.out.println("teacher: "+teacher.gettName());
	return "success";
}

spring 提供的实现方法

在这里插入图片描述

spring 中提供一个写好的 ServletContextListener,该监听器封装了加载 spring 配置文件的一系列操作,实现步骤:

(1)在 web.xml 中配置ContextLoaderListener,通过<context-param>标签,设置 spring 配置文件的位置(contextConfigLocation属性)。

<!-- needed for ContextLoaderListener -->
<context-param>
	<param-name>contextConfigLocation</param-name>
	<param-value>classpath:spring.xml</param-value>
</context-param>
<!-- Bootstraps the root web application context before servlet initialization -->
<listener>
	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

(2)springMVC 配置文件中,只扫描控制层的包

<!-- 开启组件扫描 -->
<context:component-scan base-package="com.mcc.springMVC.webController"></context:component-scan>

<!-- 视图解析器 -->
<bean id="view" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
	<property name="prefix" value="/WEB-INF/view/"></property>
	<property name="suffix" value=".jsp"></property>
</bean>

<!-- 开启MVC驱动 -->
<mvc:annotation-driven/>

<!-- 使用Tomcat默认处理器 -->
<mvc:default-servlet-handler/>

(3)spring 配置文件中,扫描除了@Controller 注解以外的全部注解。

<context:component-scan base-package="com.mcc.springMVC">
	<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

(4)如果想要获取加载 spring 配置文件的 ClassPathXmlApplicationContext 对象,在源码中,将该对象保存在 ServletContext 域中,key 为:WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE

@RequestMapping("/teacher")
public String testTeacher(HttpSession session) {
	ServletContext context = session.getServletContext();
	String attributeName = WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE;
	ApplicationContext applicationContext = (ApplicationContext)context.getAttribute(attributeName);
	Teacher teacher = applicationContext.getBean("teacher", Teacher.class);
	teacher.settName("MCC");
	System.out.println("teacher: "+teacher.gettName());
	return "success";
}

完整测试代码

在这里插入图片描述
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_4_0.xsd" version="4.0">
  <display-name>springAndspringMVC</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>
  
  <!-- 配置编码器 -->
  <filter>
  	<filter-name>CharacterEncodingFilter</filter-name>
  	<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  	<init-param>
  		<param-name>encoding</param-name>
  		<param-value>UTF-8</param-value>
  	</init-param>
  </filter>
  <filter-mapping>
  	<filter-name>CharacterEncodingFilter</filter-name>
  	<url-pattern>/*</url-pattern>
  </filter-mapping>
  
  <!-- 配置REST请求方式 -->
  <filter>
  	<filter-name>HiddenHttpMethodFilter</filter-name>
  	<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
  </filter>
  <filter-mapping>
  	<filter-name>HiddenHttpMethodFilter</filter-name>
  	<url-pattern>/*</url-pattern>
  </filter-mapping>
  
  <!-- The front controller of this Spring Web application, responsible for handling all application requests -->
	<servlet>
		<servlet-name>springDispatcherServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:springMVC.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<!-- Map all requests to the DispatcherServlet for handling -->
	<servlet-mapping>
		<servlet-name>springDispatcherServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
  
  	<!-- needed for ContextLoaderListener -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:spring.xml</param-value>
	</context-param>
	<!-- Bootstraps the root web application context before servlet initialization -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
  	
</web-app>

spring.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"
	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-4.3.xsd">
	
	<context:component-scan base-package="com.mcc.springMVC">
		<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
	</context:component-scan>

</beans>

springMVC.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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
		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">
	
	<!-- 开启组件扫描 -->
	<context:component-scan base-package="com.mcc.springMVC.webController"></context:component-scan>
	
	<!-- 视图解析器 -->
	<bean id="view" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/view/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>
	
	<!-- 开启MVC驱动 -->
	<mvc:annotation-driven/>
	
	<!-- 使用Tomcat默认处理器 -->
	<mvc:default-servlet-handler/>
	
</beans>

WebController.java

package com.mcc.springMVC.webController;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.WebApplicationContext;

import com.mcc.springMVC.pojo.Student;
import com.mcc.springMVC.pojo.Teacher;

@Controller
public class WebController {
	
	@Autowired
	private Student student;
	
	@RequestMapping("/student")
	public String testStudent() {
		student.setStuName("mcc");
		System.out.println("student: "+student.getStuName());
		return "success";
	}
	
	@RequestMapping("/teacher")
	public String testTeacher(HttpSession session) {
		ServletContext context = session.getServletContext();
		String attributeName = WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE;
		ApplicationContext applicationContext = (ApplicationContext)context.getAttribute(attributeName);
		Teacher teacher = applicationContext.getBean("teacher", Teacher.class);
		teacher.settName("MCC");
		System.out.println("teacher: "+teacher.gettName());
		return "success";
	}
}

Student.java

package com.mcc.springMVC.pojo;

import org.springframework.stereotype.Component;

@Component
public class Student {
	private String stuName;

	public Student() {
		super();
	}

	public Student(String stuName) {
		super();
		this.stuName = stuName;
	}

	public String getStuName() {
		return stuName;
	}

	public void setStuName(String stuName) {
		this.stuName = stuName;
	}

	@Override
	public String toString() {
		return "Student [stuName=" + stuName + "]";
	}	
}

Teacher.java

package com.mcc.springMVC.pojo;

import org.springframework.stereotype.Component;

@Component
public class Teacher {
	private String tName;

	public Teacher() {
		super();
	}

	public Teacher(String tName) {
		super();
		this.tName = tName;
	}

	public String gettName() {
		return tName;
	}

	public void settName(String tName) {
		this.tName = tName;
	}

	@Override
	public String toString() {
		return "Teacher [tName=" + tName + "]";
	}	
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值