一.配置
01.Tips
1>.RestController的工能就等于Controller + RespondBody的合体
Controller可以理解为返回一个html页面;
RestController可以理解为返回一个json对象
2>.设置请求头前缀:server.servlet.context-path=/crud
3>.下面的两句标注效果一样
// @RequestMapping(value = "/user/login",method = RequestMethod.POST)
@PostMapping(value = "/user/login")
4>.设置指定的日期格式:spring.mvc.date-format=yyyy-MM-dd
5>.thymeleaf中显示日期的时候需要格式化
<td th:text="${#dates.format(emp.birth,'yyyy-MM-dd HH:mm')}"></td>
6>.controller获得请求头中的参数
@GetMapping("/emp/{id}")
public String toEditPage(@PathVariable("id") Integer id,
Model model){……}
7>.发送put请求
<form th:action="@{/emp}" method="post">
<input type="hidden" name="_method" value="put" th:if="${emp!=null}">……
</form>
8>.thymeleaf添加属性
<a th:attr="del_uri=@{/emp/}+${emp.id}" class="btn btn-sm btn-danger deleteBtn">Delete</a>
02.将配置文件中配置的每一个属性的值,映射到这个组件中
@Component :只有这个组件是容器中的组件,才能使用容器提供的ConfigurationProperties功能;
@ConfigurationProperties(prefix="person")
@ConfigurationProperties:告诉SpringBoot将本类中的所有属性和配置文件中相关的配置进行绑定;
* prefix = "person":配置文件中哪个下面的所有属性进行一一映射
03.注解的方式给容器内添加组件
/**
2 * @Configuration:指明当前类是一个配置类,代替spring之前的配置文件
@Configuration
publicclassMyAppConfig{
//通过bean添加组件,将方法的返回值添加到容器中;容器中这个组件默认的id就是方法名
@Bean
public HelloService helloService02(){
System.out.println("配置类@Bean给容器中添加组件了...");
return new HelloService();
}
}
查看是否存在组件 ioc.containsBean("helloService02")
04.多配置文件
我们在主配置文件编写的时候,文件名可以是 application-{profile}.properties/yml 默认使用application.properties的配置;
在配置文件中application.properties指定 spring.profiles.active=dev
05.自动配置原理
xxxxAutoConfigurartion:自动配置类; 给容器中添加组件。
xxxxProperties:封装配置文件中相关属性;
二.日志
01.springboot底层使用slf4j + logback实现的日志管理
使用:
//记录器
Logger logger = LoggerFactory.getLogger(getClass());
@Test
public void contextLoads() {
//System.out.println();
//日志的级别;
//由低到高 trace<debug<info<warn<error
//可以调整输出的日志级别;日志就只会在这个级别以以后的高级别生效 logger.trace("这是trace日志...");
logger.debug("这是debug日志...");
//SpringBoot默认给我们使用的是info级别的,没有指定级别的就用SpringBoot默认规定的级别;root级别
logger.info("这是info日志...");
logger.warn("这是warn日志...");
logger.error("这是error日志...");
}
三.Web
01.springboot对静态文件的映射
1>、所有 /webjars/** ,都去 classpath:/META-INF/resources/webjars/ 找资源; webjars:以jar包的方式引入静态资源,比如前段常用的jquery都可以用webJars来引用,只需要添加maven依赖;
2>、"/**" 访问当前项目的任何资源,都去(静态资源的文件夹)找映射
1 "classpath:/META‐INF/resources/", 2 "classpath:/resources/",
3 "classpath:/static/",
4 "classpath:/public/"
5 "/":当前项目的根路径
localhost:8080/abc === 去静态资源文件夹里面找abc
3>、欢迎页; 静态资源文件夹下的所有index.html页面;被"/**"映射;
localhost:8080/ 找index页面
4>、所有的 **/favicon.ico 都是在静态资源文件下找;
02.Thymeleaf使用
1>.导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring‐boot‐starter‐thymeleaf</artifactId>
</dependency>
2>.只要我们把HTML页面放在classpath:/templates/,thymeleaf就能自动渲染; 使用:
导入thymeleaf的名称空间,就可以写thymeleaf语法
<html lang="en" xmlns:th="http://www.thymeleaf.org">
3>.thymeleaf语法
1>.基本
th:text;改变当前元素里面的文本内容; 行内表达式[[#{}]]
th:任意html属性;来替换原生属性的值
${...}:获取变量值;
*{...}:选择表达式:和${}在功能上是一样;
#{...}:获取国际化内容;
@{...}:定义URL:@{/order/process(execId=${execId},execType='FAST')}
~{...}:片段引用表达式
<div th:insert="~{commons :: main}">...</div>
2>.公共抽取
先用fragment声明
<div th:fragment="copy">公共的部分</div>
然后用insert引用
<div th:insert="~{footer::copy}"></div>
注意:~{templatename::fragmentname}:模板名::片段名
如果使用th:insert等属性进行引入,可以不用写~{}:
行内写法可以加上:[[~{}]];[(~{})];
三种引入公共片段的th属性:
th:insert:将公共片段整个插入到声明引入的元素中
th:replace:将声明引入的元素替换为公共片段
th:include:将被引入的片段的内容包含进这个标签中

03.拓展springMVC
编写一个配置类(@Configuration),是WebMvcConfigurer类型;不能标注@EnableWebMvc; 既保留了所有的自动配置,也能用我们扩展的配置;
//使用WebMvcConfigurer可以来扩展SpringMVC的功能
@Configuration
public class MyMvcConfig implements WebMvcConfigurer{
@
public WebMvcConfigurer webMvcConfigurer(){
WebMvcConfigurer configurer = new WebMvcConfigurer() {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
registry.addViewController("/index.html").setViewName("index");
}
};
return configurer;
}
}
如果想全面接管SpringMVC;
SpringBoot对SpringMVC的自动配置不需要了,所有都是我们自己配置;所有的SpringMVC的自动配置都失效了 我们需要在配置类中添加@EnableWebMvc即可;
注意:
1)、SpringBoot在自动配置很多组件的时候,先看容器中有没有用户自己配置的(@Bean、@Component)如 果有就用用户配置的,如果没有,才自动配置;如果有些组件可以有多个(ViewResolver)将用户配置的和自己默 认的组合起来;
2)、在SpringBoot中会有非常多的xxxConfigurer帮助我们进行扩展配置 3)、在SpringBoot中会有很多的xxxCustomizer帮助我们进行定制配置
04.国际化
1>.编写国际化配置文件,抽取页面需要显示的国际化消息

2>.配置文件中配置国际化文件
#配置国际化
spring.messages.basename=i18n.login
3>.去页面获取国际化的值;
th:text="#{login.tip}"
//如果中文显示乱码 则:FileEncodings中修改编码风格为utf-8,并勾上 native-to-asc...
4>.手动切换语言
//1.在html配置切换按钮
<a class="btn btn-sm" th:href="@{/index.html(l='zh_CN')}">中文</a>
//2.在WebMvcConfigurer配置local
@Bean
public LocaleResolver localeResolver(){
return new MyLocaleResolver();
}
//3.事项MyLocaleResolver
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[] s = l.split("_");
locale = new Locale(s[0], s[1]);
}
return locale;
}
}
05.拦截器:可以实现登录检查
1>.通过判断session中有没有登录信息来拦截,所以在登录成功的时候在session中放入登录用户信息;
@PostMapping(value = "/user/login")
public String login(@RequestParam("username") String username,
@RequestParam("password") String password,
Map<String, Object> map,
HttpSession session){
if (!StringUtils.isEmpty(username) && "111".equals(password)){
// 防止表单重复提交 可以选择重定向 后缀就是重定向后的后缀 而不是/user/login
session.setAttribute("loginUser",username);
return "redirect:/main.html";
}
map.put("msg","username or password is failure!");
return "index";
}
2>.编写拦截器
public class LoginHandlerInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
Object loginUser = request.getSession().getAttribute("loginUser");
if (loginUser == null) {
request.setAttribute("msg","没有权限 请先登录");
// 请求转发
request.getRequestDispatcher("/index.html").forward(request,response);
return false;
} else {
return true;
}
}
}
3>.WebMvcConfigurer中配置拦截器
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**").excludePathPatterns("/","/index.html","/user/login");
}
06.Restful风格的CRUD

1>.查询
<a class="nav-link" href="#" th:href="@{/emps}">
@Autowired
EmployeeDao employeeDao;
@GetMapping("/emps")
public String list(Model model){
Collection<Employee> all = employeeDao.getAll();
// 把员工的结果放在请求域中
model.addAttribute("emps", all);
return "emp/list";
}
07.自定义错误页面
1>、有模板引擎的情况下;error/状态码; 【将错误页面命名为 错误状态码.html 放在模板引擎文件夹里面的error文件夹下】,发生此状态码的错误就会来到 对应的页面; 我们可以使用4xx和5xx作为错误页面的文件名来匹配这种类型的所有错误,精确优先(优先寻找精确的状态码.html);
没有模板引擎(模板引擎找不到这个错误页面),静态资源文件夹下找;
以上都没有错误页面,就是默认来到SpringBoot默认的错误提示页面;
08.配置嵌入式Servlet容器
1>.通过server.来修改
server.port=8081
server.context‐path=/crud
server.tomcat.uri‐encoding=UTF‐8 5
//通用的Servlet容器设置
server.xxx
//Tomcat的设置
server.tomcat.xxx
2>.在webMvcConfigurer编写一个EmbeddedServletContainerCustomizer:嵌入式的Servlet容器的定制器;来修改Servlet容器的 配置
@Bean //一定要将这个定制器加入到容器中
public EmbeddedServletContainerCustomizere mbeddedServletContainerCustomizer(){
return new EmbeddedServletContainerCustomizer() {
//定制嵌入式的Servlet容器相关的规则
@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
container.setPort(8083);
}
};
}
09.注册Servlet三大组件【Servlet、Filter、Listener】
//注册三大组件
@Bean
publicServletRegistrationBean myServlet(){
ServletRegistrationBean registrationBean = new ServletRegistrationBean(new
MyServlet(),"/myServlet");
return registrationBean;
}
@Bean
public FilterRegistrationBean myFilter(){
@Bean
public ServletListenerRegistrationBean myListener(){
ServletListenerRegistrationBean<MyListener> registrationBean = new
ServletListenerRegistrationBean<>(new MyListener());
return registrationBean;
}
网友评论