SpringBoot之web开发实例

SpringBoot-Web项目实例 文章目录SpringBoot-Web项目实例1 项目结构2 [国际化]语言切换配置通过按钮切换信息3 登陆&拦截器登陆重定向&拦截器4 CRUD-员工列表4.1 RestfulCRUD4.2 访问员工列表thymeleaf公共页面抽取链接高亮修改表格内容,增加按钮4.3 添加员工页面页面表单4.4 员工修改4.5 员工删除5 错误处理5.1 错误处理原理5.2 自定义错误页面 SpringBoot-Web项目实例 1 项目结构 加入Dao层,和实体对象 加入静态资源css、img、js进 阅读详情

SpringBoot之web开发实例

一 访问首页

默认访问首页使用WebMVCConfigureAdapter来添加视图控制器代替controller中的访问方法
代码实现:

@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {
    //所有的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");
                registry.addViewController("/main.html").setViewName("dashboard");
            }
}

二 国际化

1 SpringMVC处理国际化步骤

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

2 SpringBoot处理国际化步骤

(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;
}

(3)去页面获取国际化的值

<!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" th:action="@{/user/login}" method="post">
			<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>
			<!--判断-->
			<p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
			<label class="sr-only" **th:text="#{login.username}"**>Username</label>
			<input type="text"  name="username" class="form-control" placeholder="Username" **th:placeholder="#{login.username}"** required="" autofocus="">
			<label class="sr-only" **th:text="#{login.password}"**>Password</label>
			<input type="password" name="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" th:href="@{/index.html(l='zh_CN')}">中文</a>
			<a class="btn btn-sm" th:href="@{/index.html(l='en_US')}">English</a>
		</form>
	</body>

</html>

SpringBoot实现国际化原理
主要是两个对象:Locale(区域信息对象)和LocaleResolver(获取区域信息对象),默认的就是根据请求头带来的区域信息获取Locale进行国际化
追踪源码如下:

@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(prefix = "spring.mvc", name = "locale")
public LocaleResolver localeResolver() {
	if (this.mvcProperties.getLocaleResolver() == WebMvcProperties.LocaleResolver.FIXED) {
		return new FixedLocaleResolver(this.mvcProperties.getLocale());
	}
	AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver();
	localeResolver.setDefaultLocale(this.mvcProperties.getLocale());
	return localeResolver;

	}

(4)点击链接切换国际化
在登录页面的连接加参数

<a class="btn btn-sm" th:href="@{/index.html(**l='zh_CN')**}">中文</a>
			<a class="btn btn-sm" th:href="@{/index.html(**l='en_US'**)}">English</a>

代码实现:

/**
 * 可以在连接上携带区域信息
 */
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) {

    }
}
//在MyMVCConfig配置类中将写的MyLocaleResolver加入容器中
 @Bean
    public LocaleResolver localeResolver(){

        return new MyLocaleResolver();
    }

页面截图如下:
在这里插入图片描述

三 登录拦截器

1 登录错误信息显示

页面修改实时生效小技巧:
在配置文件中禁用thymeleaf的缓存
spring.thymeleaf.cache=false
页面修改完后Ctrl+F9重新编译页面
登录错误信息页面显示代码:

<--加判断条件进行错误信息显示-->
<p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
2 登录拦截器检查

(1)登录拦截器定义

/**
 * 登陆检查,
 */
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 {

    }
}

(2)注册定义的登录拦截器

@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {
    //所有的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");
                registry.addViewController("/main.html").setViewName("dashboard");
            }

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

    @Bean
    public LocaleResolver localeResolver(){

        return new MyLocaleResolver();
    }

}

四 页面公共部分抽取(thymeleaf)

1 抽取公共页面

抽取页面的头部、尾部和导航栏的公共部分代码
(1)实现方法:

1、抽取公共片段
<div th:fragment="copy">
	&copy; 2011 The Good Thymes Virtual Grocery
</div>
2、引入公共片段
<div th:insert="~{footer :: copy}"></div>
引入两种方式:
	(1)~{templatename::selector}:模板名::选择器
	(2)~{templatename::fragmentname}:模板名::片段名
3、默认效果:
(1)insert的公共片段在div标签中
(2)如果使用th:insert等属性进行引入,可以不用写~{}:
(3)行内写法可以加上:[[~{}]];[(~{})];

(2)三种引入公共片段的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>

效果
insert:
<div>
	<footer>
		&copy; 2011 The Good Thymes Virtual Grocery
	</footer>
</div>
replace:
<footer>
	&copy; 2011 The Good Thymes Virtual Grocery
</footer>
include:
<div>
	&copy; 2011 The Good Thymes Virtual Grocery
</div>

(3)案例
① 公共片段(常用两种方法)
使用th:fragment:头部使用th:fragment=“topbar”
使用id:导航栏使用id=“sidebar”
其中 th:class="${activeUri==‘main.html’?‘nav-link active’:‘nav-link’}"是用于判断选中导航栏时高亮显示,参数activeUri在引入公共片段是会声明

<!--topbar-->
<nav class="navbar navbar-dark sticky-top bg-dark flex-md-nowrap p-0" th:fragment="topbar">
    <a class="navbar-brand col-sm-3 col-md-2 mr-0" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">[[${session.loginUser}]]</a>
    <input class="form-control form-control-dark w-100" type="text" placeholder="Search" aria-label="Search">
    <ul class="navbar-nav px-3">
        <li class="nav-item text-nowrap">
            <a class="nav-link" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">Sign out</a>
        </li>
    </ul>
</nav>

<!--sidebar-->
<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>
            <li class="nav-item">
                <a class="nav-link"
                   href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">
                    <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-file">
                        <path d="M13 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"></path>
                        <polyline points="13 2 13 9 20 9"></polyline>
                    </svg>
                    Orders
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">
                    <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-shopping-cart">
                        <circle cx="9" cy="21" r="1"></circle>
                        <circle cx="20" cy="21" r="1"></circle>
                        <path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"></path>
                    </svg>
                    Products
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link active" href="#" th:href="@{/emps}"
                th:class="${activeUri=='emps'?'nav-link active':'nav-link'}">
                    <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-users">
                        <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path>
                        <circle cx="9" cy="7" r="4"></circle>
                        <path d="M23 21v-2a4 4 0 0 0-3-3.87"></path>
                        <path d="M16 3.13a4 4 0 0 1 0 7.75"></path>
                    </svg>
                    员工管理
                </a>
            </li>
            
        </ul>
    </div>
</nav>
2 页面引入公共片段

① 头部
~{templatename::fragmentname}:模板名::片段名

<!--引入topbar-->
<div th:replace="commons/bar::topbar"></div>

② 导航栏
~{templatename::selector}:模板名::选择器
其中activeUri='main.html’是用于导航栏选择时显示高亮的参数

<!--引入sidebar-->
<div th:replace="commons/bar::#sidebar(activeUri='main.html')"></div>

五 文件上传

1 页面表单
<form method="post" action="/upload" enctype="multipart/form-data">
    <input type="file" name="file"><br>
    <input type="submit" value="提交">
</form>
2 文件上传实现
 /**
     * MultipartFile 自动封装上传过来的文件
     * @param email
     * @param username
     * @param headerImg
     * @param photos
     * @return
     */
    @PostMapping("/upload")
    public String upload(@RequestParam("email") String email,
                         @RequestParam("username") String username,
                         @RequestPart("headerImg") MultipartFile headerImg,
                         @RequestPart("photos") MultipartFile[] photos) throws IOException {

        log.info("上传的信息:email={},username={},headerImg={},photos={}",
                email,username,headerImg.getSize(),photos.length);

        if(!headerImg.isEmpty()){
            //保存到文件服务器,OSS服务器
            String originalFilename = headerImg.getOriginalFilename();
            headerImg.transferTo(new File("H:\\cache\\"+originalFilename));
        }

        if(photos.length > 0){
            for (MultipartFile photo : photos) {
                if(!photo.isEmpty()){
                    String originalFilename = photo.getOriginalFilename();
                    photo.transferTo(new File("H:\\cache\\"+originalFilename));
                }
            }
        }


        return "main";
    }
3 总结

(1)表单提交类型为post
(2) 表单的enctype=“multipart/form-data”
(3)表单的 name为file
(4)controller类上的参数类型为 MultipartFile@RequestPart(“headerImg”) MultipartFile headerImg
(5)进行具体文件上传操作

六 Restful风格进行CRUD操作

1 Restful风格与普通风格的区别

在这里插入图片描述

2 项目案例的功能描述

在这里插入图片描述

3 项目案例实现

(1)列表显示
页面代码
对于日期格式可以使用th:text="${#dates.format(emp.birth, ‘yyyy-MM-dd HH:mm’)}"

<div class="table-responsive">
						<table class="table table-striped table-sm">
							<thead>
								<tr>
									<th>#</th>
									<th>lastName</th>
									<th>email</th>
									<th>gender</th>
									<th>department</th>
									<th>birth</th>
									<th>操作</th>
								</tr>
							</thead>
							<tbody>
								<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>
							</tbody>
						</table>
					</div>
				</main>
				<form id="deleteEmpForm"  method="post">
					<input type="hidden" name="_method" value="delete"/>
				</form>
			</div>

(2)添加修改功能
① 添加修改页面合二为一

<body>
		<!--引入抽取的topbar-->
		<!--模板名:会使用thymeleaf的前后缀配置规则进行解析-->
		<div th:replace="commons/bar::topbar"></div>

		<div class="container-fluid">
			<div class="row">
				<!--引入侧边栏-->
				<div th:replace="commons/bar::#sidebar(activeUri='emps')"></div>

				<main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">
					<!--需要区分是员工修改还是添加;-->
					<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>
				</main>
			</div>
		</div>

(3)删除功能

<div class="table-responsive">
						<table class="table table-striped table-sm">
							<thead>
								<tr>
									<th>#</th>
									<th>lastName</th>
									<th>email</th>
									<th>gender</th>
									<th>department</th>
									<th>birth</th>
									<th>操作</th>
								</tr>
							</thead>
							<tbody>
								<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>
							</tbody>
						</table>
					</div>
				</main>
				<form id="deleteEmpForm"  method="post">
					<input type="hidden" name="_method" value="delete"/>
				</form>
			</div>
		</div>
		<script>
			$(".deleteBtn").click(function(){
			    //删除当前员工的
			    $("#deleteEmpForm").attr("action",$(this).attr("del_uri")).submit();
			    return false;
            });
		</script>
	</body>

(4)业务CRUD代码

@Controller
public class EmployeeController {
    @Autowired
    EmployeeDao employeeDao;

    @Autowired
    DepartmentDao departmentDao;

    //查询所有员工返回列表页面
    @GetMapping("/emps")
    public String  list(Model model){
        Collection<Employee> employees = employeeDao.getAll();

        //放在请求域中
        model.addAttribute("emps",employees);
        // thymeleaf默认就会拼串
        // classpath:/templates/xxxx.html
        return "emp/list";
    }

    //来到员工添加页面
    @GetMapping("/emp")
    public String toAddPage(Model model){
        //来到添加页面,查出所有的部门,在页面显示
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("depts",departments);
        return "emp/add";
    }

    //员工添加
    //SpringMVC自动将请求参数和入参对象的属性进行一一绑定;要求请求参数的名字和javaBean入参的对象里面的属性名是一样的
    @PostMapping("/emp")
    public String addEmp(Employee employee){
        //来到员工列表页面

        System.out.println("保存的员工信息:"+employee);
        //保存员工
        employeeDao.save(employee);
        // redirect: 表示重定向到一个地址  /代表当前项目路径
        // forward: 表示转发到一个地址
        return "redirect:/emps";
    }

    //来到修改页面,查出当前员工,在页面回显
    @GetMapping("/emp/{id}")
    public String toEditPage(@PathVariable("id") Integer id,Model model){
        Employee employee = employeeDao.get(id);
        model.addAttribute("emp",employee);

        //页面要显示所有的部门列表
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("depts",departments);
        //回到修改页面(add是一个修改添加二合一的页面);
        return "emp/add";
    }

    //员工修改;需要提交员工id;
    @PutMapping("/emp")
    public String updateEmployee(Employee employee){
        System.out.println("修改的员工数据:"+employee);
        employeeDao.save(employee);
        return "redirect:/emps";
    }

    //员工删除
    @DeleteMapping("/emp/{id}")
    public String deleteEmployee(@PathVariable("id") Integer id){
        employeeDao.delete(id);
        return "redirect:/emps";
    }
}

七 定制错误处理

1 SpringBoot默认的错误处理机制

(1)浏览器默认效果,响应HTML页面
在这里插入图片描述
浏览器发送请求的请求头
在这里插入图片描述
(2)客户端默认效果,响应json数据
在这里插入图片描述
客户端请求的请求头
在这里插入图片描述
(3)原理
参照ErrorMVCAutoConfiguration的错误处理的自动配置
追踪源码,给容器添加了以下核心组件
解析步骤:
① ErrorPageCustomizer:一但系统出现4xx或者5xx之类的错误;ErrorPageCustomizer就会生效(定制错误的响应规则),就会来到
/error请求

@Value("${error.path:/error}")
 private String path = "/error"; //系统出现错误以后来到error请求进行处理;(web.xml注册的错误页面规则)

② BasicErrorController:处理默认的/error请求
会处理浏览器和客户端两种错误情况

@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 = getStatus(request);
		Map<String, Object> model = Collections.unmodifiableMap(getErrorAttributes(request, isIncludeStackTrace(request, MediaType.TEXT_HTML)));
		response.setStatus(status.value());
		//去哪个页面作为错误页面;包含页面地址和页面内容
		ModelAndView modelAndView = resolveErrorView(request, response, status, model);
		return (modelAndView == null ? new ModelAndView("error", model) : modelAndView);
	}
	@RequestMapping
	@ResponseBody//产生json数据,其他客户端来到这个方法处理;
 	public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
		Map<String, Object> body = getErrorAttributes(request,isIncludeStackTrace(request, MediaType.ALL));
		HttpStatus status = getStatus(request);
		return new ResponseEntity<Map<String, Object>>(body, status);
	}

③ DefaultErrorAttrbutes:获取到错误属性,帮我们在页面共享信息

@Override
public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes,
	boolean includeStackTrace) {
	Map<String, Object> errorAttributes = new LinkedHashMap<String, Object>();
	errorAttributes.put("timestamp", new Date());
	addStatus(errorAttributes, requestAttributes);
	addErrorDetails(errorAttributes, requestAttributes, includeStackTrace);
	addPath(errorAttributes, requestAttributes);
	return errorAttributes;
}

④ DefaultErrorViewResolver:解析响应错误页面

protected ModelAndView resolveErrorView(HttpServletRequest request,HttpServletResponse response, HttpStatus status, Map<String, Object> model) {
	//所有的ErrorViewResolver得到ModelAndView
	for (ErrorViewResolver resolver : this.errorViewResolvers) {
		ModelAndView modelAndView = resolver.resolveErrorView(request,status, model);
		if (modelAndView != null) {
			return modelAndView;	
		}
	}
	return null;
}

@Override
public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status,Map<String, Object> model) {
	ModelAndView modelAndView = resolve(String.valueOf(status), model);
	if (modelAndView == null && SERIES_VIEWS.containsKey(status.series())) {
		modelAndView = resolve(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);
	if (provider != null) {
		//模板引擎可用的情况下返回到errorViewName指定的视图地址
		return new ModelAndView(errorViewName, model);
	}
	//模板引擎不可用,就在静态资源文件夹下找errorViewName对应的页面  error/404.html
	return resolveResource(errorViewName, model);
}
2 定制响应错误页面

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

@ControllerAdvice
public class MyExceptionHandler {
	@ResponseBody
	@ExceptionHandler(UserNotExistException.class)
	public Map<String,Object> handleException(Exception e){
		Map<String,Object> map = new HashMap<>();
		map.put("code","user.notexist");
		map.put("message",e.getMessage());
		return map;
	}
}

② 转发到/error进行自适应响应效果处理
问题:不能携带我们自定义的错误信息

@ControllerAdvice
public class MyExceptionHandler {
	@ResponseBody
	@ExceptionHandler(UserNotExistException.class)
	public Map<String,Object> handleException(Exception e, HttpServletRequest request){
		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",500);
		map.put("code","user.notexist");
		map.put("message",e.getMessage());
		//转发到/error
		return "forward:/error";

	}
}

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

//给容器中加入我们自己定义的ErrorAttributes
@Component
public class MyErrorAttributes extends DefaultErrorAttributes {
	@Override
	 public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) {
		 Map<String, Object> map = super.getErrorAttributes(requestAttributes, includeStackTrace);
		 map.put("company","atguigu");
		return map;
	}
}

最终的效果:响应自适应,也可以携带自定义的错误数据
在这里插入图片描述

八 配置嵌入式Servlet容器

1 定制和修改Servlet容器的相关配置

(1)ServerProperties(也是EmbeddedServletContainerCustomizer)修改和server有关的配置

server.port=8081
server.context‐path=/crud
server.tomcat.uri‐encoding=UTF‐8
//通用的Servlet容器设置server.xxx
//Tomcat的设置server.tomcat.xxx

(2)编写一个EmbeddedServletContainerCustomizer:嵌入式的Servlet容器的定制器;来修改Servlet容器的配置

@Configuration
public class MyServerConfig {
    //配置嵌入式的Servlet容器
    @Bean
    public EmbeddedServletContainerCustomizer embeddedServletContainerCustomizer(){
        return new EmbeddedServletContainerCustomizer() {

            //定制嵌入式的Servlet容器相关的规则
            @Override
            public void customize(ConfigurableEmbeddedServletContainer container) {
                container.setPort(8083);
            }
        };
    }

}
2 注册Servlet的三大组件【Servlet、Filter、Listener】

(1)由于SpringBoot默认是以jar包的方式启动嵌入式的Servlet容器来启动SpringBoot的web应用,没有web.xml文件。

注册三大组件用以下方式
ServletRegistrationBean
FilterRegistrationBean
ServletListenerRegistrationBean

@Configuration
public class MyServerConfig {

    //注册三大组件
    @Bean
    public ServletRegistrationBean myServlet(){
        ServletRegistrationBean registrationBean = new ServletRegistrationBean(new MyServlet(),"/myServlet");
        registrationBean.setLoadOnStartup(1);
        return registrationBean;
    }

    @Bean
    public FilterRegistrationBean myFilter(){
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        registrationBean.setFilter(new MyFilter());
        registrationBean.setUrlPatterns(Arrays.asList("/hello","/myServlet"));
        return registrationBean;
    }

    @Bean
    public ServletListenerRegistrationBean myListener(){
        ServletListenerRegistrationBean<MyListener> registrationBean = new ServletListenerRegistrationBean<>(new MyListener());
        return registrationBean;
    }
}

(2)SpringBoot帮我们自动配置SpringMVC的时候,自动的注册SpringMVC的前端控制器DIspatcherServlet;
在DispatcherServletAutoConfiguration中

@Bean(name = DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME)
@ConditionalOnBean(value = DispatcherServlet.class, name =DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)

public ServletRegistrationBean dispatcherServletRegistration(
	DispatcherServlet dispatcherServlet) {
	ServletRegistrationBean registration = new ServletRegistrationBean(
	dispatcherServlet, this.serverProperties.getServletMapping());
	//默认拦截: /  所有请求;包静态资源,但是不拦截jsp请求;	/*会拦截jsp
	//可以通过server.servletPath来修改SpringMVC前端控制器默认拦截的请求路径	
	registration.setName(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME);
	registration.setLoadOnStartup(
	this.webMvcProperties.getServlet().getLoadOnStartup());
	if (this.multipartConfig != null) {
		registration.setMultipartConfig(this.multipartConfig);
	}
	return registration;
}
3 替换其他嵌入式Servlet容器

在这里插入图片描述
(1)默认使用Tomcat

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring‐boot‐starter‐web</artifactId>
	引入web模块默认就是使用嵌入式的Tomcat作为Servlet容器;
</dependency>

(2)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>

(3)Undertow

<!‐‐ 引入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>
4 嵌入式Servlet容器自动配置原理

EmbeddedServletContainerAutoConfiguration:嵌入式的Servlet容器自动配置?

@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
@Configuration
@ConditionalOnWebApplication
@Import(BeanPostProcessorsRegistrar.class)
//导入BeanPostProcessorsRegistrar:Spring注解版;给容器中导入一些组件
//导入了EmbeddedServletContainerCustomizerBeanPostProcessor:
//后置处理器:bean初始化前后(创建完对象,还没赋值赋值)执行初始化工作
public class EmbeddedServletContainerAutoConfiguration {
    
    @Configuration
	@ConditionalOnClass({ Servlet.class, Tomcat.class })//判断当前是否引入了Tomcat依赖;
	@ConditionalOnMissingBean(value = EmbeddedServletContainerFactory.class, search = SearchStrategy.CURRENT)//判断当前容器没有用户自己定义EmbeddedServletContainerFactory:嵌入式的Servlet容器工厂;作用:创建嵌入式的Servlet容器
	public static class EmbeddedTomcat {

		@Bean
		public TomcatEmbeddedServletContainerFactory tomcatEmbeddedServletContainerFactory() {
			return new TomcatEmbeddedServletContainerFactory();
		}

	}
    
    /**
	 * Nested configuration if Jetty is being used.
	 */
	@Configuration
	@ConditionalOnClass({ Servlet.class, Server.class, Loader.class,
			WebAppContext.class })
	@ConditionalOnMissingBean(value = EmbeddedServletContainerFactory.class, search = SearchStrategy.CURRENT)
	public static class EmbeddedJetty {

		@Bean
		public JettyEmbeddedServletContainerFactory jettyEmbeddedServletContainerFactory() {
			return new JettyEmbeddedServletContainerFactory();
		}

	}

	/**
	 * Nested configuration if Undertow is being used.
	 */
	@Configuration
	@ConditionalOnClass({ Servlet.class, Undertow.class, SslClientAuthMode.class })
	@ConditionalOnMissingBean(value = EmbeddedServletContainerFactory.class, search = SearchStrategy.CURRENT)
	public static class EmbeddedUndertow {

		@Bean
		public UndertowEmbeddedServletContainerFactory undertowEmbeddedServletContainerFactory() {
			return new UndertowEmbeddedServletContainerFactory();
		}

	}

(1)EmbeddedServletContainerFactory(嵌入式Servlet容器工厂)

public interface EmbeddedServletContainerFactory {

   //获取嵌入式的Servlet容器
   EmbeddedServletContainer getEmbeddedServletContainer(
         ServletContextInitializer... initializers);

}

在这里插入图片描述
(2)EmbeddedServletContainer:(嵌入式的Servlet容器)
在这里插入图片描述
(3)以TomcatEmbeddedServletContainerFactory为例

public EmbeddedServletContainer getEmbeddedServletContainer(
      ServletContextInitializer... initializers) {
    //创建一个Tomcat
   Tomcat tomcat = new Tomcat();
    
    //配置Tomcat的基本环节
   File baseDir = (this.baseDirectory != null ? this.baseDirectory
         : createTempDir("tomcat"));
   tomcat.setBaseDir(baseDir.getAbsolutePath());
   Connector connector = new Connector(this.protocol);
   tomcat.getService().addConnector(connector);
   customizeConnector(connector);
   tomcat.setConnector(connector);
   tomcat.getHost().setAutoDeploy(false);
   configureEngine(tomcat.getEngine());
   for (Connector additionalConnector : this.additionalTomcatConnectors) {
      tomcat.getService().addConnector(additionalConnector);
   }
   prepareContext(tomcat.getHost(), initializers);
    
    //将配置好的Tomcat传入进去,返回一个EmbeddedServletContainer;并且启动Tomcat服务器
   return getTomcatEmbeddedServletContainer(tomcat);
}

(4)嵌入式容器的配置修改如何生效
① ServerProperties实际也是EmbeddedServletContainerCustomizer、② EmbeddedServletContainerCustomizer
EmbeddedServletContainerCustomizer定制器帮我们修改了Servlet容器的配置
容器中导入了EmbeddedServletContainerCustomizerBeanPostProcessor

//初始化之前
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName)
      throws BeansException {
    //如果当前初始化的是一个ConfigurableEmbeddedServletContainer类型的组件
   if (bean instanceof ConfigurableEmbeddedServletContainer) {
       //
      postProcessBeforeInitialization((ConfigurableEmbeddedServletContainer) bean);
   }
   return bean;
}

private void postProcessBeforeInitialization(
			ConfigurableEmbeddedServletContainer bean) {
    //获取所有的定制器,调用每一个定制器的customize方法来给Servlet容器进行属性赋值;
    for (EmbeddedServletContainerCustomizer customizer : getCustomizers()) {
        customizer.customize(bean);
    }
}

private Collection<EmbeddedServletContainerCustomizer> getCustomizers() {
    if (this.customizers == null) {
        // Look up does not include the parent context
        this.customizers = new ArrayList<EmbeddedServletContainerCustomizer>(
            this.beanFactory
            //从容器中获取所有这葛类型的组件:EmbeddedServletContainerCustomizer
            //定制Servlet容器,给容器中可以添加一个EmbeddedServletContainerCustomizer类型的组件
            .getBeansOfType(EmbeddedServletContainerCustomizer.class,
                            false, false)
            .values());
        Collections.sort(this.customizers, AnnotationAwareOrderComparator.INSTANCE);
        this.customizers = Collections.unmodifiableList(this.customizers);
    }
    return this.customizers;
}

ServerProperties也是定制器

总结:
1)SpringBoot根据导入的依赖情况,给容器中添加相应的EmbeddedServletContainerFactory【TomcatEmbeddedServletContainerFactory】

2)容器中某个组件要创建对象就会惊动后置处理器;EmbeddedServletContainerCustomizerBeanPostProcessor;
只要是嵌入式的Servlet容器工厂,后置处理器就工作;

3)后置处理器,从容器中获取所有的EmbeddedServletContainerCustomizer,调用定制器的定制方法

5 嵌入式Servlet容器启动原理

问题:
什么时候创建嵌入式的Servlet容器工厂?什么时候获取嵌入式的Servlet容器并启动Tomcat;获取嵌入式的Servlet容器工厂
1)SpringBoot应用启动运行run方法

2)refreshContext(context);SpringBoot刷新IOC容器【创建IOC容器对象,并初始化容器,创建容器中的每一个组件】;如果是web应用创建AnnotationConfigEmbeddedWebApplicationContext,否则: AnnotationConfigApplicationContext

3)refresh(context);刷新刚才创建好的ioc容器;

public void refresh() throws BeansException, IllegalStateException {
   synchronized (this.startupShutdownMonitor) {
      // Prepare this context for refreshing.
      prepareRefresh();

      // Tell the subclass to refresh the internal bean factory.
      ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

      // Prepare the bean factory for use in this context.
      prepareBeanFactory(beanFactory);

      try {
         // Allows post-processing of the bean factory in context subclasses.
         postProcessBeanFactory(beanFactory);

         // Invoke factory processors registered as beans in the context.
         invokeBeanFactoryPostProcessors(beanFactory);

         // Register bean processors that intercept bean creation.
         registerBeanPostProcessors(beanFactory);

         // Initialize message source for this context.
         initMessageSource();

         // Initialize event multicaster for this context.
         initApplicationEventMulticaster();

         // Initialize other special beans in specific context subclasses.
         onRefresh();

         // Check for listener beans and register them.
         registerListeners();

         // Instantiate all remaining (non-lazy-init) singletons.
         finishBeanFactoryInitialization(beanFactory);

         // Last step: publish corresponding event.
         finishRefresh();
      }

      catch (BeansException ex) {
         if (logger.isWarnEnabled()) {
            logger.warn("Exception encountered during context initialization - " +
                  "cancelling refresh attempt: " + ex);
         }

         // Destroy already created singletons to avoid dangling resources.
         destroyBeans();

         // Reset 'active' flag.
         cancelRefresh(ex);

         // Propagate exception to caller.
         throw ex;
      }

      finally {
         // Reset common introspection caches in Spring's core, since we
         // might not ever need metadata for singleton beans anymore...
         resetCommonCaches();
      }
   }
}

4) onRefresh(); web的ioc容器重写了onRefresh方法

5)webioc容器会创建嵌入式的Servlet容器;createEmbeddedServletContainer();

6)获取嵌入式的Servlet容器工厂:

EmbeddedServletContainerFactory containerFactory = getEmbeddedServletContainerFactory();

​ 从ioc容器中获取EmbeddedServletContainerFactory 组件;TomcatEmbeddedServletContainerFactory创建对象,后置处理器一看是这个对象,就获取所有的定制器来先定制Servlet容器的相关配置;

7)使用容器工厂获取嵌入式的Servlet容器:this.embeddedServletContainer = containerFactory .getEmbeddedServletContainer(getSelfInitializer());

8)嵌入式的Servlet容器创建对象并启动Servlet容器;

先启动嵌入式的Servlet容器,再将ioc容器中剩下没有创建出的对象获取出来;

IOC容器启动创建嵌入式的Servlet容器

6 使用外置的Servlet容器

(1)嵌入式Servlet容器:应用打成可执行的jar

​ 优点:简单、便携;

​ 缺点:默认不支持JSP、优化定制比较复杂(使用定制器【ServerProperties、自定义EmbeddedServletContainerCustomizer】,自己编写嵌入式Servlet容器的创建工厂【EmbeddedServletContainerFactory】);

(2)外置的Servlet容器:外面安装Tomcat—应用war包的方式打包;
(3)实现步骤
① 必须创建一个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);
   }

}

④ 启动服务器就可以使用
(4)原理

① 说明
jar包:执行SpringBoot主类的main方法,启动ioc容器,创建嵌入式的Servlet容器;

war包:启动服务器,服务器启动SpringBoot应用【SpringBootServletInitializer】,启动ioc容器;
② 规则
1)、服务器启动(web应用启动)会创建当前web应用里面每一个jar包里面ServletContainerInitializer实例:

​ 2)、ServletContainerInitializer的实现放在jar包的META-INF/services文件夹下,有一个名为javax.servlet.ServletContainerInitializer的文件,内容就是ServletContainerInitializer的实现类的全类名

​ 3)、还可以使用@HandlesTypes,在应用启动的时候加载我们感兴趣的类;
③ 流程
1)启动Tomcat

2)在org\springframework\spring-web\4.3.14.RELEASE\spring-web-4.3.14.RELEASE.jar!\META-INF\services\javax.servlet.ServletContainerInitializer中:
Spring的web模块里面有这个文件:org.springframework.web.SpringServletContainerInitializer

3)SpringServletContainerInitializer将@HandlesTypes(WebApplicationInitializer.class)标注的所有这个类型的类都传入到onStartup方法的Set<Class<?>>;为这些WebApplicationInitializer类型的类创建实例;

4)每一个WebApplicationInitializer都调用自己的onStartup;


5)相当于我们的SpringBootServletInitializer的类会被创建对象,并执行onStartup方法

6)SpringBootServletInitializer实例执行onStartup的时候会createRootApplicationContext;创建容器

protected WebApplicationContext createRootApplicationContext(
      ServletContext servletContext) {
    //1、创建SpringApplicationBuilder
   SpringApplicationBuilder builder = createSpringApplicationBuilder();
   StandardServletEnvironment environment = new StandardServletEnvironment();
   environment.initPropertySources(servletContext, null);
   builder.environment(environment);
   builder.main(getClass());
   ApplicationContext parent = getExistingRootWebApplicationContext(servletContext);
   if (parent != null) {
      this.logger.info("Root context already created (using as parent).");
      servletContext.setAttribute(
            WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, null);
      builder.initializers(new ParentContextApplicationContextInitializer(parent));
   }
   builder.initializers(
         new ServletContextApplicationContextInitializer(servletContext));
   builder.contextClass(AnnotationConfigEmbeddedWebApplicationContext.class);
    
    //调用configure方法,子类重写了这个方法,将SpringBoot的主程序类传入了进来
   builder = configure(builder);
    
    //使用builder创建一个Spring应用
   SpringApplication application = builder.build();
   if (application.getSources().isEmpty() && AnnotationUtils
         .findAnnotation(getClass(), Configuration.class) != null) {
      application.getSources().add(getClass());
   }
   Assert.state(!application.getSources().isEmpty(),
         "No SpringApplication sources have been defined. Either override the "
               + "configure method or add an @Configuration annotation");
   // Ensure error pages are registered
   if (this.registerErrorPageFilter) {
      application.getSources().add(ErrorPageFilterConfiguration.class);
   }
    //启动Spring应用
   return run(application);
}

7)Spring的应用就启动并且创建IOC容器

public ConfigurableApplicationContext run(String... args) {
   StopWatch stopWatch = new StopWatch();
   stopWatch.start();
   ConfigurableApplicationContext context = null;
   FailureAnalyzers analyzers = null;
   configureHeadlessProperty();
   SpringApplicationRunListeners listeners = getRunListeners(args);
   listeners.starting();
   try {
      ApplicationArguments applicationArguments = new DefaultApplicationArguments(
            args);
      ConfigurableEnvironment environment = prepareEnvironment(listeners,
            applicationArguments);
      Banner printedBanner = printBanner(environment);
      context = createApplicationContext();
      analyzers = new FailureAnalyzers(context);
      prepareContext(context, environment, listeners, applicationArguments,
            printedBanner);
       
       //刷新IOC容器
      refreshContext(context);
      afterRefresh(context, applicationArguments);
      listeners.finished(context, null);
      stopWatch.stop();
      if (this.logStartupInfo) {
         new StartupInfoLogger(this.mainApplicationClass)
               .logStarted(getApplicationLog(), stopWatch);
      }
      return context;
   }
   catch (Throwable ex) {
      handleRunFailure(context, listeners, analyzers, ex);
      throw new IllegalStateException(ex);
   }
}

启动Servlet容器,再启动SpringBoot应用

SpringBoot资料合集-04【Spring Boot与Web开发】 1.SpringMVC快速使用 1.基于restful http接口 的CURD 2.调用rest http接口 3.通过postman调用 4.通过swagger调用 2.SpringMVC自动配置原理分析 3.定制SpringMvc的自动配置 1.通过WebMvcConfigurer进行扩展 2. Json 开发 3.国际化 4.统一异常处理 4.SpringBoot的嵌入式Servlet容器 1.嵌入式Servlet容器配置修改 2.注册servlet三大组件 3.切换其他嵌入式Servlet容器 4 阅读详情

相关推荐

FPGA实战:手写可配置SPI主机控制器,搞定多外设时序

SPI作为嵌入式系统中应用最广泛的同步串行接口之一,凭借其极简的引脚定义和灵活的传输模式,成为MCU与FPGA开发者必须掌握的基础通信协议。其本质是一种由主机产生时钟并控制数据传输的同步机制,通过CPOL和CPHA的组合可以适配不同外设的采样要求。在FPGA开发中,理解SPI的工作原理能帮助工程师摆脱对IP核的依赖,实现高度定制化的时序控制。使用Verilog设计SPI主机控制器,涉及分频、状态机、边沿检测等核心数字逻辑方法,这些技能同样适用于UART和IIC等其他接口。手写SPI模块不仅能够精确匹配NOR

weixin_33895475的博客 479

基于 Spring Boot 的 Web 三大核心交互案例精讲

本文通过三个经典的 Spring Boot Web 案例,系统讲解了前后端联调的三种核心模式:1. 表单提交:掌握传统 HTML Form 的参数绑定。2. AJAX + Session:实现无刷新登录和服务器端用户状态管理。3. JSON + `@RequestBody`:展示现代 Web 开发中,通过 AJAX 传输 JSON 数据进行复杂数据交互的最佳实践。

此人很懒,什么都留下了...快进来看看吧 5080

SpringBoot实战:高效Web开发

本文介绍了基于Spring Boot的Web开发实践指南,涵盖从基础配置到高级功能的完整开发流程。主要内容包括:1. 核心开发模块:基础配置、RESTful API设计、数据库集成(JPA/MyBatis)、安全认证(Spring Security/JWT)等;2. 典型应用场景:校园管理系统(新闻聚合、实验室预约)、校友信息系统、在线考试平台等具体实现方案;3. 关键技术点:Redis缓存优化、WebSocket实时通信、邮件服务集成、文件处理等实用功能开发;4. 部署与优化:多环境配置、Docker容器

keny-大成的博客 1079

SpringBootWeb案例_03

1.登录功能、2.登录校验、3.异常处理 登录校验中主要介绍了会话技术、JWT令牌、过滤器Filter、拦截器Interceptor,并各个技术注解进行了详细介绍。 最后介绍了全局异常处理。 (黑马程序员2023新版JavaWeb开发教程 P156 Day12-01. 基础登录功能——P171 Day12-16. 异常处理)

qq_59621600的博客 1167

【Spring Boot】Web开发 — Web开发简介

Spring Boot自带的spring-boot-starter-web组件为Web应用开发提供支持,它内嵌的Tomcat以及Spring MVC的依赖使用起来非常方便。Spring Boot创建Web应用非常简单,先创建一个普通的Spring Boot项目,然后修改pom.xml文件将spring-boot-starter-web组件加入项目就可以创建Web应用。我们使用IDEA编辑器打开新创建的Web项目。

衍生星球的博客 3549

Spring-boot web项目实例

Spring-boot web项目实例,前后端数据传递,页面搭建。

SpringBootWeb案例(一)

本文介绍了Tlias智能学习辅助系统的开发准备工作,包括需求分析和环境搭建。系统功能主要分为部门管理和员工管理两大模块,涉及增删改查等操作。环境搭建部分详细说明了创建SpringBoot工程的步骤:1.准备数据库表(dept、emp);2.创建工程并引入web、mybatis、mysql、lombok等依赖;3.配置application.properties;4.构建Mapper、Service、Controller基础结构。文中提供了完整的SQL建表语句和测试数据,以及SpringBoot工程创建过程截

XING的博客 1102

mongoDB 数据莫名其妙的没了

问题 之前没有接触过mongoDB,然后接手一个项目使用的是MongoDB,我就跟着网上的教程搭建一个MongoDB的服务,并运行起来。 一开始没有啥问题,成功的把服务与MongoDB都启动以来,运行也没有问题。但是过了几天,我再次打开时发现,以前的数据神奇的消失了。我还在想,是有什么定时清除的么,还是什么原因导致崩了然后数据就被清理了。 查找原因 第一次遇到我没有在意,重启了一下MongoDB,...

技术熊的博客小窝 1万+

springWeb项目创建实例

//本文章参看BliBli学习总结,感谢提供视频的北京动力节点,本文章仅分享供大家参考学习,没有商业用途,谢谢! SpringWeb项目创建实例 一、web基础功能实现 1、创建数据库springdb,新建表Student 2、新建一个Maven Project 类型:maven-archetype-webapp 3、pom.xml文件中加入依赖 pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://

dave的技术成长之路 715

山东大学FPGA课程实验一 加法器设计

电子设计自动化与FPGA设计,实验一 加法器设计

2503_91283667的博客 878

ESXI 8.0虚拟机安装OpenWRT软路由详细教程

OpenWrt 是嵌入式的 Linux 路由器固件,OpenWrt在稳定运行的同时提供了强大的扩展能力,用户可以完全的定制属于自己的路由系统,满足不一样的个性化需求,本文讲解如何使用ESXI安装OpenWRT,打造属于自己的软路由。本次安装使用的是版本。默认登录信息:用户:root密码:password下载固件:https://github.com/haiibo/OpenWrt/releases/tag/X86_64【CPU配置】:4核心。

qq_27121281的博客 3933

SpringBoot基于Web开发

使用Spring Boot开发Web应用是一个高效且流行的选择,因为它极大地简化了Spring应用的初始搭建以及开发过程。

2301_78122337的博客 679

comsol 多物理场仿真流程-以开关柜为例

1、主要方法 在SolidWorks中对于开关柜的内部与外部结构进行建模,生成能够导入软件计算的3D模型。将SolidWorks中的模型导入comsol软件中,设置参数进行多物理场耦合仿真。 1、具体步骤 删除高压开关柜中对其内部电磁环境无较大影响的结构,如低压测量柜、断路器内部结构等。 导入模型:将厂家提供的3D模型转化为solidworks结构模型。 修复模型:修复已转化模型中转化错误的部分、修复已转化模型中非实体部分、修复已转化模型中重叠实体部分 化简模型:去除过于...

健忘16的博客 7049

spring boot web_SpringBoot-Web开发

Web开发1.1、静态资源访问在我们开发Web应用的时候,需要引用大量的js、css、图片等静态资源。默认配置Spring Boot默认提供静态资源目录位置需置于classpath下,目录名需符合如下规则:/static/public/resources/META-INF/resources举例:我们可以在src/main/resources/目录下创建static,在该位置放置一个图片文件。启动...

weixin_39564755的博客 101

Multisim 14.0元件库下载完整指南:从安装到配置

详细介绍Multisim 14.0版本的元件库下载方法,涵盖安装步骤与后续配置流程,帮助用户快速搭建仿真环境。内容覆盖常见问题及解决方案,让multisim元件库下载更高效、稳定。

weixin_34511754的博客 1951

java毕设:基于springboot的服装搭配推荐系统(springboot+layui+jq+html)1011

项目描述 基于springboot的服装搭配推荐系统: 基于天气服装搭配推荐系统为用户提供未来一周的天气预报情况,并根据预报天气和用户现有的服装进行着装搭配,以及显示未来6小时精确温度数据为用户提供更精确的天气信息便于用户在出行前对自己的着装进行调整,每日用户可以根据自己当日对系统推荐的着装搭配舒适度进行反馈,系统将根据用户的反馈对用户着装的保暖系数进行相应调整,通过多次的反馈和调整形成对用户着装的个体化和精确化的推荐。 本系统可以为用户提供以下服务: 1.未来五天的天气信息显示; 2.未来六小时内天气温度

qq_2537071370的博客 3650

SpringBoot 之 Web开发

SpringBoot开发之 Web开发,其中包括 SpringMVC自动配置、拦截器、视图解析模板与内容协商、定制化原理等功能

京茶吉鹿的博客 4213

反光柱定位算法实战05:Cartographer Landmark融合定位——从原理到实战

本文介绍了CartographerLandmark融合定位方案,该方案将反光柱作为Landmark节点直接融入Cartographer后端优化框架,避免了传统双系统切换导致的位姿跳变问题。文章详细阐述了Landmark的核心原理、数据发布格式(包括ID、坐标、权重等关键字段)以及两种工作模式(建图模式和导航模式)。特别指出组合反光柱作为Landmark可提供方向参考,有效解决镜像歧义问题。该方案通过统一优化框架实现稳定定位,尤其适用于缺乏自然特征的环境,但存在ID匹配不稳定等局限性。整体而言,Cartogr

Studying…… 431

SpringBoot Web开发

介绍了SpringBoot有关Web的所有内容

xry12354的博客 434

米哈游运维面试题及参考答案

Linux 系统运行级别是用于定义系统启动时所需要达到的功能状态。运行级别 0:表示系统停机状态,用于关闭系统,是系统的关机级别。当系统切换到这个级别时,会停止所有的服务和进程,然后关闭系统。运行级别 1:也称为单用户模式。在这个级别下,系统只启动基本的系统服务和必要的进程,仅允许 root 用户登录系统进行维护操作,常用于系统出现故障需要紧急修复的情况,比如修复文件系统错误、重置 root 密码等。运行级别 2:多用户模式,但不支持网络文件系统(NFS)。

大模型大数据攻城狮的专栏 752

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

SpringBoot Web 开发教程(上篇)

组件核心作用Spring 底层核心,提供 IOC、事务、基础 Web、数据访问能力简化 Spring 繁琐 XML 配置,内置服务器,快速搭建独立应用统一各类数据库操作代码规范微服务分布式开发全套工具集项目登录、权限、安全认证框架Web 分为静态资源(页面文件)、动态资源(后端逻辑代码),区分 BS/CS 两种架构;Spring 生态包含 Framework、Boot、Cloud、Security 等组件,SpringBoot 简化配置、快速开发;

mgw1413的博客 273

迈瑞BS系列全自动生化分析仪LIS协议接口手册(内含HL7和ASTM)

迈瑞BS系列全自动生化分析仪LIS协议接口手册,内含HL7和ASTM)

SpringBoot对Web开发的支持!

Spring Boot对Web开发流程提供完整的支持,包括从前端到后台的开发,再到数据库的操作。使用Spring Boot开发Web工程有两种类型:前后端完全分离。这种方式是前端开发者和后端开发者完全分离地进行项目的开发,最后完成前后端的接口对接,这是目前国内一种流行的开发方式。前端负责页面的开发并调用后端接口展示数据,后端只负责提供API接口。使用Spring Boot自带的模板。这种方式适用于小型项目或者全栈开发人员,一般可以选择的模板包括Freemaker和Thymeleaf等。

IT_1024的博客 790

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

springboot resources路径_spring boot与web开发

之前我们学习过传统的SSM,JavaWeb,都有过一定的web开发的基础。但是使用SSM发现配置繁琐,原生的JavaWeb,什么都需要自己写自己封装。到了spring boot这个部分,发现一切都变得简单起来了。这次我们就学习怎么使用spring boot进行web开发!基本原理之前我们就简单的使用这个搭建过环境,并且成功跑通了helloworld!我们再来回顾一下这个过程:1....

weixin_39781783的博客 794

SpringBoot07-SpringBoot Web开发总览

Webjars本质就是以jar包的方式引入我们的静态资源 , 我们以前要导入一个静态资源文件,直接导入即可。使用SpringBoot需要使用Webjars,我们可以去搜索一下:网站:https://www.webjars.org要使用jQuery,我们只要要引入jQuery对应版本的pom依赖即可!

xzh202206的博客 1047

SpringBoot之Web开发

SpringBoot之Web开发 今天给大家带来的是使用SpringBoot来进行Web开发的简介。之前通过ssm使用三层框架(表现层、业务层、数据层)来进行web的开发,SpringBoot对web开发实现更简单的功能实现。 使用SpringBoot; 创建SpringBoot应用,选中我们所需要的模块。 SpringBoot已经默认将这些场景配置好了,只需要在配置文件中指定少量配置就可以运行...

qq_41425382的博客 353

SpringBoot(三):Spring Boot的Web开发

1.Web开发的核心内容主要包括:内嵌servlet容器和SpringMvc 2.SpringBoot的Web开发支持 spring-boot-starter-web为我们提供了嵌入的Tomcat以及SpringMvc的依赖。而Web相关的自动配置存储在spring-boot-autoconfigure.jar的org.springframework.boot.autoconfigure.we...

鹏哥哥Aaa 617
上一篇: SpringBoot之SpringMVC自动配置
下一篇: Docker之安装和常用命令
勉之~
博客等级 码龄9年 575粉丝 251原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值