虽然WebMvcConfigurerAdapter已经被淘汰,但是仍然可以用这种方式,这样可以更改静态资源的首页加载
//所有的webMvcConfigure组件都会一起起作用
@Bean //将组件注册在容器
public WebMvcConfigurer webMvcConfigurer(){
WebMvcConfigurer configurer = new WebMvcConfigurer() {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("login");
registry.addViewController("/index.html").setViewName("login");
registry.addViewController("main.html").setViewName("dashboard");
}
};
return configurer;
}
使用thymeleaf的方式引入资源,可以在项目更改server.servlet.context-path=/crud时,仍然不会出现问题
<link href="asserts/css/bootstrap.min.css" th:href="@{/webjars/bootstrap/4.3.1/css/bootstrap.css}" rel="stylesheet">
<link href="asserts/css/signin.css" th:href="@{/asserts/css/signin.css}" rel="stylesheet">
国际化:
1)编写国际化配置文件
2)使用ResourceBundleMessageSource管理国际化资源文件
3)在页面使用 fmt:message取出国际化内容
2)springboot自动配置好了管理国际化资源文件的组件
spring.messages.basename=i18n.login
3)去页面取国际化的值
<body class="text-center">
<form class="form-signin" action="dashboard.html">
<img class="mb-4" th:href="@{/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>
<label class="sr-only" th:text="#{login.username}">Username</label>
<input type="text" class="form-control" placeholder="Username" required="" autofocus="" th:placeholder="#{login.username}">
<label class="sr-only" th:text="#{login.password}">Password</label>
<input type="password" class="form-control" placeholder="Password" required="" th:placeholder="#{login.password}">
<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>
4.点击链接切换国际化
MyLocaleResolver类:
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 httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {
}
MyMvcCobfig类:(springboot自动配置,往容器中注入LocaleResolver类,就会使用自己的类)
@Bean
public LocaleResolver localeResolver(){
return new MyLocaleResolver();
}
登陆:
开发期间模板引擎页面修改以后,要实时生效:
1)禁用末班引擎的缓存
#禁用模板引擎的缓存
spring.thymeleaf.cache=false
2)页面修改完成以后按 ctrl+F9,重新编译
//@RequestMapping(value = "/user/login",method = RequestMethod.POST)
@PostMapping(value = "/user/login")
public String login(@RequestParam("username") String username,
@RequestParam("password") String password,
Map<String,Object> map){
if (!StringUtils.isEmpty(username) && "123456".equals(password)){
return "dashboard";
}else {
map.put("msg","用户名或密码错误");
return "login";
}
}
登陆错误提示
<p style="color:red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
拦截器进行登陆检查
LoginHandlerInterceptor类:
/*
* 登陆检查
* */
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;
}
}
MyConfig类:
@Bean
public WebMvcConfigurer webMvcConfigurer(){
WebMvcConfigurer configurer = new WebMvcConfigurer() {
@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) {
registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**")
.excludePathPatterns("/index.html","/","/user/login","/webjars/**","/static/**","/asserts/**");
}
};
5 .CRUD-员工列表
1)RestfulCRUD:CRUD满足Rest风格
URI:/资源名称/资源标识 Http请求方式区分对资源CRUD操作
2)实验的请求架构
3)员工列表
thymeleaf抽取公共页面元素
1.抽取公共片段
<div th:fragment="copy">
</div>
2.引入公共片段
<div th:insert="~{footer :: copy}"></div>
~{templatename :: selector} 模板名 :: 选择器
~{templatename :: fragementname} 模板名::片段名
3.默认效果
inssert的功能标签在div标签中
三种引入功能片段的方式:
th:insert : 将公共片段整个插入声明引入的元素中
th:replace : 将声明引入的元素替换成公共片段
th:include : 将被引入的片段的内容包含进这个标签中
指定请求方式提交,可以配合restful风格编程
spring.mvc.hiddenmethod.filter.enabled=true
<!--发送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}">
使用这种提交方式,可以防止样式更改
<button th:attr="del_uri=@{/emp/}+${emp.id}" type="submit" class="btn btn-sm btn-danger deleteBtn">删除</button>
<form id="deleteEmpForm" method="post">
<input type="hidden" name="_method" value="delete"/>
</form>
<script>
$(".deleteBtn").click(function () {
$("#deleteEmpForm").attr("action",$(this).attr("del_uri")).submit();
return false;
})
</script>
7.错误处理机制
1)springboot默认的错误处理机制
默认效果:
DefaultErrorAttributes:
帮我们在页面共享信息
public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {
Map<String, Object> errorAttributes = new LinkedHashMap();
errorAttributes.put("timestamp", new Date());
this.addStatus(errorAttributes, webRequest);
this.addErrorDetails(errorAttributes, webRequest, includeStackTrace);
this.addPath(errorAttributes, webRequest);
return errorAttributes;
}
BasicErrorController:
@Controller
@RequestMapping({"${server.error.path:${error.path:/error}}"})
public class BasicErrorController extends AbstractErrorController {
public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {//产生html类型数据,浏览器发送数据用这个页面处理
HttpStatus status = this.getStatus(request);
Map<String, Object> model = Collections.unmodifiableMap(this.getErrorAttributes(request, this.isIncludeStackTrace(request, MediaType.TEXT_HTML)));
response.setStatus(status.value());
//去哪个页面作为错误页面,包含页面内容和页面地址
ModelAndView modelAndView = this.resolveErrorView(request, response, status, model);
return modelAndView != null ? modelAndView : new ModelAndView("error", model);
}
@RequestMapping
public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {//产生json类型数据,其他设备用这个方法处理
HttpStatus status = this.getStatus(request);
if (status == HttpStatus.NO_CONTENT) {
return new ResponseEntity(status);
} else {
Map<String, Object> body = this.getErrorAttributes(request, this.isIncludeStackTrace(request, MediaType.ALL));
return new ResponseEntity(body, status);
}
}
ErrorPageCustomizer:系统出现错误以后来到error请求来进行处理
DefaultErrorViewResolver:
public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, Map<String, Object> model) {
ModelAndView modelAndView = this.resolve(String.valueOf(status.value()), model);
if (modelAndView == null && SERIES_VIEWS.containsKey(status.series())) {
modelAndView = this.resolve((String)SERIES_VIEWS.get(status.series()), model);
}
return modelAndView;
}
private ModelAndView resolve(String viewName, Map<String, Object> model) {
//默认springboot可以去找到一个页面
String errorViewName = "error/" + viewName;
//模板引擎可以解析这个页面地址就用模板引擎解析
TemplateAvailabilityProvider provider = this.templateAvailabilityProviders.getProvider(errorViewName, this.applicationContext);
//模板引擎可用的情况下,返回errorViewName指定的页面,模板引擎不可用的情况下,就在静态资源文件夹下找 errorViewName对应的页面
return provider != null ? new ModelAndView(errorViewName, model) : this.resolveResource(errorViewName, model);
}
步骤:
一旦系统出现4xx或5xx之类的错误,ErrorPageCustomizer配置就会生效(定制错误的响应规则);就会来到/error请求,就会被BasicErrorController处理
1)响应页面
protected ModelAndView resolveErrorView(HttpServletRequest request, HttpServletResponse response, HttpStatus status, Map<String, Object> model) {
Iterator var5 = this.errorViewResolvers.iterator();
ModelAndView modelAndView;
do {
if (!var5.hasNext()) {
return null;
}
ErrorViewResolver resolver = (ErrorViewResolver)var5.next();
modelAndView = resolver.resolveErrorView(request, status, model);
} while(modelAndView == null);
return modelAndView;
}
2)如何定制错误响应
1).如何定制错误的页面
1)有模板引擎情况下,error/状态码(将错误页面命名为,错误状态码.html放在error文件夹下)发生此类状态码的错误就会来对应的页面
2)定制错误的json数据
1.自定义异常处理&返回定制json数据
@ControllerAdvice
public class MyExceptionHandler {
@ResponseBody
@ExceptionHandler(UserNotExitException.class)
public Map<String, Object> handleException(Exception e){
Map<String,Object> map = new HashMap();
map.put("code","user.notexit");
map.put("message",e.getMessage());
return map;
}
}//没有自适应
2.转发到/error进行自适应效果处理
@ExceptionHandler(UserNotExitException.class)
public String handleException(Exception e, HttpServletRequest request){
//传入我们自己的状态码
request.setAttribute("javax.servlet.error.status_code",500);
Map<String,Object> map = new HashMap();
map.put("code","user.notexist");
map.put("message",e.getMessage());
return "forward:/error";
}
3.将我们定制的数据发送出去
自定义ErrorAttributes
@Component
public class MyErrorAttributes extends DefaultErrorAttributes {
public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {
Map<String, Object> map = super.getErrorAttributes(webRequest, includeStackTrace);
Map<String,Object> ext = (Map<String, Object>) webRequest.getAttribute("ext", 0);
map.put("company","xiuzhiwu");
map.put("ext",ext);
return map;
}
}