文章目录
1. 快速搭建登录页面
静态文件可以在网上寻找boostrap模板,本次不作提供。
编写对应的controller
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HelloController {
/**
* 首页的视图映射?如果有多个路径都转跳到首页配置较麻烦,可以自定义一个视图映射的配置方法
* @return
*/
@RequestMapping({"/","login.html"})
public String hello(){
return "login";
}
}
上面提到了拓展对应的Spring mvc功能,如果同一个方法有多个对应的路径映射,可以通过配置对应的mvcConfig
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* Create by lanzhou on 2019/7/30
* 扩充Spring MVC功能
*/
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
/**
* 自定义视图映射器
* @param registry
*/
@Override
public void addViewControllers(ViewControllerRegistry registry) {
//表示 路径 /和/index.html都映射到login页面
registry.addViewController("/").setViewName("login");
registry.addViewController("/index.html").setViewName("login");
}
}
配置好对应的登录页面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; 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 for Bootstrap</title>
<!-- Bootstrap core CSS 通过@{}引入对应的路径 -->
<link href="asserts/css/bootstrap.min.css" th:href="@{/webjars/bootstrap/4.2.1/css/bootstrap.css}" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="asserts/css/signin.css" th:href="@{asserts/css/signin.css}" rel="stylesheet">
</head>
<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">Please sign in</h1>
<label class="sr-only">Username</label>
<input type="text" class="form-control" placeholder="Username" required="" autofocus="">
<label class="sr-only">Password</label>
<input type="password" class="form-control" placeholder="Password" required="">
<div class="checkbox mb-3">
<label>
<input type="checkbox" value="remember-me"> Remember me
</label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
<p class="mt-5 mb-3 text-muted">© 2017-2018</p>
<a class="btn btn-sm">中文</a>
<a class="btn btn-sm">English</a>
</form>
</body>
</html>
2. 国际化处理
- 在Resource文件下配置对应的国际化配置文件,分别取对应的文件名。
2. 配置每个对应的文件,Spring boot自动配置好了国际化管理组件。
3. 看一下Spring boot对一个的自动配置国际化的组件。
本质上就是去掉对应的国际代码然后获取对应的文件名。
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
@Conditional(ResourceBundleCondition.class)
@EnableConfigurationProperties
public class MessageSourceAutoConfiguration {
private static final Resource[] NO_RESOURCES = {};
@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;
}
其中message resource类
//配置文件可以直接放在类路径下叫messages.properties;
public class MessageSourceProperties {
private String basename = "messages";
........
4.在对应的页面获取国际化的值。通过#{}
获取对应的值
<h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}">Please sign in</h1>
完整的可以查看如下代码
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; 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 for Bootstrap</title>
<!-- Bootstrap core CSS 通过@{}引入对应的路径 -->
<link href="asserts/css/bootstrap.min.css" th:href="@{/webjars/bootstrap/4.2.1/css/bootstrap.css}" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="asserts/css/signin.css" th:href="@{asserts/css/signin.css}" rel="stylesheet">
</head>
<body class="text-center">
<form class="form-signin" action="dashboard.html">
<img class="mb-4" th:src="@{/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" th:placeholder="#{login.username}" required="" autofocus="">
<label class="sr-only" th:text="#{login.password}">Password</label>
<input type="password" class="form-control" placeholder="Password" th:placeholder="#{login.password}" required="">
<div class="checkbox mb-3">
<label>
<input type="checkbox" value="remember-me"/> [[#{login.remember-me}]]
</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">中文</a>
<a class="btn btn-sm">English</a>
</form>
</body>
</html>
- 直接访问
http://localhost:8082/
是不会成功的。因为我们的配置代替了默认的messages,但是没有在对应的application.properties中做相应的配置。配置好了之后就可以正常访问了。
spring.messages.basename=i18n.login
2.通过链接切换对应的国际化
Spring boot默认对国际化信息做了默认配置,默认是使用http请求头来区分国际地区。
源码如下
@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(prefix = "spring.mvc", name = "locale")
public LocaleResolver localeResolver() {
if (this.mvcProperties.getLocaleResolver() == WebMvcProperties.LocaleResolver.FIXED) {
return new FixedLocaleResolver(this.mvcProperties.getLocale());
}
//new一个AcceptHeaderLocaleResolver对象
AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver();
localeResolver.setDefaultLocale(this.mvcProperties.getLocale());
return localeResolver;
}
AcceptHeaderLocaleResolver源码:如果配置了对应的localResource,则用自己的,没有配置则从请求头中获取。
@Nullable
public Locale getDefaultLocale() {
return this.defaultLocale;
}
@Override
public Locale resolveLocale(HttpServletRequest request) {
Locale defaultLocale = getDefaultLocale();
//获取request的请求头
if (defaultLocale != null && request.getHeader("Accept-Language") == null) {
return defaultLocale;
}
Locale requestLocale = request.getLocale();
List<Locale> supportedLocales = getSupportedLocales();
if (supportedLocales.isEmpty() || supportedLocales.contains(requestLocale)) {
return requestLocale;
}
Locale supportedLocale = findSupportedLocale(request, supportedLocales);
if (supportedLocale != null) {
return supportedLocale;
}
return (defaultLocale != null ? defaultLocale : requestLocale);
}
现在我们可以配置自己的localresource
来做自己的区域化转跳。
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;
/**
* Create by lanzhou on 2019/7/30
* 扩充Spring MVC功能
*/
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
/**
* 自定义视图映射器
* @param registry
*/
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("login");
registry.addViewController("/index.html").setViewName("login");
}
//将对应的组件注入到配置文件中
@Bean
public LocaleResolver localeResolver(){
return new NativeLocalResoler();
}
//利用内部静态类做区域化信息
public static class NativeLocalResoler implements LocaleResolver {
//重写对应的resolveLocale方法
@Override
public Locale resolveLocale(HttpServletRequest request) {
String language = request.getParameter("language");
Locale locale = Locale.getDefault();
if(!StringUtils.isEmpty(language)){
String[] split = language.split("_");
locale = new Locale(split[0],split[1]);
}
return locale;
}
@Override
public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
}
}
}
当然最后肯定得重新配置相应的login.html文件
<a class="btn btn-sm" th:href="@{/login.html(language='zh_CN')}">中文</a>
<a class="btn btn-sm" th:href="@{/login.html(language='en_US')}">English</a>
2. 登陆和登陆拦截器
上面写了做登录页面的国际化
现在可以针对于登录之后的操作
目的:
- 登录正确跳转到对应的页面,并且做简单的用户名和密码校验
- 登陆之后防止表单做重复提交
- 针对登陆做简单拦截器
编写对应的loginController.java
/**
* 登录操作的控制器
*/
@Controller
public class LoginController {
/**
* 如果登录成功则跳转到dashboard页面,并且采用post方法提交表单
* 如果登录出错则提示错误信息到页面
* @param username
* @param password
* @return
*/
@RequestMapping(value = "/user/login", method = RequestMethod.POST)
public String login(@RequestParam("username") String username,
@RequestParam("password") String password,
Map<String, Object> map){
if(!StringUtils.isEmpty(username) && "admin".equals(password)){
//防止重复提交表单可以通过重定向到指定页面
return "redirect:/main.html";
}else{
map.put("msg","用户名不存在或者密码错误,请稍后重试!");
return "login";
}
}
}
静态页面的处理
- 需要在对应的input表单中配置对应name属性,否则后端无法取出对应的字段信心
<form class="form-signin" action="dashboard.html" th:action="@{/user/login}" method="post">
在表单中配置对应的action和请求方法
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; 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 for Bootstrap</title>
<!-- Bootstrap core CSS 通过@{}引入对应的路径 -->
<link href="asserts/css/bootstrap.min.css" th:href="@{/webjars/bootstrap/4.2.1/css/bootstrap.css}" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="asserts/css/signin.css" th:href="@{asserts/css/signin.css}" rel="stylesheet">
</head>
<body class="text-center">
<form class="form-signin" action="dashboard.html" th:action="@{/user/login}" method="post">
<img class="mb-4" th:src="@{/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>
<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" class="form-control" name="username" placeholder="Username" th:placeholder="#{login.username}" required="" autofocus="">
<label class="sr-only" th:text="#{login.password}">Password</label>
<input type="password" name="password" class="form-control" placeholder="Password" th:placeholder="#{login.password}" required="">
<div class="checkbox mb-3">
<label>
<input type="checkbox" value="remember-me"/> [[#{login.remember-me}]]
</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="@{/login.html(language='zh_CN')}">中文</a>
<a class="btn btn-sm" th:href="@{/login.html(language='en_US')}">English</a>
</form>
</body>
</html>
编写对应的自定义mvc配置文件
添加重定向的视图映射registry.addViewController("/main.html").setViewName("dashboard");
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
/**
* 自定义视图映射器
* @param registry
*/
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("login");
registry.addViewController("/index.html").setViewName("login");
registry.addViewController("/main.html").setViewName("dashboard");
}
但是配置了重定向之后,如果用户在浏览器中直接方法http://localhost:8082/main.html
也是可以访问到对应的后台的,那登录的权限校验岂不是失效了?
因此需要对不同的操作做对应的登录拦截器。
具体做法如下
- 配置对应的拦截器。
/**
* 登录拦截器
*/
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 {
}
}
并且将其配置到mvc配置文件中:
添加对应的拦截器,拦截除了"/index.html","/","/user/login"
之外的所有请求
/**
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**").excludePathPatterns("/index.html","/","/user/login");
}
拦截器中的对应的loginUser得在登录的时候通过session传入到后端,因此需要修改对应的loginController
@Controller
public class LoginController {
/**
* 如果登录成功则跳转到dashboard页面,并且采用post方法提交表单
* 如果登录出错则提示错误信息到页面
* @param username
* @param password
* @return
*/
@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, HttpSession session){
if(!StringUtils.isEmpty(username) && "admin".equals(password)){
session.setAttribute("loginUser",username);
//防止重复提交表单可以通过重定向到指定页面
return "redirect:/main.html";
}else{
map.put("msg","用户名不存在或者密码错误,请稍后重试!");
return "login";
}
}
}
至此,登陆及对应的登陆拦截全部完成。
3. CRUD-01查看用户列表
对于入手而言,一般都实现简单的增删改查工作,这一部分主要讲一下如何查。
主要流程:
- 编写对应的controller。需要将后端的数据获取出来传递给前端。通过
model
的方式 - html文件中编写对应的请求路径及动态数据处理方式。同时在页面增加一些按钮。比如添加、删除、编辑。
- 提出一些公共的页面(topbar, sidebar)将其放在commons文件中。
(1)controller
@Controller
public class EmployeeController {
@Autowired
private EmployeeDao employeeDao;
/**
* 查看所有的员工,model给页面传入值
* @param model
* @return
*/
@GetMapping("/emps")
public String list(Model model){
//获取所有的员工,并且其数据通过model的方式返回到页面
Collection<Employee> emps = employeeDao.getAll();
model.addAttribute("emps",emps);
return "emp/list";
}
}
(2)静态页面编写。
增加几个按钮,这些样式都是默认的bootstrap
样式。
<button class="btn btn-sm btn-success">add</button>
<td>
<button class="btn btn-sm btn-primary">edit</button>
<button class="btn btn-sm btn-danger">delete</button>
</td>
<main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">
<a class="btn btn-sm btn-success" href="emp" th:href="@{/emp}">add</a>
<div class="table-responsive">
<table class="table table-striped table-sm">
<thead>
<tr>
<th>id</th>
<th>lastName</th>
<th>email</th>
<th>gender</th>
<th>departmentName</th>
<th>birth</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<!--//从后端传入的值中开始遍历-->
<tr th:each="emp: ${emps}">
<td th:text="${emp.id}" ></td>
<td th:text="${emp.lastName}" ></td>
<td th:text="${emp.email}" ></td>
<td th:text="${emp.gender}==0?'female':'male'" ></td>
<td th:text="${emp.department.departmentName}" ></td>
<td th:text="${#dates.format(emp.birth,'yyyy-mm-dd HH:mm:ss')}" ></td>
<td>
<button class="btn btn-sm btn-primary">edit</button>
<button class="btn btn-sm btn-danger">delete</button>
</td>
</tr>
</tbody>
</table>
</div>
</main>
(3) 提取公共页面
提取公共页面的方式:
<footer th:fragment="copy">
© 2011 The Good Thymes Virtual Grocery
</footer>
引入方式
<div th:insert="footer :: copy"></div>
<div th:replace="footer :: copy"></div> 推荐使用
<div th:include="footer :: copy"></div>
效果
<div>
<footer>
© 2011 The Good Thymes Virtual Grocery
</footer>
</div>
<footer>
© 2011 The Good Thymes Virtual Grocery
</footer>
<div>
© 2011 The Good Thymes Virtual Grocery
</div>
那么到目前为止静态页面主要如下:
访问对应的查看员工列表页面:
http://localhost:8082/emps
4. CRUD-02增加用户
主要的思路如下:
- 编写对一个的controller方法。
- 编写对应的静态文件
(1)编写对应的controller。不同于查看,添加操作其实需要两步,首先进入添加的页面。第二步才是真正的提交操作。
/**
* 添加用户之前先来到添加页面,首先需要查出后端的部门数据
* @return
*/
@GetMapping("/emp")
public String toAddPage(Model model){
//获取所有的部门信息,通过model的方式返回给前端。
Collection<Department> departments = departmentDao.getDepartments();
model.addAttribute("departments",departments);
return "emp/add";
}
(2)增加页面报表的html静态文件
<main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">
<!--提交表单-->
<form th:action="@{/emp}" method="post">
<div class="form-group">
<label>LastName</label>
<input name="lastName" type="text" class="form-control" placeholder="zhangsan" th:value="${employee!=null}?${employee.lastName}">
</div>
<div class="form-group">
<label>Email</label>
<input name="email" type="email" class="form-control" placeholder="zhangsan@atguigu.com" th:value="${employee!=null}?${employee.email}">
</div>
<div class="form-group">
<label>Gender</label><br/>
<div class="form-check form-check-inline" >
<input class="form-check-input" type="radio" name="gender" value="1" th:checked="${employee!=null}?${employee.gender==1}">
<label class="form-check-label">男</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="gender" value="0" th:checked="${employee!=null}?${employee.gender==0}">
<label class="form-check-label">女</label>
</div>
</div>
<div class="form-group" >
<label>department</label>
<select class="form-control" name="department.id">
<!--动态获取后台的部门信息-->
<option th:selected="${employee!=null}?${department.id == employee.department.id}" th:value="${department.getId()}" th:each="department:${departments}" th:text="${department.getDepartmentName()}">department</option>
</select>
</div>
<div class="form-group">
<label>Birth</label>
<input type="text" name="birth" class="form-control" placeholder="2019/09/09" th:value="${employee!=null}?${#dates.format(employee.birth, 'yyyy-MM-dd HH:mm')}">
</div>
<button type="submit" class="btn btn-primary" th:text="${employee !=null }?'修改':'添加'">add</button>
</form>
</main>
(3)增加用户真正的操作
/**
* 添加员工操作。通过post提交的方式表示其是添加操作
* 入参是员工的,SpringMvc会自动将表单中的属性和入参对象属性进行绑定。前提是表单属性和入参属性一致。
* @param employee
* @return
*/
@PostMapping("/emp")
public String add(Employee employee){
employeeDao.save(employee);
//重定向到当前项目路径下的emps请求
return "redirect:/emps";
}
5. CRUD-03修改用户信息
- 增加对应处理的controller
- 共用增加用户的页面
(1)对应处理方法
和增加用户的操作类型,修改用户需要首先进入到对应的修改页面,然后再进行修改操作。
通过前端传入对应的用户Id,查找到相应的用户信息,通过model
方式传入到前端。
/**
* 修改员工信息。之后跳转的页面和添加页面是一样的.
* @param id 从前端路径中获取,可以利用@PathVariable
* @param model 返回给页面信息
* @return
*/
@GetMapping("/emp/{id}")
public String update(@PathVariable("id") Integer id,Model model){
Employee employee = employeeDao.get(id);
model.addAttribute("employee",employee);
Collection<Department> departments = departmentDao.getDepartments();
model.addAttribute("departments",departments);
//回到修改页面
return "emp/add";
}
(2) 真正的更新操作
/**
* 真正的员工修改操作。修改完之后重定向到用户列表。并且从前端传入员工id
* @param employee
* @return
*/
@PutMapping("/emp")
public String update(Employee employee){
employeeDao.save(employee);
return "redirect:/emps";
}
(2) 静态页面加一些判断
<!--发送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}">
6. CRUD-04删除用户
- 配置对应的controller
- 编辑静态html
(1)编写对应的controller
/**
*
* @param id 删除的用户Id
* @return
*/
@DeleteMapping("/emp/{id}")
public String delete(@PathVariable("id") Integer id){
employeeDao.delete(id);
return "redirect:/emps";
}
(2)修改对应html
<form th:action="@{/emp/}+${emp.id}" method="post">
<input type="hidden" name="_method" value="delete"/>
<button type="submit" class="btn btn-sm btn-danger" >delete</button>
</form>