一、 默认访问首页
// 所有的webMvcConfigureAdapter组件都会在一起起作用
@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;
}
二、添加国际化
sprngMVC的步骤
- 编写国际化配置文件;
- 使用ResourceBundleMessageSource 管理国际化资源文件
- 在页面使用fmt:message取出国际化内容
springBoot步骤:
- 编写国际化配置文件;抽取需要显示的国际化信息
- springBoot自动配置好了管理国际化资源文件的组件
public class MessageSourceAutoConfiguration {
private static final Resource[] NO_RESOURCES = new Resource[0];
public MessageSourceAutoConfiguration() {
}
@Bean
@ConfigurationProperties(
prefix = "spring.messages"
)
// 获取资源文件属性
public MessageSourceProperties messageSourceProperties() {
return new MessageSourceProperties();
}
@Bean
public MessageSource messageSource(MessageSourceProperties properties) {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
if (StringUtils.hasText(properties.getBasename())) {
// 设置国际化资源文件的基础名(去掉国家代码的)
messageSource.setBasenames(StringUtils.commaDelimitedListToStringArray(StringUtils.trimAllWhitespace(properties.getBasename())));
}
if (properties.getEncoding() != null) {
messageSource.setDefaultEncoding(properties.getEncoding().name());
}
messageSource.setFallbackToSystemLocale(properties.isFallbackToSystemLocale());
Duration cacheDuration = properties.getCacheDuration();
if (cacheDuration != null) {
messageSource.setCacheMillis(cacheDuration.toMillis());
}
messageSource.setAlwaysUseMessageFormat(properties.isAlwaysUseMessageFormat());
messageSource.setUseCodeAsDefaultMessage(properties.isUseCodeAsDefaultMessage());
return messageSource;
}
public class MessageSourceProperties {
private String basename = "messages";//我们配置文件文件可以直接放在类路径下的messages.properties;
private Charset encoding;
@DurationUnit(ChronoUnit.SECONDS)
private Duration cacheDuration;
private boolean fallbackToSystemLocale;
private boolean alwaysUseMessageFormat;
private boolean useCodeAsDefaultMessage;
public MessageSourceProperties() {
this.encoding = StandardCharsets.UTF_8;
this.fallbackToSystemLocale = true;
this.alwaysUseMessageFormat = false;
this.useCodeAsDefaultMessage = false;
}
3.去页面获取国际化的值
修改文件encoding编码
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>Signin Template · Bootstrap</title>
<!--<link rel="canonical" href="https://getbootstrap.com/docs/4.3/examples/sign-in/">-->
<!-- Bootstrap core CSS -->
<link href="css/bootstrap.css" th:href="@{/webjars/bootstrap/4.0.0/css/bootstrap.css}" rel="stylesheet" crossorigin="anonymous">
<style>
.bd-placeholder-img {
font-size: 1.125rem;
text-anchor: middle;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
@media (min-width: 768px) {
.bd-placeholder-img-lg {
font-size: 3.5rem;
}
}
</style>
<!-- Custom styles for this template -->
<link href="css/signin.css" th:href="@{/css/signin.css}" rel="stylesheet">
<script src="js/prompt.js" th:src="@{/js/prompt.js}"></script></head>
<body class="text-center">
<form class="form-signin" action="mainPage.html" th:action="@{/user/login}" method="post">
<img class="mb-4" src="img/bootstrap-solid.svg" th:src="@{/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>
<p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
<label class="sr-only" th:text="#{login.username}">UserName</label>
<input type="text" name="username" id="username" class="form-control" placeholder="UserName" th:placeholder="#{login.username}" required="" autofocus="">
<label class="sr-only" th:text="#{login.password}">Password</label>
<input type="password" name="password" id="inputPassword" class="form-control" placeholder="Password" th:placeholder="#{login.password}" required="">
<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-2019</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>
</body></html>
效果是根据浏览器的语言设置的信息切换国际化;
原理:
国际化Locale(区域信息对象);LocaleResolver(获取区域信息对象)
@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(
prefix = "spring.mvc",
name = {"locale"}
)
public LocaleResolver localeResolver() {
if (this.mvcProperties.getLocaleResolver() == org.springframework.boot.autoconfigure.web.servlet.WebMvcProperties.LocaleResolver.FIXED) {
return new FixedLocaleResolver(this.mvcProperties.getLocale());
} else {
AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver();
localeResolver.setDefaultLocale(this.mvcProperties.getLocale());
return localeResolver;
}
}
// 默认的区域解析器是根据浏览器请求头中获取
我们可以自己写一个国际化解析器
/**
* 可以在连接上携带上区域信息
*/
public class MyLocaleResolver implements LocaleResolver{
@Override
public Locale resolveLocale(HttpServletRequest request) {
// 获取去请求中的l参数
String l = request.getParameter("l");
// 初始化默认的Locale
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, @Nullable HttpServletResponse httpServletResponse, @Nullable Locale locale) {
}
}
// 将自己写的区域信息解析器注册到容器中
@Bean
public LocaleResolver localeResolver(){
return new MyLocaleResolver();
}
登陆
开发期间模板引擎页面修改以后,要实时生效
- 禁用模板引擎的缓存
#禁用缓存
spring.thymeleaf.cache=false
- 页面修改完成ctrl+f9;重新编译;
- 拦截器实现
- 实现HandlerInterceptor接口
//目标方法执行之前 @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { return true; }
CRUD
普通CRUD(uri来区分操作) | RestulCRUD | |
---|---|---|
查询 | getEmp | emp —GET |
添加 | addEmp?xxx | emp —POST |
修改 | updateEmp?id=xxx&xxx | emp/{id} —PUT |
删除 | delectEmp?id=1 | emp/{id} —DELECT |
实验请求架构:
实验功能 | 请求url | 请求方式 |
---|---|---|
查询所有员工 | emps | GET |
查询某个员工(来到求改页面) | emp/1 | GET |
来到添加页面 | emp | GET |
添加员工 | emp | POST |
来到修改页面 | emp/1 | GET |
修改员工 | emp | PUT |
删除员工 | emp/1 | DELECT |
修改员工数据时,put请求在表单中的使用:
高版本的springboot 的HiddenHttpMethodFilter默认时关闭的需要
在application.xml中添加配置
#启动HiddenHttpMethodFilter 可以使用put请求
spring.mvc.hiddenmethod.filter.enabled=true
<!--发送put请求修改员工数据-->
<!--1.Spring MVC种配置HiddenHttpMethodFilter 这一步springboot已经自动配置好-->
<!--2.页面创建一个post表单-->
<!--3.创建input项,name="_method" 值就是我们指定的请求方式-->
<form th:action="@{/emp}" method="post">
<!--发送put请求修改员工数据-->
<!--1.Spring MVC种配置HiddenHttpMethodFilter-->
<!--2.页面创建一个post表单-->
<!--3.创建input项,name="_method" 值就是我们指定的请求方式-->
<input type="hidden" name="_method" value="put" th:if="${emp!=null}">
删除员工
方式一:
通过将button按钮放到form表单中进行提交
<td >
<a class="btn btn-sm btn-primary" th:href="@{/emp/}+${emp.id}">编辑</a>
<form id="deleteEmpForm" th:action="@{/emp/}+${emp.id}" method="post">
<input type="hidden" name="_method" value="delete">
<button type="submit" class="btn btn-sm btn-danger">删除</button>
</form>
</td>
方式二:通过js在提交给form表单;将form表单放到表单外面;减少form的个数。
<!--- 在table中的删除按钮----->
<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>
<!-------删除的form表单放在table外面 所有数据公用这一个form--->
<form id="deleteEmpForm" method="post">
<input type="hidden" name="_method" value="delete">
</form>
<!---------bootStrap core javascript ---------->
<script type="text/javascript" th:src="@{/webjars/jquery/3.3.1/jquery.js}"></script>
<script type="text/javascript" th:src="@{/webjars/bootstrap/4.0.0/js/bootstrap.js}"></script>
<script>
$(".deleteBtn").click(function () {
// 删除当前员工
$('#deleteEmpForm').attr('action',$(this).attr("del_uri")).submit();
return false;
})
</script>