Sping Boot 学习笔记(六)

Spring Boot 学习笔记(六)

Spring Boot与web开发

Web开发

使用Spring Boot
1.创建SpringBoot应用,选中我们需要的模块
2.SpringBoot已经默认将这些场景配置好了,只需要在配置文件中指定少量的配置就可以运行起来
3.自己编写业务代码

自动配置原理
这个场景SpringBoot帮我们配置了什么?能不能修改?能修改那些配置?能不能扩展?xxx
xxxxAutoConfiguration:帮我们给容器中自动配置组件
xxxxProperties:配置类来封装配置文件的内容;

SpringBoot对静态资源的映射规则

@ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false)
public class ResourceProperties {
//可以设置和资源有关的参数,缓存时间等
@Override
		public void addResourceHandlers(ResourceHandlerRegistry registry) {
			if (!this.resourceProperties.isAddMappings()) {
				logger.debug("Default resource handling disabled");
				return;
			}
			Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
			CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
			if (!registry.hasMappingForPattern("/webjars/**")) {
				customizeResourceHandlerRegistration(registry.addResourceHandler("/webjars/**")
						.addResourceLocations("classpath:/META-INF/resources/webjars/")
						.setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
			}
			String staticPathPattern = this.mvcProperties.getStaticPathPattern();
			if (!registry.hasMappingForPattern(staticPathPattern)) {
				customizeResourceHandlerRegistration(registry.addResourceHandler(staticPathPattern)
						.addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations()))
						.setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
			}
		}

		private Integer getSeconds(Duration cachePeriod) {
			return (cachePeriod != null) ? (int) cachePeriod.getSeconds() : null;
		}

		private void customizeResourceHandlerRegistration(ResourceHandlerRegistration registration) {
			if (this.resourceHandlerRegistrationCustomizer != null) {
				this.resourceHandlerRegistrationCustomizer.customize(registration);
			}
		}
		//配置欢迎页映射
		@Bean
		public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext,
				FormattingConversionService mvcConversionService, ResourceUrlProvider mvcResourceUrlProvider) {
			WelcomePageHandlerMapping welcomePageHandlerMapping = new WelcomePageHandlerMapping(
					new TemplateAvailabilityProviders(applicationContext), applicationContext, getWelcomePage(),
					this.mvcProperties.getStaticPathPattern());
			welcomePageHandlerMapping.setInterceptors(getInterceptors(mvcConversionService, mvcResourceUrlProvider));
			return welcomePageHandlerMapping;
		}

1.所有/webjars/**,都去classpath:/META-INF/resources/webjars/找资源;
webjars:以jar包的方式引入静态资源;
http://localhost:8080/webjars/jquery/3.3.1/jquery.js

<!--引入jquery的webjar-->
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>3.3.1</version>
        </dependency>

2. "/** 访问当前项目的任何资源,(静态资源文件夹)

"classpath:/META-INF/resources/",
"classpath:/resources/", 
"classpath:/static/", 
"classpath:/public/"
"/": //当前项目的根路径

localhost:8080/abc === 去静态资源文件夹里面找abc
3.欢迎页;静态资源文件夹下面的所有index.html页面;被“/**”映射
localhost:8080/找index页面
4.所有的**/favicon.ico都是在静态资源下找

3.模板引擎

JSP,Velocity、freemarker、Thymeleaf
语法更简单,功能更强大;

引入thymeleaf;

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        切换thymeleaf版本
<thymeleaf.version>3.0.2.RELEASE</thymeleaf.version>
        <!--布局功能的支持程序,thymeleaf3主程序 layout2以上版本-->
        <!--thymeleaf2 layout1-->
        <thymeleaf-layout-dialect.version>2.1.1</thymeleaf-layout-dialect.version>

Thymeleaf使用&语法

@ConfigurationProperties(prefix = "spring.thymeleaf")
public class ThymeleafProperties {

	private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8;

	public static final String DEFAULT_PREFIX = "classpath:/templates/";

	public static final String DEFAULT_SUFFIX = ".html";
	//

只要我们吧HTML页面放在classpath:/templates/,thymeleaf就能自动渲染;
使用:
1.导入thymeleaf的名称空间

<html lang="en" xmlns:th="http://www.thymeleaf.org">

2.使用thymeleaf语法:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>成功</h1>
    <!--th:text="" 将div里面的文本内容设置为-->
    <div th:text="${hello}">这是显示欢迎信息</div>
</body>
</html>

3.语法规则

1.th:text:改变当前元素里面的文本内容;
th:任意html属性;来替换原生属性的值
2.表达式

Simple expressions:(表达式语法)
	Variable Expressions: ${...} :获取变量值 OGNL
			1.获取对象的属性、调用方法
			2.使用内置的基本对象
			#ctx : the context object. 
			#vars: the context variables. 
			#locale : the context locale. 
			#request : (only in Web Contexts) the HttpServletRequest object. 			        						                                                 #response : (only in Web Contexts) the HttpServletResponse object.
			#session : (only in Web Contexts) the HttpSession object. 														      #servletContext : (only in Web Contexts) the ServletContext object
			${session.foo}
			3.内置的一些工具对象:
#execInfo : information about the template being processed. 		#messages : methods for obtaining externalized messages inside variables expressions, in the same way as they would be obtained using #{} syntax. #uris : methods for escaping parts of URLs/URIs Page 20 of 106
#conversions : methods for executing the configured conversion service (if any). #dates : methods for java.util.Date objects: formatting, component extraction, etc. #calendars : analogous to #dates , but for java.util.Calendar objects. #numbers : methods for formatting numeric objects. #strings : methods for String objects: contains, startsWith, prepending/appending, etc. #objects : methods for objects in general. #bools : methods for boolean evaluation. #arrays : methods for arrays. #lists : methods for lists. #sets : methods for sets. #maps : methods for maps. #aggregates : methods for creating aggregates on arrays or collections. #ids : methods for dealing with id attributes that might be repeated (for example, as a result of an iteration).
	Selection Variable Expressions: *{...} :选择表达式 和${}在功能上是一样的
			补充:配合th:object="${session.user}":
<div th:object="${session.user}"> <p>Name: <span th:text="*{firstName}">Sebastian</span>.</p> <p>Surname: <span th:text="*{lastName}">Pepper</span>.</p> <p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p> </div>
	Message Expressions: #{...} :获取国际化内容
	Link URL Expressions: @{...} :定义url:
	@{/order/process(execId=${execId},execType='FAST')}
	Fragment Expressions: ~{...} :片段引用表达式
	<div th:insert="~{commons :: main}">...</div>
Literals (字面量)
	Text literals: 'one text' , 'Another one!' ,… 
	Number literals: 0 , 34 , 3.0 , 12.3 ,… 
	Boolean literals: true , false 
	Null literal: null 
	Literal tokens: one , sometext , main ,… 
Text operations: (文本操作)
	String concatenation: + 
	Literal substitutions: |The name is ${name}|
Arithmetic (数学运算)
	operations: Binary operators: + , - , * , / , % 
	Minus sign (unary operator): - 
Boolean operations: (布尔运算)
	Binary operators: and , or 
	Boolean negation (unary operator): ! , not 
Comparisons and equality: (比较运算)
	Comparators: > , < , >= , <= ( gt , lt , ge , le ) 
	Equality operators: == , != ( eq , ne ) 
Conditional operators: (条件运算)(三元运算符也支持)
	If-then: (if) ? (then) 
	If-then-else: (if) ? (then) : (else) 
	Default: (value) ?: (defaultvalue) 
Special tokens: 
No-Operation:

扩展SpringMVC

    <mvc:view-controller path="/hello" view-name="success"/>
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/hello"/>
            <bean></bean>
        </mvc:interceptor>
    </mvc:interceptors>

编写一个配置类(@Configuration),是WebMvcConfigurerAdapter类型;不能标注@EnableWebMvc
既保留了所有的自动配置,也能用我们扩展的配置

//使用WebMvcConfigurerAdapter可以扩展SpringMVC的功能
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
//        super.addViewControllers(registry);
        //浏览器发送/atguigu请求来到 success
        registry.addViewController("/atguigu").setViewName("success");
    }
}

原理:
1.WebMvcAutoConfiguration是SpringMVC的自动配置类
2.再做其他自动配置时会导入:@Import(EnableWebMvcConfiguration.class)
3.

	@Configuration(proxyBeanMethods = false)
	public static class EnableWebMvcConfiguration extends DelegatingWebMvcConfiguration implements ResourceLoaderAware {
	private final WebMvcConfigurerComposite configurers = new WebMvcConfigurerComposite();

	//从容器中获取所有的WebMvcConfigurer
	@Autowired(required = false)
	public void setConfigurers(List<WebMvcConfigurer> configurers) {
		if (!CollectionUtils.isEmpty(configurers)) {
			this.configurers.addWebMvcConfigurers(configurers);
			//一个参考实现;将所有的WebMvcConfigurer相关的配置都来一起调用
				@Override
			//public void addViewControllers(ViewControllerRegistry registry) {
				//for (WebMvcConfigurer delegate : this.delegates) {
				//	delegate.addViewControllers(registry);
				}
			}
		}
	}

容器中所有的WebMvcConfigurer都会一起起作用
4.我们的配置类也会被调用
效果:SpringMVC的自动配置和我们的扩展配置都会起作用

全面接管SpringMVC

SpringBoot对SpringMVC的自动配置不需要了,所有都是我们自己配置;所有的SpringMVC的自动配置都失效了,我们需要在配置类中添加@EnableWebMvc即可

//使用WebMvcConfigurerAdapter可以扩展SpringMVC的功能
@EnableWebMvc
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
//        super.addViewControllers(registry);
        //浏览器发送/atguigu请求来到 success
        registry.addViewController("/atguigu").setViewName("success");
    }
}

原理:
1@EnableWebMvc的核心

@Import(DelegatingWebMvcConfiguration.class)
public @interface EnableWebMvc {
@Configuration(proxyBeanMethods = false)
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {
@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication(type = Type.SERVLET)
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class })
//容器中没有这个组件的时候,这个自动配置类才生效
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class, TaskExecutionAutoConfiguration.class,
		ValidationAutoConfiguration.class })
public class WebMvcAutoConfiguration {

4.@EnableWebMvc将WebMvcConfigurationSupport组件导入进来;
5.导入的WebMvcConfigurationSupport只是SpringMVC最基本的功能;

如何修改Spring Boot的默认配置

模式:
1.Spring Boot在自动配置很多组件的时候,先看容器中有没有用户自己配置的(@Bean、@Component)如果有就用用户自己配置的,如果没有,才自动配置;如果有些组件可以有多个(ViewResolver)将用户配置的和自己默认的组合起来;
2.在SpringBoot中会有非常多的Configurer帮助我们进行扩展配置

RestfulCRUD

1.默认访问首页

    @RequestMapping({"/", "/index.html"})
    public String index(){
        return "index";
    }
     //所有的WebMvcConfigurerAdapter组件都会一起起作用
    @Bean //将组件注册在容器中
    public WebMvcConfigurerAdapter WebMvcConfigurerAdapter(){
        WebMvcConfigurerAdapter adapter = new WebMvcConfigurerAdapter(){
            @Override
            public void addViewControllers(ViewControllerRegistry registry) {
                registry.addViewController("/").setViewName("login");
                registry.addViewController("/index.html").setViewName("login");
            }
        };
        return adapter;
    }

国际化

1.编写国际化配置文件
2.使用ResourceBundleMessageSource管理国际化资源文件
3.在页面使用fmt:message取出国际化内容

步骤:
1.编写国际化配置文件,抽取页面需要显示的国际话消息
2.SpringBoot自动配置好了国际化资源文件的组件

@ConfigurationProperties(prefix = "spring.messages")
 public class MessageSourceAutoConfiguration { 
 /*** Comma‐separated list of basenames (essentially a fully‐qualified classpath 
 * location), each following the ResourceBundle convention with relaxed support for 
* slash based locations. If it doesn't contain a package qualifier (such as * "org.mypackage"), it will be resolved from the classpath root.
*  
*/ private String basename = "messages"; 
//我们的配置文件可以直接放在类路径下叫messages.properties; 
@Bean 
public MessageSource messageSource() { 
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
 if (StringUtils.hasText(this.basename)) { 
 //设置国际化资源文件的基础名(去掉语言国家代码的) 
 messageSource.setBasenames(StringUtils.commaDelimitedListToStringArray( StringUtils.trimAllWhitespace(this.basename))); 
 }
if (this.encoding != null) { 
	messageSource.setDefaultEncoding(this.encoding.name()); 
}
messageSource.setFallbackToSystemLocale(this.fallbackToSystemLocale); 	
messageSource.setCacheSeconds(this.cacheSeconds); 	
messageSource.setAlwaysUseMessageFormat(this.alwaysUseMessageFormat); 
	return messageSource; 
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
		<meta name="description" content="">
		<meta name="author" content="">
		<title>Signin Template for Bootstrap</title>
		<!-- Bootstrap core CSS -->
		<link href="asserts/css/bootstrap.min.css" th:href="@{/webjars/bootstrap/4.0.0/css/bootstrap.css}" rel="stylesheet">
		<!-- Custom styles for this template -->
		<link href="asserts/css/signin.css" th:href="@{/asserts/css/signin.css}" rel="stylesheet">
	</head>

	<body class="text-center">
		<form class="form-signin" action="dashboard.html">
			<img class="mb-4" th:src="@{/asserts/img/bootstrap-solid.svg}" src="asserts/img/bootstrap-solid.svg" alt="" width="72" height="72">
			<h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}">Please sign in</h1>
			<label class="sr-only" th:text="#{login.username}">Username</label>
			<input type="text" class="form-control" placeholder="Username" th:placeholder="#{login.username}" required="" autofocus="">
			<label class="sr-only" th:text="#{login.password}">Password</label>
			<input type="password" class="form-control" placeholder="Password" th:placeholder="#{login.password}" required="">
			<div class="checkbox mb-3">
				<label>
          <input type="checkbox" value="remember-me"/> [[#{login.remember}]]
        </label>
			</div>
			<button class="btn btn-lg btn-primary btn-block" type="submit" th:text="#{login.btn}">Sign in</button>
			<p class="mt-5 mb-3 text-muted">© 2017-2018</p>
			<a class="btn btn-sm">中文</a>
			<a class="btn btn-sm">English</a>
		</form>

	</body>

</html>

效果:根据浏览器语言设置的信息切换了国际化

原理:
国际化Locale(区域信息对象);LocaleResolver(获取区域信息对象)
4.点击链接切换国际化

/**
 * 可以在链接上携带区域信息
 */
public class MyLocaleResolver implements LocaleResolver {
    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        String l = request.getParameter("l");
        Locale locale = Locale.getDefault();
        if (!StringUtils.isEmpty(l)) {
            String[] split = l.split("_");
            locale = new Locale(split[0],split[1]);
        }
        return locale;
    }

    @Override
    public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {

    }
}
	@Bean
    public LocaleResolver localeResolver(){
        return new MyLocaleResolver();
    }

登录

开发期间模板引擎页面修改以后要实时生效
1.禁用模板引擎的缓存
2.页面修改完成以后ctrl+f9:重新编译

登录错误消息的显示

<p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>

拦截器进行登录检查

/**
 * 登录检查,
 */
public class LoginHandlerInterceptor implements HandlerInterceptor {
    //目标方法执行之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object user = request.getSession().getAttribute("loginUser");
        if (user == null) {
            //未登录,返回登录页面
            request.setAttribute("msg","没有权限请先登录");
            request.getRequestDispatcher("/index.html").forward(request,response);
            return false;
        }else{
            //已登录,放行请求
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
    //注册拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //super.addInterceptors(registry);
        //静态资源: *.css,*.js
        //SpringBoot已经做好了静态资源映射
        registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**")
                .excludePathPatterns("/index.html","/","/user/login")
                .excludePathPatterns("/asserts/css");
    }

CRUD-员工列表

1.ResultfulCRUD:CRUD满足Rest风格
URI:/资源名称/资源标识 HTPP请求方式区分对资源CRUD操作

普通的CRUD(uri来区分操作)RestfulCRUD
查询getEmpemp—GET
添加addEmp?xxxemp—POST
修改updateEmp?id=xxx&xxx=xxemp/{id}—PUT
删除deleteEmp?id=1emp/{id}----DELETE

实验的请求架构

请求URI请求方式
查询所有员工empsGET
查询某个员工(来到修改页面)emp/{id}GET
来到添加页面empGET
添加员工empGET
来到修改页面(查出员工进行信息回显)emp/{id}GET
修改员工empPUT
删除员工emp/{id}DELETE
1、抽取公共片段 
<div th:fragment="copy"> 
&copy; 2011 The Good Thymes Virtual Grocery 
</div> 
2、引入公共片段 
<div th:insert="~{footer :: copy}"></div>
 ~{templatename::selector}:模板名::选择器 
 ~{templatename::fragmentname}:模板名::片段名 
 3、默认效果: 
 insert的公共片段在div标签中 
 如果使用th:insert等属性进行引入,可以不用写~{}: 
 行内写法可以加上:[[~{}]];[(~{})]

三种引入功能片段的th属性
th:insert:将公共的片段整个插入到声明引入的元素中
th:replace:将声明引入的元素替换为公共片段
th:include:将被引入的片段的内容包含进这个标签中

<footer th:fragment="copy"> 
&copy; 2011 The Good Thymes Virtual Grocery 
</footer>


 引入方式
 <div th:insert="footer :: copy"></div>
 <div th:replace="footer :: copy"></div> 
 <div th:include="footer :: copy"></div>
 效果
 <div>
 	<footer> 
 		&copy; 2011 The Good Thymes Virtual Grocery 
 	</footer> 
 </div> 
 <footer> 
 &copy; 2011 The Good Thymes Virtual Grocery 
 </footer> 
 <div> 
 	&copy; 2011 The Good Thymes Virtual Grocery
 </div>

引入片段的时候传入参数:

<nav class="col‐md‐2 d‐none d‐md‐block bg‐light sidebar" id="sidebar"> 
	<div class="sidebar‐sticky"> 
		<ul class="nav flex‐column"> 
			<li class="nav‐item"> 
				<a class="nav‐link active" 
					th:class="${activeUri=='main.html'?'nav‐link active':'nav‐link'}" 
					href="#" th:href="@{/main.html}"> 
					<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke‐width="2" stroke‐ linecap="round" stroke‐linejoin="round" class="feather feather‐home"> 
					<path d="M3 9l9‐7 9 7v11a2 2 0 0 1‐2 2H5a2 2 0 0 1‐2‐2z"></path> 
					<polyline points="9 22 9 12 15 12 15 22"></polyline> </svg> 
					Dashboard <span class="sr‐only">(current)</span> 
					</a> 
				</li> 
<!‐‐引入侧边栏;传入参数‐‐> 
<div th:replace="commons/bar::#sidebar(activeUri='emps')"></div>

引入片段的时候传入参数
提交的数据格式不对:生日:日期;
2017-12-12;2017/12/12;2017.12.12;
日期的格式化;SpringMVC将页面提交的值需要转换为指定的类型; 2017-12-12—Date; 类型转换,格式化;
默认日期是按照/的方式;

错误处理机制

1.SpringBoot默认的错误处理机制
默认效果
1.浏览器返回一个默认的错误页面
2.如果是其他客户端,默认响应一个json数据
原理:
可以参照ErrorMvcAutoConfiguration:错误处理的自动配置
给容器中添加了以下组件
1.DefaultErrorAttributes:
2.BasicErrorController:
处理默认的/error请求
3.ErrorPageCustomizer:
系统出现错误之后来到error进行请求处理;(web.xml注册的错误页面规则)
4.DefaultErrorViewResolver:

步骤
一旦系统出现4xx或者5xx之类的错误,ErrorPageCustomizer就会生效(定制错误的响应规则),就会来到/error请求;就会被BasicErrorController

2.如果定制错误的响应
1.如何定制错误的页面;
1.有模板引擎的情况下:error/状态码)(将错误页面命名为 错误的状态码.html放在模板引起文件夹里面的error文件夹下),发生此状态码的错误就会来到对应的页面;
我们可以使用4xx和5xx作为错误页面的文件名来匹配这种类型的所有错误,精确优先(优先寻找精确地状态码.html);
页面能获取的信息;
tmestamp:时间戳
staus:状态码
error:错误提示
exception:异常对象
message:异常消息
errors:JSR303数据校验的错误都在这里
2.没有模板引擎(模板引擎找不到这个错误页面),静态资源文件夹下找;
3.以上都没有错误页面,就是默认来到SpringBoot默认的错误提示页面

2.如何定制地错误的json数据

1.自定义异常处理&返回定制json数据:

@ControllerAdvice
public class MyExceptionHandler {
    @ResponseBody
    @ExceptionHandler(UserNotExistException.class)
    public Map<String,Object> handlerException(Exception e){
        Map<String,Object> map = new HashMap<>();
        map.put("code","not exist");
        map.put("message",e.getMessage());
        return map;
    }
}
//没有自适应效果

2.转发到/error进行自适应响应效果处理

    @ExceptionHandler(UserNotExistException.class)
    public String handlerException(Exception e, HttpServletRequest request){
        Map<String,Object> map = new HashMap<>();
        //传入我们自己的错误状态码 4xx 5xx吗,否则就不会进入定制错误页面的解析流程
        request.setAttribute("javax.servlet.error.status_code",500);
        map.put("code","not exist");
        map.put("message",e.getMessage());
        //转发到/error
        return "forward:/error";
    }

3.将我们的定制的数据携带出去
出现错误以后,会来到/error请求,会被BasicErrorController请求处理,响应出去可以获取的数据是由getErrorAttributes得到的(是AbstractErrorController(ErrorController)规定的方法);
1.完全来编写一个ErrorController的实现类【或者是编写AbstractErrorController的子类】,放在容器中;
2.页面上能用的数据,或者是json返回能用的数据都是通过errorAttributes.getErrorAttributes得到的;
容器中DefaultErrorAttributes.getErrorAttributes()默认进行数据处理的
自定义ErrorAttributes

//给容器中加入我们自己定义的ErrorAttributes();
@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");
        return map;
    }
}

最终的效果:响应式自适应的,可以通过定制ErrorAttributes改变需要返回的内容

配置嵌入式Servlet容器

SpringBoot默认是用得是嵌入的Servlet容器(Tomcat)
问题?
如何定制和修改Servlet容器的相关配置;
修改和server有关得配置(ServerProperties)

server.port=8081
server.tomcat.uri-encoding=UTF-8
//通用的Servlet容器设置
server.xxx
//tomcat的设置
server.tomcat.xxx
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值