spring boot中常用的配置文件的重写
@Configuration
public class viewConfigSolver extends WebMvcConfigurerAdapter {
/* spring boot 已经自动配置好了springmvc 配置好了viewResolver
* 视图解析器(根据方法的返回值得到视图对象,视图对象决定如何渲染(转发或者重定向))
* 我们可以自己给容器中添加一个视图解析器
* ContentNegotiatingViewResolver就会将其组合进来*/
@Override
public void addViewControllers(ViewControllerRegistry registry) {
super.addViewControllers(registry);
//浏览器发送/index.xml这个请求就来到success页面
// 既保留了原有的配置也能使用我们自己的配置 registry.addViewController("/index.html").setViewName("login");
// }
// 所有的WebMvcConfigurerAdapter组件都会一起起作用
}
@Bean // 将组件注册在容器中
public WebMvcConfigurerAdapter webMvcConfigurerAdapter(){
// 这个类已经过时了,推荐的是WebMvcConfig 它也是实现了WebMvcConfig
WebMvcConfigurerAdapter adapter = new WebMvcConfigurerAdapter() {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("login");
// 加上一个视图映射
registry.addViewController("/index.html").setViewName("login"); registry.addViewController("/main.html").setViewName("dashboard");
}
// 注册拦截器
@Override
public void addInterceptors(InterceptorRegistry registry) {
// super.addInterceptors(registry);
// //静态资源; *.css , *.js 不需要再处理静态资源
//SpringBoot已经做好了静态资源映射 拦截所有请求 排除登录页面的请求
registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**").excludePathPatterns("/templates/login.html","/","/user/login","/asserts/**","/webjars/**"); }
};
return adapter;
}
//将自定义的国际化添加到容器中
/* @Bean
public LocaleResolver localeResolver(){
return new MylocaleResolver();
} */
}
以上是自定义的视图解析器,和拦截器但是这个方法已经过时了,当你点进去查看源码的时候会发现有一个
---------------------------------------------
@Deprecated注解,
科普一下这个注解的意思就是若某类或某方法加上该注解之后,表示此方法或类不再建议使用,
调用时也会出现删除线,但并不代表不能用,只是说,不推荐使用,因为还有更好的方法可以调用。
或许有人会问 为什么会出现加这个注解呢,直接在写方法的时候定义一个新的不就好了吗?
因为在一个项目中,工程比较大,代码比较多,而在后续开发过程中,可能之前的某个方法实现的并不是很合理,这个时候就要新加一个方法,而之前的方法又不能随便删除,因为可能在别的地方有调用它,所以加上这个注解,就方便以后开发人员的方法调用了。
原文:https://blog.csdn.net/alinekang/article/details/79314815
--------------------------------------------------------------------------
所以这里有一个新的实现 下面这个演示是不能直接使用的,能直接使用的在下下面这个是更新后的 类 WebMvcConfigurationSupport
package cn.edu.aynu.zhulina.demo.MyConfig; import cn.edu.aynu.zhulina.demo.component.LoginHandlerInterceptor;
import cn.edu.aynu.zhulina.demo.component.MylocaleResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
@Configuration
public class MyViewConfig extends WebMvcConfigurationSupport {
/*自定义一个方法之后再去声明呢*/
@Bean
public WebMvcConfigurationSupport webMvcConfigurationSupport(){
WebMvcConfigurationSupport adapter = new WebMvcConfigurationSupport() {
@Override
protected void addViewControllers(ViewControllerRegistry registry) {
//super.addViewControllers(registry);
registry.addViewController("/").setViewName("login");
// 加上一个视图映射
registry.addViewController("/index.html").setViewName("login"); registry.addViewController("/main.html").setViewName("dashboard");
} @Override
protected void addInterceptors(InterceptorRegistry registry) {
//super.addInterceptors(registry);
// registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**").excludePathPatterns("/login.html","/","/user/login","/asserts/**","/webjars/**"); }
};
return adapter;
} // 将自定义的国际化添加到容器中
@Bean
public LocaleResolver localeResolver(){
return new MylocaleResolver();
}
}
但是你如果写会发现发现无法访问静态资源,已经controller都无法访问,为什么呢,是应为因为java8接口具有默认实现
因为在springboot中默认是加载了mvc的配置,可以查看注释@WebMvcAutoConfiguration,这个注释有一个条件注释@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)。也就是说只要在容器中发现有WebMvcConfigurationSupport这个类,那就会失效,我们就必须在我们的主类上添加@EnableWebMvc注解,这样我就无法访问默认的静态资源了。因为WebMvcConfigurerAdapter过时,是因为java8中接口有默认实现,而WebMvcConfigurerAdapter实现的就是WebMvcConfigurer方法,所以我只要实现WebMvcConfigurer接口,然后重写我们需要的方法即可。
原文:https://blog.csdn.net/pengdandezhi/article/details/81182701
-----------------------------------------------------
下面我带你们看一下源码,究竟是为什么
spring mvc自动配置 没事可以研究研究 https://docs.spring.io/spring-boot/docs/1.5.10.RELEASE/reference/htmlsingle/#boot-features-developing-web-applications
@Configuration
@ConditionalOnWebApplication(type = Type.SERVLET)
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class })
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + )
@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class,
TaskExecutionAutoConfiguration.class, ValidationAutoConfiguration.class })
public class WebMvcAutoConfiguration { public static final String DEFAULT_PREFIX = ""; public static final String DEFAULT_SUFFIX = ""; private static final String[] SERVLET_LOCATIONS = { "/" };
那么就是单纯的实现类了
package cn.edu.aynu.zhulina.demo.MyConfig; import cn.edu.aynu.zhulina.demo.component.LoginHandlerInterceptor;
import cn.edu.aynu.zhulina.demo.component.MylocaleResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class DefineConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("login");
/*加上一个视图映射*/
registry.addViewController("/index.html").setViewName("login"); registry.addViewController("/main.html").setViewName("dashboard");
} @Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**").excludePathPatterns("/login.html","/","/user/login","/asserts/**","/webjars/**");
}
/*将自定义的国际化添加到容器中*/
@Bean
public LocaleResolver localeResolver(){
return new MylocaleResolver();
}
}
接下来就是自定义异常了 ,先来看一下注解
@ControllerAdvice的作用
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface ControllerAdvice {
....
}
也被声明为一个组件有两个好处,可以被spring boot 添加到容器中 然后也可以被<context:component-scan>扫描到
作用:@ControllerAdvice是一个@Component,用于定义@ExceptionHandler,@InitBinder和@ModelAttribute方法,适用于所有使用@RequestMapping方法。
@ControllerAdvice常用来处理异常
package cn.edu.aynu.zhulina.demo.Controller; import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler; import javax.servlet.http.HttpServletRequest;
import java.nio.file.attribute.UserPrincipalNotFoundException;
import java.util.HashMap;
import java.util.Map;
@ControllerAdvice
public class MyExceptionHandler { @ExceptionHandler(UserPrincipalNotFoundException.class)
public String handlerException(HttpServletRequest request,Exception e){
Map<String ,Object> map = new HashMap();
//传入我们自己的错误状态码 4xx 5xx
/**
* Integer statusCode = (Integer) request
.getAttribute("javax.servlet.error.status_code");
*/
request.setAttribute("javax.servlet.error.status_code",);
map.put("code","user.NotExist");
map.put("message","用户出错啦");
request.setAttribute("ext",map);
return "forward:/error";
}
}
@ExceptionHandler和@ResponseStatus中,如果单使用@ExceptionHandler,只能在当前Controller中处理异常。但当配合@ControllerAdvice一起使用的时候,就可以摆脱那个限制了。
package cn.edu.aynu.zhulina.demo.Controller; import cn.edu.aynu.zhulina.demo.exception.UserNotExistException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest;
import java.nio.file.attribute.UserPrincipalNotFoundException;
import java.util.HashMap;
import java.util.Map;
@ControllerAdvice
public class MyExceptionHandler { @ExceptionHandler(UserNotExistException.class)
public String handlerException(HttpServletRequest request,Exception e){
Map<String ,Object> map = new HashMap();
//传入我们自己的错误状态码 4xx 5xx
/**
* Integer statusCode = (Integer) request
.getAttribute("javax.servlet.error.status_code");
*/
request.setAttribute("javax.servlet.error.status_code",);
map.put("code","user.NotExist");
map.put("message","用户出错啦");
request.setAttribute("ext",map);
return "forward:/error"; }
}
package cn.edu.aynu.zhulina.demo.component; import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.WebRequest; import java.util.Map;
@Component
public class MyErrorAttributes extends DefaultErrorAttributes {
@Override
public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {
Map<String,Object> map = super.getErrorAttributes(webRequest, includeStackTrace);
map.put("company","atguigu");
/*我们的异常处理器携带的数据*/
Map<String,Object> ext = (Map<String, Object>) webRequest.getAttribute("ext", );
map.put("ext",ext);
return map;
} }
可以自定义异常信息,但是我没有成功并没有显示出我的异常信息,待后续..................
spring boot中常用的配置文件的重写的更多相关文章
- spring boot中的底层配置文件application.yam(application.property)的装配原理初探
*在spring boot中有一个基础的配置文件application.yam(application.property)用于对spring boot的默认设置做一些改动. *在spring boot ...
- 解决Spring boot中读取属性配置文件出现中文乱码的问题
问题描述: 在配置文件application.properties中写了 server.port=8081 server.servlet.context-path=/boy name=张三 age=2 ...
- Spring Boot中路径及配置文件读取问题
编译时src/main/java中*.java文件会被编译成*.class文件,在classpath中创建对应目录及class文件 src/main/resources目录中的文件 ...
- Spring Boot 中配置文件application.properties使用
一.配置文档配置项的调用(application.properties可放在resources,或者resources下的config文件夹里) package com.my.study.contro ...
- spring boot(三):Spring Boot中Redis的使用
spring boot对常用的数据库支持外,对nosql 数据库也进行了封装自动化. redis介绍 Redis是目前业界使用最广泛的内存数据存储.相比memcached,Redis支持更丰富的数据结 ...
- Spring Boot中的注解
文章来源:http://www.tuicool.com/articles/bQnMra 在Spring Boot中几乎可以完全弃用xml配置文件,本文的主题是分析常用的注解. Spring最开始是为了 ...
- springboot(三):Spring boot中Redis的使用
spring boot对常用的数据库支持外,对nosql 数据库也进行了封装自动化. redis介绍 Redis是目前业界使用最广泛的内存数据存储.相比memcached,Redis支持更丰富的数据结 ...
- Spring Boot 中的静态资源到底要放在哪里?
当我们使用 SpringMVC 框架时,静态资源会被拦截,需要添加额外配置,之前老有小伙伴在微信上问松哥Spring Boot 中的静态资源加载问题:"松哥,我的HTML页面好像没有样式?& ...
- Spring Boot:Spring Boot 中 Redis 的使用
Redis 介绍 Redis 是目前业界使用最广泛的内存数据存储.相比 Memcached,Redis 支持更丰富的数据结构,例如 hashes, lists, sets 等,同时支持数据持久化.除此 ...
随机推荐
- Md5的生成
1.使用hashlib包(一) import hashlib src = 'anthing' m1 = hash.new() m1.update(src) print (m1.hexdigest()) ...
- Google Colab 基本操作
## 上传 from google.colab import files uploaded = files.upload() for fn in uploaded.keys(): print('Use ...
- [python] 解决pip install download速度过慢问题 更换豆瓣源
""" python建立pip.ini.py 2016年4月30日 03:35:11 codegay """ import os ini=& ...
- WiFi-ESP8266入门http(3-3)网页认证上网-post请求-ESP8266程序
第一版 原型系统 连上西电的网 直接发送上网的认证信息 返回认证结果网页 成功上网 #include <ESP8266WiFi.h> #define Use_Serial Serial s ...
- Java NIO5:通道和文件通道
一.通道是什么 通道式(Channel)是java.nio的第二个主要创新.通道既不是一个扩展也不是一项增强,而是全新的.极好的Java I/O示例,提供与I/O服务的直接连接.Channel用于在字 ...
- 长期招收linux驱动工程师
公司:宝存科技 工作内容: 1.负责企业级ssd的feature设计和开发工作 2.负责ftl算法的设计及开发 3.排查客户问题 任职要求: 1.精通C语言 2.熟练掌握linux操作系统使用 3.熟 ...
- UVA10256 The Great Divide
怎么又没人写题解,那我来贡献一发好了. 题目意思很简单,平面上有两种颜色的点,问你能否求出一条直线使两种颜色的点完全分开. 首先我们考虑两个点集相离的充要条件,这两个点集的凸包必须相离.(很好证明或者 ...
- 反射那些基础-Class
目录 1 Class 类是什么? 2 如何获取 Class 对象 2.1 Object.getClass() 2.2 .class 语法 2.3 Class.forName() 2.4 通过包装类的 ...
- .Net Core 在 Linux-Centos上的部署实战教程(一)
pa我是在VS2017上写好项目然后来部署的,我的宗旨能截图就少BB 服务器系统: Asp.Net Core版本: 1.往服务器安装.net core 2.1 https://www.microsof ...
- .net core 2.1 开源项目 COMCMS dnc版本
项目一直从dotnet core 1.1开始,升级到2.0,乃至如今2.1,以后保持继续更新. 但可能只是一个后台,前台的话,到时候看有没有好的模板. ------------无聊的分割线------ ...