四、Web开发
1、开发步骤
使用SpringBoot:
- 创建springboot应用,选择我们需要的模块;
- SpringBoot已经默认将这些场景都配置好了,只需要在配置文件中指定少量配置就可以运行起来;
- 自己编写业务代码;
**自动配置原理:**这个场景SpringBoot帮我们配置了什么?能不能修改?能不能扩展?
xxxAutoConfiguration:帮我们给容器中自动配置组件
xxxProperties:配置类来封装配置文件的内容
2、SpringBoot对静态资源的映射规则
@ConfigurationProperties(
prefix = "spring.resources",
ignoreUnknownFields = false
)
public class ResourceProperties {
可以设置和静态资源有关的参数,缓存时间等
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (!this.resourceProperties.isAddMappings()) {
logger.debug("Default resource handling disabled");
} else {
Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
if (!registry.hasMappingForPattern("/webjars/**")) {
this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{"/webjars/**"}).addResourceLocations(new String[]{"classpath:/META-INF/resources/webjars/"}).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
}
String staticPathPattern = this.mvcProperties.getStaticPathPattern();
if (!registry.hasMappingForPattern(staticPathPattern)) {
this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{staticPathPattern}).addResourceLocations(WebMvcAutoConfiguration.getResourceLocations(this.resourceProperties.getStaticLocations())).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
}
}
}
- 所有/webjars/**,都去 /META-INF/resources/webjars/ 找资源;(webjars:以jar包方式引入静态资源)https://www.webjars.org/
localhost:8080/webjars/jquery/3.3.1/jquery.js即可访问文件
<!--引入jquery-webjar-->在访问的时候只需要写webjars下面的资源名称即可
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.3.1</version>
</dependency>
-
"/**"访问当前项目的任何资源(静态资源的文件夹)
"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"
-
欢迎页:静态资源文件夹下所有的index.html页面:被"/**"映射;localhost:8080/ 找index页面
-
所有的**/favicon.ico都是在静态源文件下找
3、模板引擎
jsp、velocity、Freemarker、Thymeleaf
SpringBoot推荐使用的Thymeleaf:语法更简单,功能更强大;
1、引入Themeleaf
<!-- 引入thymeleaf-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2、Thymeleaf使用&语法
只要我们把html页面放在classpath:/templates/,thymeleaf就自动渲染;
使用:
-
导入thymeleaf的名称空间
-
使用thymeleaf语法
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>success</h1> <!--th:text=""将div里面的文本内容设置为指定的值--> <div th:text="${hello}"> </div> </body> </html>
3、语法规则
-
th:text;改变当前元素里面的文本内容
th:任意html属性;用来替换原生属性的值 -
表达式:${…}获取对象的属性、调用方法;使用内置的基本对象;使用内置的工具对象
*{…}选择表达式,和${…}在功能上是一样的;补充:配合th:object使用
;#{…}获取国际化内容
~{…}片段引用表达式
@{…}定义url链接
4、SpringMVC自动配置
1、SpringBoot自动配置好了SpringMVC
以下是SpringBoot对SpringMVC的默认:
-
自动配置了ViewResolver(视图解析器:根据方法的返回值得到视图对象(View),视图对象决定如何渲染(转发页面/重定向页面));COntentNeogotiationResolver:组合所有的视图解析器;如何定制:我们可以自己给容器添加一个视图解析器;自动的将其组合进来;
-
静态首页访问
-
favicon.ico
-
静态资源文件夹路径,webjars
-
自动注册了Converter(转换器)、Formatter(格式化器);自己添加的格式化器、转换器,我们只需要放在容器中即可。
-
HttpMessageConverter:SpringMVC用来转换HTTP请求和响应的。HttpMessageConverter是从容器中确定;获取所有的HttpMessageConverter;自己给容器添加HttpMessageConverter,只需要将自己的组件注册容器中(@Bean,@Component)
-
MessageCodeResolver:定义错误代码生成规则
-
ConfigurableWebBindingInitializer:我们可以配置一个ConfigurableWebBindingInitializer来替换默认的
2、扩展SpringMVC
编写一个配置类(@Configuration),是WebMvcConfigurerAdapter类型;不能标注@EnableWebMvc,既保留了所有的自动配置,也能用我们扩展的配置
//使用WebMvcConfigurer可以扩展SpringMVC的功能
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
//浏览器发送squash请求来到success.html页面
registry.addViewController("/squash").setViewName("success");
}
}
原理:
- WebMvcConfigurer是SpringMVC的自动配置类;
- 在做其他自动配置时会导入;
- 容器中所有的WebMvcConfigurer都会一起起作用;
- 我们的配置类也会被调用;效果:SpringMVC的自动配置和我们的扩展配置都会起作用
3、全面接管SpringMVC
SpringBoot对SpringMVC的自动配置不需要了,所有都是我们自己配置;我们需要在配置类中添加@EnableWebMvc即可;所有的SpingMVC自动配置都失效
5、如何修改SpringBoot的默认配置
模式:
- SpringBoot在自动配置很多组件的时候,先看容器中有没有用户自己配制的(@Bean、@Component),如果由就用用户配置的,如果没有,才自动配置;如果有些组件可以由多个(ViewResolver)将用户配置和自己默认的组合起来;
- 在SpringBoot中会有非常多的xxxConfigurer帮助我们进行扩展配置
6、RestfulCRUD
1.默认访问首页
//使用WebMvcConfigurerAdapter可以来扩展SpringMVC的功能
//@EnableWebMvc 不要接管SpringMVC
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
// super.addViewControllers(registry);
//浏览器发送 /atguigu 请求来到 success
registry.addViewController("/atguigu").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.国际化
2)、使用ResourceBundleMessageSource管理国际化资源文件
3)、在页面使用fmt:message取出国际化内容
步骤:
1)编写国际化配置文件,抽取页面需要显示的国际化消息
2)SpringBoot自动配置好了管理国际化资源文件的组件;
3)去页面获取国际化的值;
效果:根据浏览器语言设置的信息切换了国际化;
原理:
国际化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();
}
}
3.登录
模板引擎页面修改以后,要实时生效:
1) 禁用模板引擎的缓存
2) 页面修改完成之后ctrl+F9重新编译;
登录错误消息的显示:
<p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
3)登录完成之后进行页面重定向(防止刷新页面再次提交表单):
session.setAttribute("loginUser",username);
//登录成功,防止表单重复提交,可以重定向到主页
return "redirect:/main.html";
4.拦截器进行登录检查
//登录检查,
public class LoginHandlerInterceptor implements HandlerInterceptor {
//目标方法执行之前
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler)throws ServletException, IOException {
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 addInterceptors(InterceptorRegistry registry) {
//静态资源: *.css,*.js
//SpringBoot已经做好了静态资源映射
registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**")
.excludePathPatterns("/index.html","/","/user/login");
}
5.CRUD-员工列表
实验要求:
1. RestfulCRUD
CRUD满足Rest风格
URI:/资源名称/资源标识
HTTP请求方式区分对资源CRUD操作
普通CRUD(uri来区分):
查询:getEmp
添加:addEmp?xxx
修改:updateEMP?id=xx
删除:deleteEMP?id=xx
RestfulCRUD:
查询:emp--GET
添加:emp--POST
修改:emp/{id}--PUT
删除:emp/{id}--DELETE
2. 实验的请求架构
查询所有员工:uri:emp,请求方式:GET
查询某个员工(来到修改页面):uri:emp/{id},请求方式:GET
添加员工(来到添加页面):uri:emp,请求方式:GET
添加员工:uri:emp,请求方式:POST
来到修改页面(查出员工进行信息回显):uri:emp/{id},请求方式:GET
修改员工:uri:emp,请求方式:PUT
删除员工:uri:emp/{id},请求方式:DELETE
3. 员工列表:
thymeleaf工共页面元素抽取
-
抽取公共片段
-
引入公共片段
3)默认效果:
insert的功能片段在div标签中
如果使用th:insert等属性进行引入,可以不用写~{};
行内写法可以加上[[~{}]];[(~{})]
三种引入功能片段的th属性:
th:inert将公共片段整个插入到声明引入的元素中
th:replace将声明引入的元素替换为公共片段
th:include将被引入的片段的内容包含进标签中
引入片段的时候传入参数:
<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>
4.CRUD-员工添加
添加页面
提交的数据格式不对:生日:日期;
2017-12-12;2017/12/12;2017.12.12;
日期的格式化;SpringMVC将页面提交的值需要转换为指定的类型;
2017-12-12---Date; 类型转换,格式化;
默认日期是按照/的方式;
redirect:表示重定向到一个地址
forward:表示转发到一个地址
forward:是服务器请求资源,服务器直接访问目标地址的URL,把那个URL的响应内容读取过来,然后把这些内容再发给浏览器,浏览器根本不知道服务器发送的内容是从哪儿来的,所以它的地址栏中还是原来的地址。
redirect:就是服务端根据逻辑,发送一个状态码,告诉浏览器重新去请求那个地址,一般来说浏览器会用刚才请求的所有参数重新请求,所以session,request参数都可以获取
5.员工修改
修改添加二合一表单
#SpringBoot 2.2.X默认不支持put,delete等请求方式的首先需要在配置文件中打开他们,代码如下:
spring.mvc.hiddenmethod.filter.enabled=true
<!--需要区分是员工修改还是添加;-->
<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>
6.员工删除
<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.错误处理机制
- SpringBoot默认的错误处理机制
默认效果:
1. 浏览器,返回一个默认的错误页面
2. 如果是其他客户端,默认相应一个json数据
原理:
可以参照ErrorMvcAutoConfiguration;错误处理的自动配置;
步骤:
一旦系统出现4xx或者5xx之类的错误;ErrorPageCustomizer就会生效(定制错误的相应规划);就会来到/error请求;就会被BasicErrorController处理;
1. 响应页面;去哪个页面是由DefaultErrorViewResolver解析得到
2.
- 如何定制错误相应:
如何定制错误的页面:
有模板引擎的情况下;error/404.html状态码;将错误页面命名为错误状态码.html放在error文件夹下发生此状态码的错误就会来到对应的页面
我们可是使用4xx和5xx作为错误页面的文件名来匹配这种类型的所有错误,优先寻找精确的状态码.html
1)页面能获取的信息:
timestamp:时间戳
status:状态码
error:错误码
exception:异常对象
message:异常消息
errors:JSR303数据校验的错误都在这里
<h1>status:[[${status}]]</h1>
<h1>timestamp:[[${timestamp}]]</h1>
2)没有模板引擎(模板引擎找不到这个错误页面,静态资源文件夹下找;
3)以上都没有错误页面,就是默认来到springboot默认的错误提示页面;
如何定制错误的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","user.notEexist");
map.put("message",e.getMessage());
return map;
}
}
2)转发到/error进行自适应效果处理,一定要设置错误状态码,否则就不会进入错误页面的解析流程
@ExceptionHandler(UserNotExistException.class)
public String handlerException(Exception e, HttpServletRequest request){
//传入我们自己的错误状态码
request.setAttribute("javax.servlet.error.status_code",500);
Map<String,Object> map=new HashMap<>();
map.put("code","user.notEexist");
map.put("message",e.getMessage());
//转发到/error
return "forward:/error";
}
3)将我们的定制数据携带出去
出现错误以后,会来到/error请求,会被BasicErrorController处理,响应出去可以获取的数据是由getAttributes得到的
- 完全编写一个ErrorControoler的实现类,放在容器中
- 页面上能用的数据,或者是json能返回能用的数据都是通过errorAttributes.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("compony","squash");
return map;
}
}
最终效果:响应是自适应的,可以通过定制ErrorAttributes改变需要返回的内容
8、配置嵌入式Servlet容器
Springboot默认使用的是嵌入的Servlet容器(Tomcat);
问题:
1)如何定制和修改Servlet容器的相关配置?
-
修改和server有关的配置(ServletProperties)
server.port=8080
server.context-path=/crud//通用的servlet容器设置 server.xxx //Tomcat设置 server.tomcat.xxx
-
编写一个EmbeddedServletContainerCustomizer:嵌入式servlet容器的定制器;来修改servlet的容器配置
注册Servlet三大组件【Servlet、Filter、Listener】
由于SpringBoot默认是以jar包的方式启动Servlet容器来启动web应用,没有web.xml文件
注册三大组件用以下方式
ServletRegistrationBean
//注册三大组件
@Bean
public ServletRegistrationBean myServlet(){
ServletRegistrationBean registrationBean=new ServletRegistrationBean(new MyServlet(),"/myServlet");
return registrationBean;
}
FilterRegitrationBean
@Bean
public FilterRegistrationBean myFilter(){
FilterRegistrationBean registrationBean=new FilterRegistrationBean();
registrationBean.setFilter(new MyFilter());
registrationBean.setUrlPatterns(Arrays.asList("/hello","/myServlet"));
return registrationBean;
}
ServletListenerRegitrationBean
@Bean
public ServletListenerRegistrationBean myListener(){
ServletListenerRegistrationBean registrationBean=new ServletListenerRegistrationBean(new MyListener());
return registrationBean;
}
SpringBoot帮我们自动配置SpringMvc的时候,自动注册SpringMvc的前端控制器
2)SpringBoot能不能支持其他的Servlet容器
替换为其他嵌入式Servlet容器
默认支持Tomcat、Jetty(长连接)、Undertow(不支持jsp,并发性好)
切换在pom.xml中修改dependency
嵌入式Servlet容器自动配置原理
步骤:
1)、SpringBoot根据导入的依赖情况,给容器中添加相应的EmbeddedServletContainerFactory【TomcatEmbeddedServletContainerFactory】
2)、容器中某个组件要创建对象就会惊动后置处理器;EmbeddedServletContainerCustomizerBeanPostProcessor;
只要是嵌入式的Servlet容器工厂,后置处理器就工作;
3)、后置处理器,从容器中获取所有的EmbeddedServletContainerCustomizer,调用定制器的定制方法
嵌入式Servlet容器启动原理
什么时候创建嵌入式的Servlet容器工厂?什么时候获取嵌入式的Servlet容器并启动Tomcat;
获取嵌入式的Servlet容器工厂:
1)、SpringBoot应用启动运行run方法
2)、refreshContext(context);SpringBoot刷新IOC容器【创建IOC容器对象,并初始化容器,创建容器中的每一个组件】;如果是web应用创建AnnotationConfigEmbeddedWebApplicationContext,否则:AnnotationConfigApplicationContext
3)、refresh(context);刷新刚才创建好的ioc容器;
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容器
使用外置的Servlet容器
嵌入式Servlet容器:应用打成可执行的jar
优点:简单、便携;
缺点:默认不支持JSP、优化定制比较复杂(使用定制器【ServerProperties、自定义EmbeddedServletContainerCustomizer】,自己编写嵌入式Servlet容器的创建工厂【EmbeddedServletContainerFactory】);
外置的Servlet容器:外面安装Tomcat—应用war包的方式打包;
步骤
1)、必须创建一个war项目;(利用idea创建好目录结构)
2)、将嵌入式的Tomcat指定为provided;
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
3)、必须编写一个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容器;