0


SpringBoot模拟数据库开发

Spring boot模拟数据库开发

准备工作

  • 把准备的后台模板准备好,地址:
  • 链接:https://pan.baidu.com/s/13mNCQ18_nl6DHpxfKl4ZFw 提取码:love
  • 导所需要的依赖<!--thymleaf引擎导入--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency><!--官方导入--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!--lombok导入--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency>
  1. 然后把网页模板都导入到templates文件夹下在这里插入图片描述

2.把静态资源导入到static文件夹下

在这里插入图片描述

3.模拟数据库操作

  1. pojo层创建@Data@AllArgsConstructor@NoArgsConstructor//部门表publicclassDevelopment{privateInteger id;privateString developmentName;}@Data@NoArgsConstructor//员工表publicclassEmployee{privateInteger id;privateString lastName;privateString email;privateInteger gender;privateDevelopment development;privateDate birth;publicEmployee(Integer id,String lastName,String email,Integer gender,Development development){this.id = id;this.lastName = lastName;this.email = email;this.gender = gender;this.development = development;this.birth=newDate();}}
  2. dao层创建@RepositorypublicclassDevelopmentDao{//模拟数据库管理数据publicstaticMap<Integer,Development> developments=null;static{ developments=newHashMap<Integer,Development>(); developments.put(101,(newDevelopment(101,"教育部"))); developments.put(102,(newDevelopment(102,"人事部"))); developments.put(103,(newDevelopment(103,"运营部"))); developments.put(104,(newDevelopment(104,"技术部"))); developments.put(105,(newDevelopment(105,"后勤部")));}//获取部门表的所有信息publicCollection<Development>getDevelopmentAll(){return developments.values();}//通过获取id获得部门的信息publicDevelopmentgetDevelopmentById(Integer id){return developments.get(id);}}``````@RepositorypublicclassEmployeeDao{//模拟数据管理员工表publicstaticMap<Integer,Employee> employees=null;static{ employees=newHashMap<Integer,Employee>(); employees.put(1001,newEmployee(1001,"Aa","[email protected]",0,newDevelopment(101,"教育部"))); employees.put(1002,newEmployee(1002,"Bb","[email protected]",1,newDevelopment(102,"人事部"))); employees.put(1003,newEmployee(1003,"Cc","[email protected]",0,newDevelopment(103,"运营部"))); employees.put(1004,newEmployee(1004,"Dd","[email protected]",1,newDevelopment(104,"技术部"))); employees.put(1005,newEmployee(1005,"Ee","[email protected]",0,newDevelopment(105,"后勤部")));}//获得所有员工的信息publicCollection<Employee>getEmployeeAll(){return employees.values();}//根据id获取员工的信息publicEmployeegetEmployeeById(Integer id){return employees.get(id);}//主键自增publicstaticInteger initEmployeeid=1006;//增加一个员工publicvoidaddEmployee(Employee employee){//如果添加的员工id为空if(employee.getId()==null){//那么就自动+1 employee.setId(initEmployeeid++);}//把所添加的信息添加到数据库中 employees.put(employee.getId(),employee);}//根据id删除一个员工publicvoiddeleteEmployee(Integer id){ employees.remove(id);}}

首页实现

  1. 扩展首页的mvc配置//添加一个视图控制器,来控制跳转的方式@OverridepublicvoidaddViewControllers(ViewControllerRegistry registry){ registry.addViewController("/").setViewName("login"); registry.addViewController("/index.html").setViewName("login"); registry.addViewController("/main.html").setViewName("index");}
  2. 需要关闭thymleaf引擎的缓存机制#关闭thymleaf缓存机制spring.thymeleaf.cache=false
  3. 网页表头需要添加thymleaf的命名空间xmlns:th="http://www.thymeleaf.org"
  4. 需要把网页改成thymleaf格式<!-- Bootstrap core CSS --><linkth:href="@{/css/bootstrap.min.css}"rel="stylesheet"><!-- Custom styles for this template --><linkth:href="@{/css/signin.css}"rel="stylesheet">所有页面的静态资源都需要使用thymleaf接管,其他也都是需要改,在线的连接不需要改

国际化

  • 首先需要修改File Encodings

在这里插入图片描述

  • 创建i18n文件夹,并且创建login.properties

在这里插入图片描述

在这里插入图片描述

  • 把网页修改成国际化<formclass="form-signin"th:action="@{/user/login}"><imgclass="mb-4"th:src="@{/img/bootstrap-solid.svg}"alt=""width="72"height="72"><h1class="h3 mb-3 font-weight-normal"th:text="#{login.tip}">Please sign in</h1><pstyle="color: red;"th:text="${msg}"th:if="${not #strings.isEmpty(msg)}"></p><labelclass="sr-only">[[#{login.username}]]</label><inputname="username"type="text"class="form-control"th:placeholder="#{login.username}"required=""autofocus=""><labelclass="sr-only">[[#{login.password}]]</label><inputname="password"type="password"class="form-control"th:placeholder="#{login.password}"required=""><divclass="checkbox mb-3"><label><inputtype="checkbox"value="remember-me"> [[#{login.remember}]] </label></div><buttonclass="btn btn-lg btn-primary btn-block"type="submit">[[#{login.btn}]]</button><pclass="mt-5 mb-3 text-muted">© 2017-2018</p><aclass="btn btn-sm"th:href="@{/index.html(l='zh_CN')}">中文</a><aclass="btn btn-sm"th:href="@{/index.html(l='en_US')}">English</a></form>th:text:#{}来配置国际化信息
  • 自定义一个组件LocaleResolver来控制语言的国际化//解析请求@OverridepublicLocaleresolveLocale(HttpServletRequest request){//获取语言的请求String language = request.getParameter("l");Locale locale =Locale.getDefault();//如果没有所选的语言就是默认的//如果获取的链接携带了国际化的参数//如果选择的语言不为空if(!StringUtils.isEmpty(language)){//zh_CNString[] split = language.split("_");//国家,地区 locale =newLocale(split[0], split[1]);}return locale;}
  • 然后将自定义组件配置到spring容器中,也就是@Bean``````//这个是为了实现国际化publicLocaleResolverlocalResolver(){returnnewMyLocalResolver();}

登录功能实现

因为数据库是伪造的,所以登录的时候无论什么都能登录进去

  • 写一个登录的控制器LoginController``````@ControllerpublicclassLoginController{@RequestMapping("/user/login")publicStringlogin(@RequestParam("username")String username,@RequestParam("password")String pwd,Model model,HttpSession session){System.out.println("debug==>"+username);if(!StringUtils.isEmpty(username)&&"123456".equals(pwd)){ session.setAttribute("loginUser", username);return"redirect:/main.html";}else{ model.addAttribute("msg","密码或者用户名输入错误,请重新登录!");return"login";}}}
  • 由于没有提示,所以需要在前端加一个标签来提示<!--如果msg显示为空,就会提示为空--><pstyle="color: red;"th:text="${msg}"th:if="${not #strings.isEmpty(msg)}"></p>展示登录页面

在这里插入图片描述

登录拦截器

  • 创建一个拦截器方法LoginHandlerInterceptor,为了拦截那些没有登录就进入主界面的操作publicclassLoginHandlerInterceptorimplementsHandlerInterceptor{@OverridepublicbooleanpreHandle(HttpServletRequest request,HttpServletResponse response,Object handler)throwsException{//登录成功后,应该有用户的sessionObject loginUser = request.getSession().getAttribute("loginUser");if(loginUser==null){//没有登录 request.setAttribute("msg","没有权限,请先登录"); request.getRequestDispatcher("/index.html").forward(request,response);returnfalse;}else{returntrue;}}}
  • LoginHandlerInterceptor配置到spring容器中,@Bean.//添加一个拦截器,为了拦截那些没有登录就进入主界面的操作@OverridepublicvoidaddInterceptors(InterceptorRegistry registry){ registry.addInterceptor(newLoginHandlerInterceptor()).addPathPatterns("/**").excludePathPatterns("/","/index.html","/user/login","css/**","fonts/**","images/**","js/**","lib/**");}
  • 展示登录页面

在这里插入图片描述

展示员工列表

  • 把所有多余的代码都写到一个网页中commons.html``````<!DOCTYPEhtml><htmllang="en"xmlns:th="http://www.thymeleaf.org"><!--顶部栏--><navclass="navbar navbar-dark sticky-top bg-dark flex-md-nowrap p-0"th:fragment="top"><aclass="navbar-brand col-sm-3 col-md-2 mr-0"href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">[[${session.loginUser}]]</a><inputclass="form-control form-control-dark w-100"type="text"placeholder="Search"aria-label="Search"><ulclass="navbar-nav px-3"><liclass="nav-item text-nowrap"><aclass="nav-link"th:href="@{/user/logout}">注销</a></li></ul></nav><!--侧边栏--><navclass="col-md-2 d-none d-md-block bg-light sidebar"th:fragment="sidebar"><divclass="sidebar-sticky"><ulclass="nav flex-column"><liclass="nav-item"><ath:class="${active=='dashboard.html'?'nav-link active':'nav-link'}"th:href="@{/dashboard.html}"><svgxmlns="http://www.w3.org/2000/svg"width="24"height="24"viewBox="0 0 24 24"fill="none"stroke="currentColor"stroke-width="2"stroke-linecap="round"stroke-linejoin="round"class="feather feather-home"><pathd="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"></path><polylinepoints="9 22 9 12 15 12 15 22"></polyline></svg> 首页 <spanclass="sr-only">(current)</span></a></li><liclass="nav-item"><ath:class="${active=='dashboard.html'?'nav-link active':'nav-link'}"th:href="@{/dashboard.html}"><svgxmlns="http://www.w3.org/2000/svg"width="24"height="24"viewBox="0 0 24 24"fill="none"stroke="currentColor"stroke-width="2"stroke-linecap="round"stroke-linejoin="round"class="feather feather-home"><pathd="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"></path><polylinepoints="9 22 9 12 15 12 15 22"></polyline></svg> 首页 <spanclass="sr-only">(current)</span></a></li><liclass="nav-item"><aclass="nav-link"href="http://getbootstrap.com/docs/4.0/examples/dashboard/#"><svgxmlns="http://www.w3.org/2000/svg"width="24"height="24"viewBox="0 0 24 24"fill="none"stroke="currentColor"stroke-width="2"stroke-linecap="round"stroke-linejoin="round"class="feather feather-file"><pathd="M13 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"></path><polylinepoints="13 2 13 9 20 9"></polyline></svg> Orders </a></li><liclass="nav-item"><ath:class="${active=='list1.html'?'nav-link active':'nav-link'}"th:href="@{/users}"><svgxmlns="http://www.w3.org/2000/svg"width="24"height="24"viewBox="0 0 24 24"fill="none"stroke="currentColor"stroke-width="2"stroke-linecap="round"stroke-linejoin="round"class="feather feather-shopping-cart"><circlecx="9"cy="21"r="1"></circle><circlecx="20"cy="21"r="1"></circle><pathd="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"></path></svg> 用户管理 </a></li><liclass="nav-item"><ath:class="${active=='list.html'?'nav-link active':'nav-link'}"th:href="@{/emps}"><svgxmlns="http://www.w3.org/2000/svg"width="24"height="24"viewBox="0 0 24 24"fill="none"stroke="currentColor"stroke-width="2"stroke-linecap="round"stroke-linejoin="round"class="feather feather-shopping-cart"><circlecx="9"cy="21"r="1"></circle><circlecx="20"cy="21"r="1"></circle><pathd="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"></path></svg> 员工管理 </a></li><liclass="nav-item"><aclass="nav-link"href="http://getbootstrap.com/docs/4.0/examples/dashboard/#"><svgxmlns="http://www.w3.org/2000/svg"width="24"height="24"viewBox="0 0 24 24"fill="none"stroke="currentColor"stroke-width="2"stroke-linecap="round"stroke-linejoin="round"class="feather feather-bar-chart-2"><linex1="18"y1="20"x2="18"y2="10"></line><linex1="12"y1="20"x2="12"y2="4"></line><linex1="6"y1="20"x2="6"y2="14"></line></svg> Reports </a></li><liclass="nav-item"><aclass="nav-link"href="http://getbootstrap.com/docs/4.0/examples/dashboard/#"><svgxmlns="http://www.w3.org/2000/svg"width="24"height="24"viewBox="0 0 24 24"fill="none"stroke="currentColor"stroke-width="2"stroke-linecap="round"stroke-linejoin="round"class="feather feather-layers"><polygonpoints="12 2 2 7 12 12 22 7 12 2"></polygon><polylinepoints="2 17 12 22 22 17"></polyline><polylinepoints="2 12 12 17 22 12"></polyline></svg> Integrations </a></li></ul><h6class="sidebar-heading d-flex justify-content-between align-items-center px-3 mt-4 mb-1 text-muted"><span>Saved reports</span><aclass="d-flex align-items-center text-muted"href="http://getbootstrap.com/docs/4.0/examples/dashboard/#"><svgxmlns="http://www.w3.org/2000/svg"width="24"height="24"viewBox="0 0 24 24"fill="none"stroke="currentColor"stroke-width="2"stroke-linecap="round"stroke-linejoin="round"class="feather feather-plus-circle"><circlecx="12"cy="12"r="10"></circle><linex1="12"y1="8"x2="12"y2="16"></line><linex1="8"y1="12"x2="16"y2="12"></line></svg></a></h6><ulclass="nav flex-column mb-2"><liclass="nav-item"><aclass="nav-link"href="http://getbootstrap.com/docs/4.0/examples/dashboard/#"><svgxmlns="http://www.w3.org/2000/svg"width="24"height="24"viewBox="0 0 24 24"fill="none"stroke="currentColor"stroke-width="2"stroke-linecap="round"stroke-linejoin="round"class="feather feather-file-text"><pathd="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path><polylinepoints="14 2 14 8 20 8"></polyline><linex1="16"y1="13"x2="8"y2="13"></line><linex1="16"y1="17"x2="8"y2="17"></line><polylinepoints="10 9 9 9 8 9"></polyline></svg> Current month </a></li><liclass="nav-item"><aclass="nav-link"href="http://getbootstrap.com/docs/4.0/examples/dashboard/#"><svgxmlns="http://www.w3.org/2000/svg"width="24"height="24"viewBox="0 0 24 24"fill="none"stroke="currentColor"stroke-width="2"stroke-linecap="round"stroke-linejoin="round"class="feather feather-file-text"><pathd="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path><polylinepoints="14 2 14 8 20 8"></polyline><linex1="16"y1="13"x2="8"y2="13"></line><linex1="16"y1="17"x2="8"y2="17"></line><polylinepoints="10 9 9 9 8 9"></polyline></svg> Last quarter </a></li><liclass="nav-item"><aclass="nav-link"href="http://getbootstrap.com/docs/4.0/examples/dashboard/#"><svgxmlns="http://www.w3.org/2000/svg"width="24"height="24"viewBox="0 0 24 24"fill="none"stroke="currentColor"stroke-width="2"stroke-linecap="round"stroke-linejoin="round"class="feather feather-file-text"><pathd="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path><polylinepoints="14 2 14 8 20 8"></polyline><linex1="16"y1="13"x2="8"y2="13"></line><linex1="16"y1="17"x2="8"y2="17"></line><polylinepoints="10 9 9 9 8 9"></polyline></svg> Social engagement </a></li><liclass="nav-item"><aclass="nav-link"href="http://getbootstrap.com/docs/4.0/examples/dashboard/#"><svgxmlns="http://www.w3.org/2000/svg"width="24"height="24"viewBox="0 0 24 24"fill="none"stroke="currentColor"stroke-width="2"stroke-linecap="round"stroke-linejoin="round"class="feather feather-file-text"><pathd="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path><polylinepoints="14 2 14 8 20 8"></polyline><linex1="16"y1="13"x2="8"y2="13"></line><linex1="16"y1="17"x2="8"y2="17"></line><polylinepoints="10 9 9 9 8 9"></polyline></svg> Year-end sale </a></li></ul></div></nav></html>
  • 根据 th:fragment="sidebar"th:replace="~{commons/commons::top}"来实现网页的嵌入<!--顶部栏--><navclass="navbar navbar-dark sticky-top bg-dark flex-md-nowrap p-0"th:fragment="top"><aclass="navbar-brand col-sm-3 col-md-2 mr-0"href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">[[${session.loginUser}]]</a><inputclass="form-control form-control-dark w-100"type="text"placeholder="Search"aria-label="Search"><ulclass="navbar-nav px-3"><liclass="nav-item text-nowrap"><aclass="nav-link"th:href="@{/user/logout}">注销</a></li></ul></nav><divth:replace="~{commons/commons::top}"></div>
  • 创建员工控制器,来实现展示功能EmployeeController``````publicclassEmployeeController{@AutowiredEmployeeDao employeeDao;@AutowiredDevelopmentDao developmentDao;@RequestMapping("/emps")publicStringlistAll(Model model){List<Employee> employees = employeeDao.queryEmployeeList();for(Employee employee : employees){System.out.println("employee==>"+employee);} model.addAttribute("emps",employees);return"/emp/list";}}
  • 根据th:class="${active=='dashboard.html'?'nav-link active':'nav-link'}"来实现标识高亮
  • 把所有的参数配置到所对应的网页中list.html``````<mainrole="main"class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4"><divclass="table-responsive"><tableclass="table table-striped table-sm"><thead><tr><th>id</th><th>lastName</th><th>email</th><th>gender</th><th>development</th><th>birth</th><th>操作</th></tr></thead><tbody><trth:each="emp:${emps}"><tdth:text="${emp.getId()}"></td><tdth:text="${emp.getLastName()}"></td><tdth:text="${emp.getEmail()}"></td><tdth:text="${emp.getGender()==0?'女':'男'}"></td><tdth:text="${emp.getEDevelopment().developmentName}"></td><tdth:text="${#dates.format(emp.getBirth(),'yyyy-MM-dd HH:mm')}"></td><td><aclass="btn btn-sm btn-primary">编辑</a><aclass="btn btn-sm btn-danger">删除</a></td></tr></tbody></table></div></main>
  • 这样的话,展示员工列表的功能就实现了

在这里插入图片描述

增加员工实现

  • 添加增加员工功能``````@GetMapping("/emp")publicStringAddtoPage(Model model){//查询所有员工的信息List<Employee> employees = employeeDao.queryEmployeeList(); model.addAttribute("employees",employees);//查询所有部门的信息List<Development> developments = developmentDao.getDevelopments(); model.addAttribute("developments",developments);return"/emp/add";}@PostMapping("/emp")publicStringAddemp(Employee employee){//添加的操作System.out.println("Addemp==>"+ employee); employeeDao.addEmplyee(employee);//调用底层业务来保存员工信息return"redirect:/emps";}
  • 创建一个add.html``````<mainrole="main"class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4"><formth:action="@{/emp}"method="post"><divclass="form-group"><label>LastName</label><inputtype="text"class="form-control"name="lastName"placeholder="张彦彬"></div><divclass="form-group"><label>Email</label><inputtype="email"name="email"class="form-control"placeholder="[email protected]"></div><divclass="form-group"><label>Gender</label><br><labelclass="radio-inline"><inputtype="radio"name="gender"value="1"> 男 </label><labelclass="radio-inline"><inputtype="radio"name="gender"value="0"> 女 </label></div><divclass="form-group"><label>Development</label><selectclass="form-control"name="development"><!--/*@thymesVar id="getDevelopmentName" type="com.zyb.pojo.Development"*/--><optionth:each="development:${developments}"th:text="${development.getDevelopmentName()}"th:value="${development.getId()}">1</option></select></div><divclass="form-group"><label>Birth</label><inputtype="text"name="birth"class="form-control"placeholder="时间"></div><buttontype="submit"class="btn btn-outline-success">添加</button></form></main>
  • 增加员工展示在这里插入图片描述在这里插入图片描述

修改员工信息

  • 添加修改员工信息功能@GetMapping("/updateEmp/{id}")publicStringtoUpdateEmp(@PathVariable("id")Integer id,Model model){Employee employeeById = employeeDao.queryEmployeeById(id);System.out.println(employeeById); model.addAttribute("emp",employeeById);Collection<Development> developments = developmentDao.getDevelopments(); model.addAttribute("developments",developments);return"emp/update";}@PostMapping("/updateEmp")publicStringupdateEmp(Employee employee){System.out.println("update==>"+ employee); employeeDao.updateEmplyee(employee);return"redirect:/emps";}
  • 创建一个update.html``````<mainrole="main"class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4"><formth:action="@{/updateEmp}"method="post"><inputtype="hidden"th:value="${emp.getId()}"name="id"><divclass="form-group"><label>LastName</label><inputth:value="${emp.getLastName()}"type="text"class="form-control"name="lastName"placeholder="张彦彬"></div><divclass="form-group"><label>Email</label><inputth:value="${emp.getEmail()}"type="email"name="email"class="form-control"placeholder="[email protected]"></div><divclass="form-group"><label>Gender</label><br><labelclass="radio-inline"><inputtype="radio"th:checked="${emp.getGender()==1}"name="gender"value="1"> 男 </label><labelclass="radio-inline"><inputtype="radio"th:checked="${emp.getGender()==0}"name="gender"value="0"> 女 </label></div><divclass="form-group"><label>Development</label><selectclass="form-control"name="development"><optionth:selected="${development.getId()==emp.getDevelopment()}"th:each="development:${developments}"th:text="${development.getDevelopmentName()}"th:value="${development.getId()}">1</option></select></div><divclass="form-group"><label>Birth</label><inputtype="text"name="birth"class="form-control"th:value="${#dates.format(emp.getBirth(),'yyyy-MM-dd HH:mm')}"placeholder="时间"></div><buttontype="submit"class="btn btn-outline-success">修改</button></form></main>
  • 修改页面展示

在这里插入图片描述

删除及404处理

  • 添加删除功能@RequestMapping("/delete/{id}")publicStringDeleteemp(@PathVariable("id")Integer id){ employeeDao.deleteEmplyee(id);return"redirect:/emps";}
  • 404处理页面只要放入到/templates/error文件夹下面,然后spring就会自动识别,如果跳转的页面不存在,就会自动跳转至此。

在这里插入图片描述
在这里插入图片描述

好了,一个springboot模拟数据库开发的网站就到此结束了,如果有什么不对的地方,请及时说出,我也会即使改正的。


本文转载自: https://blog.csdn.net/qq_43730903/article/details/122770650
版权归原作者 李淳罡(两袖青蛇) 所有, 如有侵权,请联系我们删除。

“SpringBoot模拟数据库开发”的评论:

还没有评论