springboot-web开发
springboot-web开发
-
首页配置
-
首页
扩展springmvc
@Configuration public class MvcConfig implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("index"); registry.addViewController("/index.html").setViewName("index"); } }
-
依赖
<dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf-spring5</artifactId> </dependency> <dependency> <groupId>org.thymeleaf.extras</groupId> <artifactId>thymeleaf-extras-java8time</artifactId> </dependency>
-
约束
xmlns:th="http://www.thymeleaf.org"
-
所有页面的静态资源都交于thymeleaf接管
th:href="@{/css/bootstrap.min.css}"
-
-
页面国际化
-
配置i18n文件
login.tip=请登录 login.username=用户名 login.password=密码 login.remember=记住密码 login.button=登录
spring.messages.basename=i18n.login
-
语言切换
th:href="@{/index.html(lang='zh_CN')}
-
自定义一个组件MyLocaleResolver.java
public class MyLocaleResolver implements LocaleResolver { //解析请求 @Override public Locale resolveLocale(HttpServletRequest request) { //获得lang参数 String language = request.getParameter("lang"); //设置默认 Locale locale = Locale.getDefault(); //language非空判断 if (!StringUtils.isEmpty(language)) { //zh_CN String[] split = language.split("_"); locale = new Locale(split[0], split[1]); } return locale; } @Override public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) { } }
-
在Mvcconfig.java中配置组件
@Bean public LocaleResolver localeResolver(){ return new MyLocaleResolver(); }
-
多语言 #{}
th:text="#{login.tip} th:placeholder="#{login.username} [[#{login.button}]]
-
-
登录+拦截
-
controller
@RequestMapping("/user/login") public String login(@RequestParam("username") String username, @RequestParam("password") String password, Model model, HttpSession session) { if (!StringUtils.isEmpty(username) && "123456".equals(password)) { session.setAttribute("loginUser", username); return "redirect:/main.html"; } else { model.addAttribute("msg", "用户名或密码错误"); return "index"; } }
-
页面跳转和提示
th:action="@{/user/login}"
<span style="color: red">[[${msg}]]</span>
-
未登录用户拦截器
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; } } }
-
配置拦截器到MvcConfig.java中
@Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new LoginHandlerInterceptor()) .addPathPatterns("/**") .excludePathPatterns("/", "/index.html", "/user/login", "/css/**", "/js/**", "/img/**"); }
-
-
提取公共页面
-
提取公共页面
th:fragment="topbar"
-
使用公共页面
<div th:replace="~{commons/commons::topbar}"></div>
-
传递参数
<div th:replace="~{commons/commons::sidebar(active='main.html')}"></div>
-
高亮判断
th:class="${active=='main.html'?'nav-link active':'nav-link'}"
-
-
查询所有员工
-
EmployeeController.java
@Autowired EmployeeDao employeeDao;
@RequestMapping("/emps") public String list(Model model){ Collection<Employee> employeeDaoAll = employeeDao.getAll(); model.addAttribute("emps", employeeDaoAll); return "employee/list"; }
-
list.html列表展示
<table class="table table-striped table-sm"> <thead> <tr> <th>id</th> <th>lastName</th> <th>email</th> <th>gender</th> <th>department</th> <th>birthday</th> <th>操作</th> </tr> </thead> <tbody> <tr th:each="emp:${emps}"> <td th:text="${emp.getId()}"></td> <td th:text="${emp.getLastName()}"></td> <td th:text="${emp.getEmail()}"></td> <td th:text="${emp.getGender()==1?'男':'女'}"></td> <td th:text="${emp.department.getDepartmentName()}"></td> <td th:text="${#dates.format(emp.getBirthday(),'yy-MM-dd HH:mm:ss')}"></td> <td> <button class="btn btn-sm btn-primary">编辑</button> <button class="btn btn-sm btn-danger">删除</button> </td> </tr> </tbody> </table>
-
-
添加员工
-
list.html添加按钮
<a class="btn btn-sm btn-success" th:href="@{/emp}">添加</a>
-
EmployeeController.java页面跳转get方法
//跳转到添加页面 @GetMapping("/emp") public String addPage(Model model) { Collection<Department> department = departmentDao.getDepartment(); model.addAttribute("deps", department); return "employee/add"; }
-
新建add.html套用公共部分, 写入添加表单
<form th:action="@{/emp}" th:method="post"> <div class="form-group"> <label>LastName</label> <input type="text" class="form-control" name="lastName" placeholder="请输入姓名"> </div> <div class="form-group"> <label>Email</label> <input type="email" class="form-control" name="email" placeholder="name@example.com"> </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"> <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"> <label class="form-check-label">女</label> </div> </div> <div class="form-group"> <label>department</label> <select class="form-control" name="department.id"> <!--部门列表--> <option th:each="dep:${deps}" th:text="${dep.getDepartmentName()}" th:value="${dep.getId()}"></option> </select> </div> <div class="form-group"> <label>Birth</label> <input type="text" class="form-control" name="birthday" placeholder="yyyy/MM/dd"> </div> <button type="submit" class="btn btn-primary">添加</button> </form>
-
EmployeeController.java接收并写入数据
@Autowired DepartmentDao departmentDao;
//添加确认后回到员工列表 @PostMapping("/emp") public String addEmp(Employee employee) { employeeDao.save(employee); return "redirect:/emps"; }
-
-
修改员工信息
-
按钮
<a class="btn btn-sm btn-primary" th:href="@{/emp/}+${emp.getId()}">编辑</a>
-
跳转到修改页面
@GetMapping("/emp/{id}") public String updataPage(@PathVariable("id") Integer id, Model model) { Employee employee = employeeDao.getEmployeeById(id); model.addAttribute("emp", employee); Collection<Department> department = departmentDao.getDepartment(); model.addAttribute("deps", department); return "employee/update"; }
-
套用add.html,加入id标识并为表单中填上原值
th:action="@{/emp/update}"
<input th:value="${emp.getId()}" type="hidden" name="id">
th:value="${emp.getLastName()}" th:value="${emp.getEmail()}" th:checked="${emp.getGender()==1}" th:selected="${dep.getId()==emp.getDepartment().getId()}" th:value="${#dates.format(emp.getBirthday(),'yyyy/MM/dd')}"
-
EmployeeController.java完成更新
@PostMapping("/emp/update") public String updataEmp(Employee employee) { System.out.println("debug================================>" + employee); employeeDao.save(employee); return "redirect:/emps"; }
-
-
删除员工
-
按钮
<a class="btn btn-sm btn-danger" th:href="@{/delemp/}+${emp.getId()}">删除</a>
-
controller
@GetMapping("/delemp/{id}") public String deleteEmp(@PathVariable("id") Integer id) { employeeDao.delete(id); return "redirect:/emps"; }
-
-
注销和错误页面
-
公共页面commons.html
<a class="nav-link" th:href="@{/user/logout}">Sign out</a>
-
controller
@RequestMapping("/user/logout") public String logout(HttpSession session) { session.invalidate(); return "redirect:/index.html"; }
-
在templates下建立error目录放入对用的错误页面即可
-