6. RestfulCRUD
1. 默认访问首页
package com.matthew.springboot04.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* @Description TODO 使用WebMvcConfigurerAdapter可以来扩展SpringMVC的功能
* @Author Matthew
* @Date 2019/5/26 14:40
* @Version 1.0
*/
//@EnableWebMvc 不要接管SpringMVC
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
//浏览器发送/Matthew也来到success
registry.addViewController("/Matthew").setViewName("success");
}
//所有的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;
}
}
2. 国际化
- 编写国际化配置文件;
- 使用ResourceBundleMessageSource管理国际化资源文件
- 在页面使用fmt:message取出国际化内容
步骤:
- 编写国际化配置文件,抽取页面需要显示的国际化消息
- SpringBoot自动配置好了管理国际化资源文件的组件;
@Conditional({MessageSourceAutoConfiguration.ResourceBundleCondition.class})
@EnableConfigurationProperties
public class MessageSourceAutoConfiguration {
@Bean
@ConfigurationProperties(
prefix = "spring.messages"
)
public MessageSourceProperties messageSourceProperties() {
return new MessageSourceProperties();
}
//public class MessageSourceProperties {
// private String basename = "messages";
@Bean
public MessageSource messageSource(MessageSourceProperties properties) {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
if (StringUtils.hasText(properties.getBasename())) {
//设置国际化资源文件的基础名(去掉语言国家代码的)
messageSource.setBasenames(StringUtils.commaDelimitedListToStringArray(StringUtils.trimAllWhitespace(properties.getBasename())));
}
if (properties.getEncoding() != null) {
messageSource.setDefaultEncoding(properties.getEncoding().name());
}
messageSource.setFallbackToSystemLocale(properties.isFallbackToSystemLocale());
Duration cacheDuration = properties.getCacheDuration();
if (cacheDuration != null) {
messageSource.setCacheMillis(cacheDuration.toMillis());
}
messageSource.setAlwaysUseMessageFormat(properties.isAlwaysUseMessageFormat());
messageSource.setUseCodeAsDefaultMessage(properties.isUseCodeAsDefaultMessage());
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.3.1/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(获取区域信息对象);
@ConditionalOnMissingBean:当我们没写localeResolver的时候系统启用它。
接下来我们就写一个自己的localeResolver来代替它。
@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(
prefix = "spring.mvc",
name = {"locale"}
)
public LocaleResolver localeResolver() {
if (this.mvcProperties.getLocaleResolver() == org.springframework.boot.autoconfigure.web.servlet.WebMvcProperties.LocaleResolver.FIXED) {
return new FixedLocaleResolver(this.mvcProperties.getLocale());
} else {
AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver();
localeResolver.setDefaultLocale(this.mvcProperties.getLocale());
return localeResolver;
}
}
- 点击链接切换国际化
package com.matthew.springboot04.component;
import org.springframework.web.servlet.LocaleResolver;
import org.thymeleaf.util.StringUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;
/**
* @Description TODO 可以在连接上携带区域信息
* @Author Matthew
* @Date 2019/5/28 16:20
* @Version 1.0
*/
public class MyLocaleResolver implements LocaleResolver {
@Override
public Locale resolveLocale(HttpServletRequest httpServletRequest) {
String l = httpServletRequest.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 httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {
}
}
将我们自己的LocaleResolver加入到容器中
@Bean
public LocaleResolver localeResolver(){
return new MyLocaleResolver();
}
3. 登录
模板引擎页面修改以后,要实时生效
- 禁用模板引擎的缓存
# 禁用缓存
spring.thymeleaf.cache=false
- 页面修改完成以后ctrl+F9,重新编译;
登录错误消息的显示
<p style="color: red;" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
4. 拦截器进行登录检查
package com.matthew.springboot04.component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @Description TODO 登录检查
* @Author Matthew
* @Date 2019/5/28 18:41
* @Version 1.0
*/
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;
}
}
}
5. CRUD-员工列表
实验要求:
- RestfulCRUD:CRUD满足Rest风格;
URl:/资源名称/资源标识,HTTP请求方式区分对资源CRUD操作
普通CRUD(uri来区分操作) | RestfulCRUD | |
---|---|---|
查询 | getEmp | emp----GET |
添加 | addEmp?xxx | emp----POST |
修改 | updateEmp?id=xxx&xxx=xx | emp/{id}----PUT |
删除 | deleteEmp?id=x | emp/{id}----DELETE |
- 实验的请求架构;
请求URI | 请求方式 | |
---|---|---|
查询所有员工 | emps | GET |
查询某个员工 | Emp/{id} | GET |
来到添加页面 | emp | GET |
添加员工 | emp | POST |
来到修改页面(查出员工进行信息回显) | emp/{id} | GET |
修改员工 | emp | PUT |
删除员工 | emp/{id} | DELETE |
- 员工列表:
thymeleaf公共页面元素抽取
1. 抽取公共片段
<div th:fragment="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:将被引入的片段的额内容包含进这个标签中
<div th:fragment="copy">
© 2011 The Good Thymes Virtual Grocery
</div>
引入方式
<div th:insert="footer::copy"></div>
<div th:replace="footer::copy"></div>
<div th:include="footer::copy"></div>
效果
<div>
<footer>
© 2011 The Good Thymes Virtual Grocery
</footer>
</div>
<footer>
© 2011 The Good Thymes Virtual Grocery
</footer>
<div>
© 2011 The Good Thymes Virtual Grocery
</div>
引入片段的时候传入参数
6. CRUD-员工添加
添加页面
<form>
<div class="form-group">
<label>LastName</label>
<input type="text" class="form-control" placeholder="zhangsan">
</div>
<div class="form-group">
<label>Email</label>
<input type="email" class="form-control" placeholder="zhangsan@atguigu.com">
</div>
<div class="form-group">
<label>Gender</label><br/>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="gender" value="1">
<label class="form-check-label">男</label>
</div>
<div class="form-check form-check-inline">
<input class="form‐check‐input" type="radio" name="gender" value="0">
<label class="form‐check‐label">女</label>
</div>
</div>
<div class="form-group">
<label>department</label>
<!--提交的是部门的id-->
<select class="form‐control">
<option th:value="${dept.id}" th:each="dept:${depts}" th:text="${dept.departmentName}">1</option>
</select>
</div>
<div class="form-group">
<label>Birth</label>
<input type="text" class="form-control" placeholder="zhangsan">
</div>
<button type="submit" class="btn btn-primary">添加</button>
</form>
提交的数据格式不对:生日:日期;
2017-12-12;2017/12/12;2017.12.12;
日期的格式化;SpringMVC将页面提交的值需要转换为指定的类型;
2017-12-12—Date; 类型转换,格式化;
默认日期是按照/的方式;
7. 员工修改
修改添加二合一表单
<!‐‐需要区分是员工修改还是添加;‐‐>
<form th:action="@{/emp}" method="post">
<!‐‐发送put请求修改员工数据‐‐>
<!‐‐
1、SpringMVC中配置HiddenHttpMethodFilter;(SpringBoot自动配置好的)
2、页面创建一个post表单
3、创建一个input项,name="_method";值就是我们指定的请求方式
‐‐>
<input type="hidden" name="_method" value="put" th:if="${emp!=null}"/>
<input type="hidden" name="id" th:if="${emp!=null}" th:value="${emp.id}">
<div class="form‐group">
<label>LastName</label>
<input name="lastName" type="text" class="form‐control" placeholder="zhangsan"
th:value="${emp!=null}?${emp.lastName}">
</div>
<div class="form‐group">
<label>Email</label>
<input name="email" type="email" class="form‐control"
placeholder="zhangsan@atguigu.com" th:value="${emp!=null}?${emp.email}">
</div>
<div class="form‐group">
<label>Gender</label><br/>
<div class="form‐check form‐check‐inline">
<input class="form‐check‐input" type="radio" name="gender" value="1"
th:checked="${emp!=null}?${emp.gender==1}">
<label class="form‐check‐label">男</label>
</div>
<div class="form‐check form‐check‐inline">
<input class="form‐check‐input" type="radio" name="gender" value="0"
th:checked="${emp!=null}?${emp.gender==0}">
<label class="form‐check‐label">女</label>
</div>
</div>
<div class="form‐group">
<label>department</label>
<!‐‐提交的是部门的id‐‐>
<select class="form‐control" name="department.id">
<option th:selected="${emp!=null}?${dept.id == emp.department.id}"
th:value="${dept.id}" th:each="dept:${depts}" th:text="${dept.departmentName}">1</option>
</select>
</div>
<div class="form‐group">
<label>Birth</label>
<input name="birth" type="text" class="form‐control" placeholder="zhangsan"
th:value="${emp!=null}?${#dates.format(emp.birth, 'yyyy‐MM‐dd HH:mm')}">
</div>
<button type="submit" class="btn btn‐primary" th:text="${emp!=null}?'修改':'添加'">添加
</button>
</form>
8. CRUD-员工删除
<tr th:each="emp:${emps}">
<td th:text="${emp.id}"></td>
<td>[[${emp.lastName}]]</td>
<td th:text="${emp.email}"></td>
<td th:text="${emp.gender}==0?'女':'男'"></td>
<td th:text="${emp.department.departmentName}"></td>
<td th:text="${#dates.format(emp.birth, 'yyyy‐MM‐dd HH:mm')}"></td>
<td>
<a class="btn btn‐sm btn‐primary" th:href="@{/emp/}+${emp.id}">编辑</a>
<button th:attr="del_uri=@{/emp/}+${emp.id}" class="btn btn‐sm btn‐danger
deleteBtn">删除</button>
</td>
</tr>
<script>
$(".deleteBtn").click(function(){
//删除当前员工的
$("#deleteEmpForm").attr("action",$(this).attr("del_uri")).submit();
return false;
});
</script>
7.错误处理机制
1. SpringBoot默认的错误处理机制
- 默认效果:
- 浏览器:返回一个默认的错误页面
浏览器发送请求的请求头:
- 如果是其他客户端访问,默认响应一个json数据
原理:
可以参照ErrorMvcAutoConfiguration,错误处理的自动配置。
给容器中添加了以下组件:- DefaultErrorAttributes
- 浏览器:返回一个默认的错误页面
//帮我们在页面共享信息:
public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {
Map<String, Object> errorAttributes = new LinkedHashMap();
errorAttributes.put("timestamp", new Date());
this.addStatus(errorAttributes, webRequest);
this.addErrorDetails(errorAttributes, webRequest, includeStackTrace);
this.addPath(errorAttributes, webRequest);
return errorAttributes;
}
2. BasicErrorController
@Controller
@RequestMapping({"${server.error.path:${error.path:/error}}"})
public class BasicErrorController extends AbstractErrorController {
@RequestMapping(
produces = {"text/html"}//产生html类型的数据,浏览器发送的请求来到这个方法处理
)
public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
HttpStatus status = this.getStatus(request);
Map<String, Object> model = Collections.unmodifiableMap(this.getErrorAttributes(request, this.isIncludeStackTrace(request, MediaType.TEXT_HTML)));
response.setStatus(status.value());
//去哪个页面作为错误页面,包含页面地址和页面内容
ModelAndView modelAndView = this.resolveErrorView(request, response, status, model);
return modelAndView != null ? modelAndView : new ModelAndView("error", model);
}
@RequestMapping//产生json数据,其他客户端来到这个方法处理
public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
Map<String, Object> body = this.getErrorAttributes(request, this.isIncludeStackTrace(request, MediaType.ALL));
HttpStatus status = this.getStatus(request);
return new ResponseEntity(body, status);
}
3. ErrorPageCustomizer
@Value("${error.path:/error}")
private String path = "/error"; 系统出现错误以后来到error请求进行处理;(web.xml注册的错误页面规则)
4. DefaultErrorViewResolver
public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, Map<String, Object> model) {
ModelAndView modelAndView = this.resolve(String.valueOf(status.value()), model);
if (modelAndView == null && SERIES_VIEWS.containsKey(status.series())) {
modelAndView = this.resolve((String)SERIES_VIEWS.get(status.series()), model);
}
return modelAndView;
}
private ModelAndView resolve(String viewName, Map<String, Object> model) {
//默认SpringBoot可以找到一个页面? error/404
String errorViewName = "error/" + viewName;
//如果模板引擎可以解析这个页面地址就用模板引擎解析
TemplateAvailabilityProvider provider = this.templateAvailabilityProviders.getProvider(errorViewName, this.applicationContext);
//模板引擎可用的情况下返回到errorViewName 指定的视图地址,如果不可用就在静态资源文件夹下errorViewName对应的页面error/404.html
return provider != null ? new ModelAndView(errorViewName, model) : this.resolveResource(errorViewName, model);
}
步骤:
一但系统出现4xx或者5xx;ErrorPageCustomizer就会生效(定制错误的响应规则);就会来到/error请求,就会被BasicErrorController处理;
1. 响应页面:去哪个页面是由**DefaultErrorViewResolver**
protected ModelAndView resolveErrorView(HttpServletRequest request, HttpServletResponse response, HttpStatus status, Map<String, Object> model) {
Iterator var5 = this.errorViewResolvers.iterator();
ModelAndView modelAndView;
do {
if (!var5.hasNext()) {
return null;
}
//所有的ErrorViewResolver得到ModelAndView
ErrorViewResolver resolver = (ErrorViewResolver)var5.next();
modelAndView = resolver.resolveErrorView(request, status, model);
} while(modelAndView == null);
return modelAndView;
}
- 如果定制错误响应:
- 如何定制错误的页面;
- 有模板引擎的情况下,error/状态码;【将错误页面命名为 错误状态码.html放在模板引擎文件夹里面的error文件夹下】,发生此状态码的错误就会来到对应的页面;
我们可用使用4xx和5xx作为错误页面的文件名来匹配这种类型的所有错误,精确优先(优先寻找精确的状态码.html);
页面能获取的信息;
timestamp:时间戳
status:状态码
error:错误提示
exception:异常对象
message:异常消息
errors:JSR303数据校验的错误都在这里
- 没有模板引擎(模板引擎找不到这个错误页面),静态资源文件夹下找
- 以上都没有错误页面,就是默认来到SpringBoot默认的错误提示页面
- 有模板引擎的情况下,error/状态码;【将错误页面命名为 错误状态码.html放在模板引擎文件夹里面的error文件夹下】,发生此状态码的错误就会来到对应的页面;
- 如何定制错误的json数据;
- 自定义异常处理&返回定制json数据;
- 如何定制错误的页面;
package com.matthew.springboot04.controller;
/**
* @Description TODO
* @Author Matthew
* @Date 2019/6/1 20:37
* @Version 1.0
*/
import com.matthew.springboot04.exception.UserNotExistException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.util.StringUtils;
import java.util.HashMap;
import java.util.Map;
@ControllerAdvice
public class MyExceptionHandler {
@ResponseBody
@ExceptionHandler(UserNotExistException.class)
public Map<String, Object> handlerException(Exception e) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("code", "user.notexist");
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<String, Object>();
//传入我们自己的错误状态码 4xx 5xx,否则就不会进入定制错误页面的解析流程
/*
* Integer statusCode = (Integer)request
* getAttribute("javax.servlet.error.status_code");
*/
request.setAttribute("javax.servlet.error.status_code",500);
map.put("code", "user.notexist");
map.put("message", e.getMessage());
//转发到/error
return "forward:/error";
}
3. 将我们的定制数据携带出去
出现错误以后,会来到/error请求,会被BasicErrorController处理,响应出去可用获取的数据是由getErrorAttributes得到的(是AbstracErrorController(ErrorController)规定的方法);
1. 完全来编写一个ErrorController的实现类【或者是编写AbstracErrorController的子类】,放在容器中;
2. 页面上能用的数据,或者是json返回能用的数据都是通过errorAttributes.getErrorAttributes得到;容器中DefaultErrorAttributes.getErrorAttribute默认进行数据处理的;
自定义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", "matthew");
return map;
}
}
最终的效果:响应是自适应的,可用通过定制ErrorAttributes改变需要返回的内容。
8. 配置嵌入式Servlet容器
SpringBoot默认使用tomcat作为嵌入式的Servlet容器
问题?
1. 如何定制和修改Servlet容器的相关配置;
- 修改和server有关的配置(ServerProperties【也是WebServerFactoryCustomizer】)
server.port = 8081
server.context-path=/crud
//通用的Servlet容器设置
server.xxx
//Tomcat的设置
server.tomcat.uri-encoding=UTF-8
- 编写一个EmbeddedServletContainerCustomizer:但是在spring2.0中 WebServerFactoryCustomizer替换了EmbeddedServletContainerCustomizer,嵌入式的Servlet容器的定制器;来修改Servlet容器的配置
@Bean
public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer(){
return new WebServerFactoryCustomizer<ConfigurableWebServerFactory>() {
@Override
public void customize(ConfigurableWebServerFactory factory) {
factory.setPort(8083);
}
};
}
2. 注册Servlet三大组件【Servlet、Filter、Listener】
由于SpringBoot默认是以jar包的方式启动嵌入式的Servlet容器来启动SpringBoot的web应用,没有web.xml文
件。
注册三大组件用以下方式
ServletRegistrationBean
@Bean
public ServletRegistrationBean myServlet(){
ServletRegistrationBean registrationBean = new ServletRegistrationBean(new MyServlet(), "/myServlet");
return registrationBean;
}
FilterRegistrationBean
@Bean
public FilterRegistrationBean myFilter(){
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
registrationBean.setFilter(new MyFilter());
registrationBean.setUrlPatterns(Arrays.asList("/hello", "/myServlet"));
return registrationBean;
}
ServletListenerRegistrationBean
@Bean
public ServletListenerRegistrationBean myListener() {
ServletListenerRegistrationBean<MyListener> registrationBean = new ServletListenerRegistrationBean<>(new MyListener());
return registrationBean;
}
SpringBoot帮我们自动SpringMVC的时候,自动的注册SpringMVC的前端控制器;DispatcherServlet;
DispatcherServletAutoConfiguration中:
@Bean(
name = {"dispatcherServletRegistration"}
)
@ConditionalOnBean(
value = {DispatcherServlet.class},
name = {"dispatcherServlet"}
)
public DispatcherServletRegistrationBean dispatcherServletRegistration(DispatcherServlet dispatcherServlet) {
//默认拦截:/所有请求包括静态资源,但不拦截jsp请求;/*会拦截jsp
//可以通过server。serverPath来修改SpringMVC前端控制器默认拦截的请求路径
DispatcherServletRegistrationBean registration = new DispatcherServletRegistrationBean(dispatcherServlet, this.webMvcProperties.getServlet().getPath());
registration.setName("dispatcherServlet");
registration.setLoadOnStartup(this.webMvcProperties.getServlet().getLoadOnStartup());
if (this.multipartConfig != null) {
registration.setMultipartConfig(this.multipartConfig);
}
return registration;
}
- SpringBoot能不能支持其他的Servlet容器;
3. 替换为其他嵌入式Servlet容器
默认支持:
Tomcat(默认使用)
<!--引入web模块-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
引入web模块默认就是使用潜入式的Tomcat作为Servlet容器的
</dependency>
Jetty(长连接)
<!--引入web模块-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<artifactId>spring-boot-starter-tomcat</artifactId>
<groupId>org.springframework.boot</groupId>
</exclusion>
</exclusions>
</dependency>
<!--引入其他的Servlet容器-->
<dependency>
<artifactId>spring-boot-starter-jetty</artifactId>
<groupId>org.springframework.boot</groupId>
</dependency>
Undertow(不支持JSP)
<!--引入web模块-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<artifactId>spring-boot-starter-tomcat</artifactId>
<groupId>org.springframework.boot</groupId>
</exclusion>
</exclusions>
</dependency>
<!--引入其他的Servlet容器-->
<dependency>
<artifactId>spring-boot-starter-undertow</artifactId>
<groupId>org.springframework.boot</groupId>
</dependency>
9. 使用外置的Servlet容器
嵌入式Servlet容器:jar
优点:简单、便携;
缺点:默认不支持JSP、优化定制复杂
配置外置tomcat服务器时需要将Application context:改为/
外置的Servlet容器:外面安装Tomcat——应用war包的方式打包;
步骤:
- 必须创建一个war项目;(利用idea创建好目录结构)
- 将嵌入式的Tomcat指定为provided;
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
- 必须编写一个SpringBootServletInitializer的子类,并调用configure方法
public class ServletInitializer extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
//传入springboot应用的主程序
return application.sources(SpringBoot04WebJspApplication.class);
}
}
- 启动服务器就可以使用了。
原理
jar包:执行SpringBoot主类的main方法,启动ioc容器,创建嵌入式Servlet容器。
war包:启动服务器,服务器启动SpringBoot应用【SpringBootServletInitializer 】,启动ioc容器。
servlet3.0(SpringBoot注解版):8.2.4 Shared libraries / runtimes pluggability
规则:
- 服务器Dion给(webb应用启动)会创建当前web应用里面每一个jar包里面ServletContainerInitializer的实现类的实例。
- ServletContainerInitializer的实现放在jar包的META-INF/services文件夹下,有一个名为javax.servlet.ServletContainerInitializer的文件,内容就是ServletContainerInitializer的实现类的全类名。
- 还可以使用HandlesTypes,在应用启动的时候加载我们感兴趣的类;
流程:
- 启动Tomcat
- org\springframework\spring-web\4.3.24.RELEASE\spring-web-4.3.24.RELEASE.jar!\META-INF\services\javax.servlet.ServletContainerInitializer;
Spring的web模块里面有个文件:org.springframework.web.SpringServletContainerInitializer - SpringServletContainerInitializer将@HandlesTypes({WebApplicationInitializer.class})标注的所有这个类型的类都传入到onStartup方法的Set<Class<?>>,为这些WebApplicationInitializer类型的类创建实例;
- 每一个WebApplicationInitializer都调用自己的onStartup;
- 相当于我们的SpringBootServletInitalizer的类会被创建对象,并执行onSartup方法;
- SpringBootServletInitalizer示例执行onStartup的时候会createRootApplicationContext;创建容器
protected WebApplicationContext createRootApplicationContext(ServletContext servletContext) {
SpringApplicationBuilder builder = this.createSpringApplicationBuilder();
builder.main(this.getClass());
ApplicationContext parent = this.getExistingRootWebApplicationContext(servletContext);
if (parent != null) {
this.logger.info("Root context already created (using as parent).");
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, (Object)null);
builder.initializers(new ApplicationContextInitializer[]{new ParentContextApplicationContextInitializer(parent)});
}
builder.initializers(new ApplicationContextInitializer[]{new ServletContextApplicationContextInitializer(servletContext)});
builder.contextClass(AnnotationConfigEmbeddedWebApplicationContext.class);
//调用configure方法,子类重写了这个方法,将我们的Springboot的主程序类传入了进来
builder = this.configure(builder);
builder.listeners(new ApplicationListener[]{new SpringBootServletInitializer.WebEnvironmentPropertySourceInitializer(servletContext)});
//使用builder创建一个Spring应用
SpringApplication application = builder.build();
if (application.getSources().isEmpty() && AnnotationUtils.findAnnotation(this.getClass(), Configuration.class) != null) {
application.getSources().add(this.getClass());
}
Assert.state(!application.getSources().isEmpty(), "No SpringApplication sources have been defined. Either override the configure method or add an @Configuration annotation");
if (this.registerErrorPageFilter) {
application.getSources().add(ErrorPageFilterConfiguration.class);
}
//启动Spring应用
return this.run(application);
}
- Spring的应用就启动并且创建ioc容器。
public ConfigurableApplicationContext run(String... args) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
ConfigurableApplicationContext context = null;
FailureAnalyzers analyzers = null;
this.configureHeadlessProperty();
SpringApplicationRunListeners listeners = this.getRunListeners(args);
listeners.starting();
try {
ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
ConfigurableEnvironment environment = this.prepareEnvironment(listeners, applicationArguments);
Banner printedBanner = this.printBanner(environment);
context = this.createApplicationContext();
new FailureAnalyzers(context);
this.prepareContext(context, environment, listeners, applicationArguments, printedBanner);
//刷新IOC容器
this.refreshContext(context);
this.afterRefresh(context, applicationArguments);
listeners.finished(context, (Throwable)null);
stopWatch.stop();
if (this.logStartupInfo) {
(new StartupInfoLogger(this.mainApplicationClass)).logStarted(this.getApplicationLog(), stopWatch);
}
return context;
} catch (Throwable var9) {
this.handleRunFailure(context, listeners, (FailureAnalyzers)analyzers, var9);
throw new IllegalStateException(var9);
}
}
启动Servlet容器,再启动SpringBoot应用