# Spring-Boot-CRUD **Repository Path**: alu4r/Spring-Boot-CRUD ## Basic Information - **Project Name**: Spring-Boot-CRUD - **Description**: Spring-Boot-CRUD员工的增删改查 - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 1 - **Created**: 2019-08-26 - **Last Updated**: 2020-12-19 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # Spring-Boot-CRUD #### 介绍 Spring-Boot-CRUD员工的增删改查,以下是开发笔记,参考尚硅谷老师视频 https://www.bilibili.com/video/av38657363?from=search&seid=182902299250024643 ## RestfulCRUD ### 1)、默认访问首页 ```java //使用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)、国际化 **1)、编写国际化配置文件;** 2)、使用ResourceBundleMessageSource管理国际化资源文件 3)、在页面使用fmt:message取出国际化内容 步骤: 1)、编写国际化配置文件,抽取页面需要显示的国际化消息 2)、SpringBoot自动配置好了管理国际化资源文件的组件; ```java @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)、去页面获取国际化的值; ```html Signin Template for Bootstrap

Please sign in

© 2017-2018

中文 English
``` 效果:根据浏览器语言设置的信息切换了国际化; 原理: ​ 国际化Locale(区域信息对象);LocaleResolver(获取区域信息对象); ~~~java @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; } 默认的就是根据请求头带来的区域信息获取Locale进行国际化 ~~~ 4)、点击链接切换国际化 ```java /** * 可以在连接上携带区域信息 */ 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)、禁用模板引擎的缓存 ``` # 禁用缓存 spring.thymeleaf.cache=false ``` 2)、页面修改完成以后ctrl+f9:重新编译; 登陆错误消息的显示 ```html

``` ### 4)、拦截器进行登陆检查 拦截器 ```java /** * 登陆检查, */ 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 { } } ``` 注册拦截器 ```java //所有的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; } ``` ### 5)、CRUD-员工列表 实验要求: 1)、RestfulCRUD:CRUD满足Rest风格; URI: /资源名称/资源标识 HTTP请求方式区分对资源CRUD操作 | | 普通CRUD(uri来区分操作) | RestfulCRUD | | ---- | ------------------------- | ----------------- | | 查询 | getEmp | emp---GET | | 添加 | addEmp?xxx | emp---POST | | 修改 | updateEmp?id=xxx&xxx=xx | emp/{id}---PUT | | 删除 | deleteEmp?id=1 | emp/{id}---DELETE | 2)、实验的请求架构; | 实验功能 | 请求URI | 请求方式 | | ------------------------------------ | ------- | -------- | | 查询所有员工 | emps | GET | | 查询某个员工(来到修改页面) | emp/1 | GET | | 来到添加页面 | emp | GET | | 添加员工 | emp | POST | | 来到修改页面(查出员工进行信息回显) | emp/1 | GET | | 修改员工 | emp | PUT | | 删除员工 | emp/1 | DELETE | 3)、员工列表: #### thymeleaf公共页面元素抽取 ```html 1、抽取公共片段
© 2011 The Good Thymes Virtual Grocery
2、引入公共片段
~{templatename::selector}:模板名::选择器 ~{templatename::fragmentname}:模板名::片段名 3、默认效果: insert的公共片段在div标签中 如果使用th:insert等属性进行引入,可以不用写~{}: 行内写法可以加上:[[~{}]];[(~{})]; ``` 三种引入公共片段的th属性: **th:insert**:将公共片段整个插入到声明引入的元素中 **th:replace**:将声明引入的元素替换为公共片段 **th:include**:将被引入的片段的内容包含进这个标签中 ```html 引入方式
效果
© 2011 The Good Thymes Virtual Grocery
``` 引入片段的时候传入参数: ```html