zoukankan      html  css  js  c++  java
  • springboot-web开发

    springboot-web开发

    1. 首页配置

      1. 首页

        扩展springmvc

        @Configuration
        public class MvcConfig implements WebMvcConfigurer {
            @Override
            public void addViewControllers(ViewControllerRegistry registry) {
                registry.addViewController("/").setViewName("index");
               	registry.addViewController("/index.html").setViewName("index");
            }
        }
        
      2. 依赖

        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring5</artifactId>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-java8time</artifactId>
        </dependency>
        
      3. 约束

        xmlns:th="http://www.thymeleaf.org"
        
      4. 所有页面的静态资源都交于thymeleaf接管

        th:href="@{/css/bootstrap.min.css}"
        
    2. 页面国际化

      1. 配置i18n文件

        login.tip=请登录
        login.username=用户名
        login.password=密码
        login.remember=记住密码
        login.button=登录
        
        spring.messages.basename=i18n.login
        
      2. 语言切换

        th:href="@{/index.html(lang='zh_CN')}
        
      3. 自定义一个组件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) {
            }
        }
        
      4. 在Mvcconfig.java中配置组件

        @Bean
        public LocaleResolver localeResolver(){
            return new MyLocaleResolver();
        }
        
      5. 多语言 #{}

        th:text="#{login.tip}
        th:placeholder="#{login.username}
        [[#{login.button}]]
        
    3. 登录+拦截

      1. 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";
            }
        }
        
      2. 页面跳转和提示

        th:action="@{/user/login}"
        
        <span style="color: red">[[${msg}]]</span>
        
      3. 未登录用户拦截器

        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;
                }
            }
        }
        
      4. 配置拦截器到MvcConfig.java中

        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(new LoginHandlerInterceptor())
                    .addPathPatterns("/**")
                    .excludePathPatterns("/", "/index.html", "/user/login", "/css/**", "/js/**", "/img/**");
        }
        
    4. 提取公共页面

      1. 提取公共页面

        th:fragment="topbar"
        
      2. 使用公共页面

        <div th:replace="~{commons/commons::topbar}"></div>
        
      3. 传递参数

        <div th:replace="~{commons/commons::sidebar(active='main.html')}"></div>
        
      4. 高亮判断

        th:class="${active=='main.html'?'nav-link active':'nav-link'}" 
        
    5. 查询所有员工

      1. EmployeeController.java

        @Autowired
        EmployeeDao employeeDao;
        
        @RequestMapping("/emps")
        public String list(Model model){
            Collection<Employee> employeeDaoAll = employeeDao.getAll();
            model.addAttribute("emps", employeeDaoAll);
            return "employee/list";
        }
        
      2. 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>
        
    6. 添加员工

      1. list.html添加按钮

        <a class="btn btn-sm btn-success" th:href="@{/emp}">添加</a>
        
      2. EmployeeController.java页面跳转get方法

        //跳转到添加页面
        @GetMapping("/emp")
        public String addPage(Model model) {
            Collection<Department> department = departmentDao.getDepartment();
            model.addAttribute("deps", department);
            return "employee/add";
        }
        
      3. 新建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>
        
      4. EmployeeController.java接收并写入数据

        @Autowired
        DepartmentDao departmentDao;
        
        //添加确认后回到员工列表
        @PostMapping("/emp")
        public String addEmp(Employee employee) {
            employeeDao.save(employee);
            return "redirect:/emps";
        }
        
    7. 修改员工信息

      1. 按钮

        <a class="btn btn-sm btn-primary" th:href="@{/emp/}+${emp.getId()}">编辑</a>
        
      2. 跳转到修改页面

        @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";
        }
        
      3. 套用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')}"
        
      4. EmployeeController.java完成更新

        @PostMapping("/emp/update")
        public String updataEmp(Employee employee) {
            System.out.println("debug================================>" + employee);
            employeeDao.save(employee);
            return "redirect:/emps";
        }
        
    8. 删除员工

      1. 按钮

        <a class="btn btn-sm btn-danger" th:href="@{/delemp/}+${emp.getId()}">删除</a>
        
      2. controller

        @GetMapping("/delemp/{id}")
        public String deleteEmp(@PathVariable("id") Integer id) {
            employeeDao.delete(id);
            return "redirect:/emps";
        }
        
    9. 注销和错误页面

      1. 公共页面commons.html

        <a class="nav-link" th:href="@{/user/logout}">Sign out</a>
        
      2. controller

        @RequestMapping("/user/logout")
        public String logout(HttpSession session) {
            session.invalidate();
            return "redirect:/index.html";
        }
        
      3. 在templates下建立error目录放入对用的错误页面即可

  • 相关阅读:
    『原创』一个基于Win CE 5.0的Txt文件阅读器
    『原创』来电防火墙源码
    『转载』NetBeans开发J2ME手机程序之——文件浏览器
    c#文件分割与合并 part 2
    『原创』c#下的分词程序(准原创)
    『转载』在vs2008(2005)winform中,打开office文档
    『原创』老范的来电防火墙v1.0发布了(图文)
    『原创』手把手教你用c#做个Splash(启动屏幕)
    DLL简单示例
    虚函数与多态
  • 原文地址:https://www.cnblogs.com/pinked/p/12357684.html
Copyright © 2011-2022 走看看