扩展与全面接管 SpringMVC
1、扩展配置
package com.example.demo.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration public class CustomVmcConfig extends WebMvcConfigurerAdapter { @Override public void addViewControllers(ViewControllerRegistry registry) { // super.addViewControllers(registry); // 浏览器的请求 /demo 到视图 /hello registry.addViewController("demo").setViewName("hello"); } }
2、全面接管
增加 @EnableWebMvc
后,自动配置失效
package com.example.demo.config; 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; @EnableWebMvc @Configuration public class CustomVmcConfig extends WebMvcConfigurerAdapter { @Override public void addViewControllers(ViewControllerRegistry registry) { // super.addViewControllers(registry); // 浏览器的请求 /demo 到视图 /hello registry.addViewController("demo").setViewName("hello"); } }
引入资源
模板资源: https://getbootstrap.net/
模板语法: https://www.thymeleaf.org/
webjars: https://www.webjars.org/
目录设置
resources/
templates 模板文件
static 静态文件
首页设置
package com.example.demo.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration public class CustomVmcConfig extends WebMvcConfigurerAdapter { // 设置首页位置,默认访问 public/index.html 没有经过模板引擎处理 @Bean public WebMvcConfigurerAdapter CustomVmcConfig() { WebMvcConfigurerAdapter adapter = new WebMvcConfigurerAdapter() { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("login"); registry.addViewController("/index.html").setViewName("login"); } }; return adapter; } }
国际化
默认根据浏览器语言获取对应国际化信息
1、配置语言文件
resources 资源文件夹下
├── i18n │ ├── login.properties │ ├── login_en_US.properties │ └── login_zh_CN.properties
默认配置 login.properties
login.button=登录~ login.title=登录~ login.username=用户名~ login.password=密码~ login.remember=记住我~
英文配置 login_en_US.properties
login.button=Sign In
login.title=Login
login.username=UserName
login.password=Password
login.remember=Remenber Me
中文配置 login_zh_CN.properties
login.button=登录
login.title=登录
login.username=用户名
login.password=密码
login.remember=记住我
2、配置 application.yml
spring:
messages:
basename: i18n.login
3、模板文件中使用
<button th:text="#{login.button}"></button>
1
根据浏览器请求头设置语言
GET http://localhost:8080/
Accept-Language: en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7
4、自定义国际化处理器
package com.example.demo.component; import org.springframework.util.StringUtils; import org.springframework.web.servlet.LocaleResolver; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Locale; /** * 区域信息解析器 * 自定义国际化参数,支持链接上携带区域信息 */ public class MyLocaleResolver implements LocaleResolver { @Override public Locale resolveLocale(HttpServletRequest request) { String lang = request.getParameter("lang"); Locale locale = Locale.getDefault(); if (!StringUtils.isEmpty(lang)) { String[] list = lang.split("_"); if (list.length == 2) { locale = new Locale(list[0], list[1]); } } return locale; } @Override public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) { } }
启用自定义国际化处理器
package com.example.demo.config; import com.example.demo.component.MyLocaleResolver; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; /** * 配置首页视图 */ @Configuration public class CustomVmcConfig extends WebMvcConfigurerAdapter { @Bean public MyLocaleResolver localeResolver() { return new MyLocaleResolver(); } }
优先获取查询参数返回语言设置
http://localhost:8080/?lang=zh_CN http://localhost:8080/?lang=en_US • 1 • 2
登陆&拦截器
开发期间模板引擎修改要实时生效
禁用模板引擎缓存
重新编译
<!--登录错误消息提示-->
<p
style="color: red;"
th:text="${msg}"
th:if="${not #strings.isEmpty(msg)}"
></p>
拦截器进行登录检查
登录
package com.example.demo.controller; import org.springframework.stereotype.Controller; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import javax.servlet.http.HttpSession; import java.util.Map; @Controller public class LoginController { @PostMapping("/user/login") // 等价于 @RequestMapping(value = "/user/login", method = {RequestMethod.POST}) public String login(@RequestParam("username") String username, @RequestParam("password") String password, Map<String, Object> map, HttpSession session ) { if (!StringUtils.isEmpty(username) && "123".equals(password)) { session.setAttribute("loginUser", username); // 登录成功 防止表单重新提交,做一个重定向 return "redirect:/dashboard.html"; } else { // 登录失败 map.put("msg", "账号或密码不正确"); return "login"; } } }
拦截器
package com.example.demo.component; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 登录检查 */ 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; } } @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 { } }
注册拦截器
package com.example.demo.config; import com.example.demo.component.LoginHandlerInterceptor; import com.example.demo.component.MyLocaleResolver; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; /** * 配置首页视图 */ @Configuration @SuppressWarnings("all") public class CustomVmcConfig extends WebMvcConfigurerAdapter { // 设置首页位置,默认访问 public/index.html 没有经过模板引擎处理 @Bean public WebMvcConfigurerAdapter CustomVmcConfig() { WebMvcConfigurerAdapter adapter = new WebMvcConfigurerAdapter() { /** * 注册视图控制器 * @param registry */ @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("login"); registry.addViewController("/index.html").setViewName("login"); registry.addViewController("/dashboard.html").setViewName("dashboard"); } /** * 注册拦截器 * @param registry */ @Override public void addInterceptors(InterceptorRegistry registry) { // super.addInterceptors(registry); // 拦截任意路径下的所有请求, 排除请求 registry.addInterceptor(new LoginHandlerInterceptor()) .addPathPatterns("/**") .excludePathPatterns("/index.html", "/", "/user/login", "/static/**"); } }; return adapter; } }
Restful CRUD
Rest 风格
URI: /资源/资源标识 HTTP 请求方式区分对资源 CRUD
员工列表-公共页抽取
公共片段抽取
<!-- 1、抽取公共片段 --> <div th:fragment="copy">content</div> <!-- 2、引入公共片段 --> <div th:insert="~{footer::copy}">content</div> <!-- 3、默认效果 --> <!-- insert功能片段在div标签中 -->
~{templateName::selector} 模板名::选择器 ~{templateName::fragmentName}模板名::片段名
3 种方式引入片段
th:insert 插入
th:replace 替换
th:include 引入片段内容
使用th:insert可以不写~{}
转义[[~{}]]
不转义[(~{})]
引入片段时候传入参数
链接高亮&列表完成
redirect 重定向
forward 转发
日期格式化
spring.mvc.format.date: yyyy-MM-dd