目录
2. 创建SpringConfig配置类,代替spring的配置文件
3. 创建WebConfig配置类,代替SpringMVC的配置文件
异常处理器
1. 基于配置的异常处理
需求:出现某个异常,跳转到某个指定页面
controller
@RequestMapping("/exception")
public String testException(){
int m = 10/0;
return "success";
}
执行结果:抛出异常信息
在SpringMVC中自定义的异常处理器SimpleMappingExceptionResolver
<!--自定义异常处理器-->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<!--抛出那个异常去跳转到那个页面-->
<property name="exceptionMappings">
<props>
<prop key="java.lang.ArithmeticException">error</prop>
</props>
</property>
<!--异常信息放到域对象中,到error页面中展示-->
<property name="exceptionAttribute" value="ex"></property>
</bean>
error.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>error</h1>
<p th:text="${ex}"></p>
</body>
</html>
执行结果:
2. 基于注解的异常处理(用类代替xml配置)
假如现在出现了空指针异常
@RequestMapping("/exception")
public String testException(){
String s = null;
s.toString();
return "success";
}
异常类的组件
package com.zl.controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class ExceptionController {
@ExceptionHandler(value = {NullPointerException.class})
public String testException(Exception ex, Model model){
model.addAttribute("ex",ex);
return "error";
}
}
执行结果:
基于全注解配置SpringMVC
1. 创建初始化类,代替web.xml
解释:默认是要必须重写三个方法:分别代替Spring的配置、SpringMVC的配置、还有DispatcherServlet的映射规则;但是我们知道在web.xml中标配是两个过滤器和一个DispatcherServlet,所以还要重写一个方法,去代替这两个过滤器的配置!
package com.zl.mvc.config;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.filter.HiddenHttpMethodFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import javax.servlet.Filter;
// web工程的初始化类,用来代替web.xml
public class WebInit extends AbstractAnnotationConfigDispatcherServletInitializer {
// 指定spring的配置类
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{SpringConfig.class};
}
// 指定SpringMVC的配置类
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{WebConfig.class};
}
// 指定DispatcherServlet的映射规则,即url-pattern
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
// 添加过滤器
@Override
protected Filter[] getServletFilters() {
// post乱码过滤器
CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
characterEncodingFilter.setEncoding("UTF-8");
characterEncodingFilter.setForceRequestEncoding(true);
characterEncodingFilter.setForceResponseEncoding(true);
// 处理put和delete请求的过滤器
HiddenHttpMethodFilter hiddenHttpMethodFilter = new HiddenHttpMethodFilter();
return new Filter[]{characterEncodingFilter,hiddenHttpMethodFilter};
}
}
2. 创建SpringConfig配置类,代替spring的配置文件
package com.zl.mvc.config;
import org.springframework.stereotype.Controller;
@Controller
public class SpringConfig {
}
3. 创建WebConfig配置类,代替SpringMVC的配置文件
目前主要配置8个部分:
注:对于一些Bean直接配置就可以使用,对于一些组件的开启:例如视图控制器等就需要实现 WebMvcConfigurer这个接口,然后调用方法去实现!
package com.zl.mvc.config;
import com.zl.mvc.interceptor.TestInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;
import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ITemplateResolver;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;
import java.util.List;
import java.util.Properties;
// 代替SpringMVC的配置文件
@Configuration // 将当前类标识为一个配置类
// 1. 扫描组件
@ComponentScan("com.zl.mvc.controller")
// 5. 开启mvc注解驱动
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer { // 对于一些组件的功能就需要实现这个接口去实现
// 2. 视图解析器thymeleaf
//配置生成模板解析器
@Bean // 将返回的对象纳入Spring容器管理
public ITemplateResolver templateResolver() {
WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
// ServletContextTemplateResolver需要一个ServletContext作为构造参数,可通过WebApplicationContext 的方法获得
ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(
webApplicationContext.getServletContext());
templateResolver.setPrefix("/WEB-INF/templates/");
templateResolver.setSuffix(".html");
templateResolver.setCharacterEncoding("UTF-8");
templateResolver.setTemplateMode(TemplateMode.HTML);
return templateResolver;
}
//生成模板引擎并为模板引擎注入模板解析器
@Bean
public SpringTemplateEngine templateEngine(ITemplateResolver templateResolver) {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver);
return templateEngine;
}
//生成视图解析器并未解析器注入模板引擎
// 每个方法的参数是上一个对象,通过自动装配完成的!
@Bean
public ViewResolver viewResolver(SpringTemplateEngine templateEngine) {
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setCharacterEncoding("UTF-8");
viewResolver.setTemplateEngine(templateEngine);
return viewResolver;
}
// 3. 视图控制器:view-controller
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/hello").setViewName("hello");
}
// 4. 默认的Servlet(静态资源的处理):default-servlet-handler
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
// 6. 文件上传解析器
@Bean
public MultipartResolver multipartResolver() {
CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
return commonsMultipartResolver;
}
// 7. 异常处理器
@Override
public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
SimpleMappingExceptionResolver exceptionResolver = new SimpleMappingExceptionResolver();
Properties prop = new Properties();
prop.setProperty("java.lang.ArithmeticException", "error");
// 主要就调用两个方法
exceptionResolver.setExceptionMappings(prop);
exceptionResolver.setExceptionAttribute("ex");
resolvers.add(exceptionResolver);
}
// 8. 拦截器
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 创建拦截器对象
TestInterceptor interceptor = new TestInterceptor();
// 后面跟拦截路径和放行路径
registry.addInterceptor(interceptor).addPathPatterns("/**").excludePathPatterns("/select");
}
}
controller:发出请求跳转到index
package com.zl.mvc.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class TesController {
@RequestMapping("/")
public String index(){
return "index";
}
}
index.html页面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>index</h1>
</body>
</html>
测试结果:通过配置类和注解的方式也能正常访问!