使用springboot进行web项目开发1(含数据库连接,国际化,登录控制,拦截器)

£神魔★判官ぃ 2023-01-08 04:23 88阅读 0赞

springboot-web项目的开发过程

该项目使用了thymeleaf模板引擎,整合了mybatis,实现了CRUD,权限控制(拦截器)

1.准备工作
  1. 创建spring boot项目,在resources目录下的static目录下导入静态资源css,js,img
  2. 在resources目录下的templates目录下导入静态资源xxx.html

    • 项目中使用了bootstrap的模板
2.连接数据库
  1. pom文件中引入相关依赖

    1. <dependency>
    2. <groupId>org.springframework.boot</groupId>
    3. <artifactId>spring-boot-starter-jdbc</artifactId>
    4. </dependency>
    5. <dependency>
    6. <groupId>mysql</groupId>
    7. <artifactId>mysql-connector-java</artifactId>
    8. <scope>runtime</scope>
    9. </dependency>
  2. 在主配置文件application.properties文件中配置相关参数

    1. spring.datasource.username=root
    2. spring.datasource.password=123456
    3. spring.datasource.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    4. spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

    注意:serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8,需要添加时间地区和编码方式

  3. 启动idea的mysql连接,选择schemas(要使用到的数据库表),若连接失败,在advanced中配置serverTimezone=UTC
3.国际化(i18n)

页面支持中英文切换

  1. pom.xml中引入thymeleaf引擎依赖

    1. <dependency>
    2. <groupId>org.thymeleaf</groupId>
    3. <artifactId>thymeleaf-spring5</artifactId>
    4. </dependency>
    5. <dependency>
    6. <groupId>org.thymeleaf.extras</groupId>
    7. <artifactId>thymeleaf-extras-java8time</artifactId>
    8. </dependency>
  2. 在resources创建i18n目录,在该目录下创建login.properties

    • 创建login_en_US.properties
    • 创建login_zh_CN.properties

    点击login.properties文件,点击下方的 Resource Bundle,然后页面内容进行中英文匹配

    watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80Mzg5NDc3MQ_size_16_color_FFFFFF_t_70

  3. 在主配置文件application.properties文件中配置i18n的配置

    1. spring.thymeleaf.cache=false
    2. spring.messages.basename=i18n.login

    关闭thymeleaf引擎的缓存,设置国际化信息的来源为i18n目录下的login

  4. 依照thymeleaf语法修改index中的相关代码

    1. <!DOCTYPE html>
    2. <html lang="en_US" xmlns:th="http://www.thymeleaf.org">
    3. <head>
    4. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    5. <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    6. <meta name="description" content="">
    7. <meta name="author" content="">
    8. <title>Signin Template for Bootstrap</title>
    9. <!-- Bootstrap core CSS -->
    10. <link th:href="@{/css/bootstrap.min.css}" rel="stylesheet">
    11. <!-- Custom styles for this template -->
    12. <link th:href="@{/css/signin.css}" rel="stylesheet">
    13. </head>
    14. <body class="text-center">
    15. <form class="form-signin" th:action="@{/user/login}">
    16. <img class="mb-4" th:src="@{/img/bootstrap-solid.svg}" alt="" width="72" height="72">
    17. <h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}">Please sign in</h1>
    18. <!--如果msg的值不为空才显示这个消息-->
    19. <p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
    20. <label class="sr-only" th:text="#{login.username}">Username</label>
    21. <input type="text" name="username" class="form-control" th:placeholder="#{login.username}" required="" autofocus="">
    22. <label class="sr-only" th:text="#{login.password}">Password</label>
    23. <input type="password" name="password" class="form-control" th:placeholder="#{login.password}" required="">
    24. <div class="checkbox mb-3">
    25. <label>
    26. <input type="checkbox" value="remember-me"> [[#{login.remember}]]
    27. </label>
    28. </div>
    29. <button class="btn btn-lg btn-primary btn-block" type="submit">[[#{login.btn}]]</button>
    30. <p class="mt-5 mb-3 text-muted">© 2017-2018</p>
    31. <a class="btn btn-sm" th:href="@{/index.html(l='zh_CN')}">中文</a>
    32. <a class="btn btn-sm" th:href="@{/index.html(l='en_US')}">English</a>
    33. </form>
    34. </body>
    35. </html>

    小结:

    • 引入thymeleaf的命名空间
    • 根据thymeleaf的语法规则对原有的html代码进行修改

      • 链接使用@

        1. <link th:href="@{/css/bootstrap.min.css}" rel="stylesheet">
        2. <img class="mb-4" th:src="@{/img/bootstrap-solid.svg}" alt="" width="72" height="72">
        3. <a class="btn btn-sm" th:href="@{/index.html(l='zh_CN')}">中文</a>
      • 文本信息使用#

        1. <p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
      • if等使用$

        1. <p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
  5. 自定义mvcconfig

    1. package com.cai.config;
  1. import org.springframework.context.annotation.Bean;
  2. import org.springframework.context.annotation.Configuration;
  3. import org.springframework.stereotype.Component;
  4. import org.springframework.web.servlet.LocaleResolver;
  5. import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
  6. import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
  7. import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
  8. import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
  9. import org.yaml.snakeyaml.events.Event;
  10. import java.util.Locale;
  11. @Configuration
  12. public class MyMvcConfig implements WebMvcConfigurer {
  13. @Override
  14. public void addViewControllers(ViewControllerRegistry registry) {
  15. registry.addViewController("/").setViewName("index");
  16. registry.addViewController("/index.html").setViewName("index");
  17. registry.addViewController("/main.html").setViewName("dashboard");
  18. }
  19. @Bean
  20. public LocaleResolver localeResolver(){
  21. return new LocaleConfig();
  22. }
  23. }
  1. 自定义localeconfig

    1. package com.cai.config;
    2. import org.springframework.web.servlet.LocaleResolver;
    3. import org.thymeleaf.util.StringUtils;
    4. import javax.servlet.http.HttpServletRequest;
    5. import javax.servlet.http.HttpServletResponse;
    6. import java.util.Locale;
  1. public class LocaleConfig implements LocaleResolver{
  2. @Override
  3. public Locale resolveLocale(HttpServletRequest httpServletRequest) {
  4. String l= httpServletRequest.getParameter("l");
  5. //System.out.println("debug====================>"+l);
  6. Locale locale =Locale.getDefault();
  7. if(!StringUtils.isEmpty(l)){
  8. String [] split= l.split("_");
  9. locale=new Locale(split[0],split[1]);
  10. }
  11. return locale;
  12. }
  13. @Override
  14. public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {
  15. }
  16. }
  1. 国际化总结:

    国际化其实就是对原有页面中的内容进行中英文替换。在点击中文,英文切换时,携带参数传递给自定义的localeconfig,判断显示中文还是英文页面,然后将localeconfig注入到mvcconfig当中。当页面接收到显示中文或英文时,会通过th:text=”#{login.tip}“进行显示。

4.登录控制
  1. 输入用户名密码访问

    1. 编写logincontroller,接收index.html页面传来的账号和密码,进行判断

      1. package com.cai.controller;
      2. import org.springframework.stereotype.Controller;
      3. import org.springframework.ui.Model;
      4. import org.springframework.web.bind.annotation.RequestMapping;
      5. import org.springframework.web.bind.annotation.RequestParam;
      6. import org.springframework.web.bind.annotation.ResponseBody;
      7. import org.thymeleaf.util.StringUtils;
      8. import javax.lang.model.element.NestingKind;
      9. import javax.servlet.http.HttpSession;
  1. @Controller
  2. public class LoginController {
  3. @RequestMapping("/user/login")
  4. //@Responsebody这个注解的作用是返回一个json格式
  5. //@ResponseBody
  6. //为了防止出现不必要的错误,需要加requestparam来保证参数的准确
  7. public String login(@RequestParam("username") String username, @RequestParam("password") String password, Model model, HttpSession session) {
  8. //具体的业务
  9. if (!StringUtils.isEmpty(username) && "123456".equals(password)) {
  10. session.setAttribute("loginUser",username);
  11. //登录成功的话重定向到main.html,隐藏用户名和密码
  12. return "redirect:/main.html";
  13. } else {
  14. //登录失败的话,告诉用户登录失败,返回index页面
  15. model.addAttribute("msg", "用户名或者密码错误");
  16. return "index";
  17. }
  18. }
  19. //注销
  20. @RequestMapping("/user/logout")
  21. public String logout(HttpSession session){
  22. session.invalidate();
  23. return "redirect:/index.html";
  24. }
  25. }
  26. 2. 将判断结果返回给html页面进行显示,成功则进入,不成功则显示提示信息(index.html部分代码,完整代码同上)
  27. <form class="form-signin" th:action="@{/user/login}">
  28. <!--如果msg的值不为空才显示这个消息-->
  29. <p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
  1. 通过页面路径访问需要拦截

    1. 自定义一个拦截器LoginHandlerinterceptor

      1. package com.cai.config;
      2. import org.springframework.web.servlet.HandlerInterceptor;
      3. import org.springframework.web.servlet.ModelAndView;
      4. import javax.servlet.http.HttpServletRequest;
      5. import javax.servlet.http.HttpServletResponse;
      6. /** * @BelongsProject:IntelliJ IDEA * @Package:com.cai.config * @Author:superman * @CreateTime:2021--01--14 10:58 * @Description:登录拦截器 */
      7. public class LoginHandlerinterceptor implements HandlerInterceptor {
      8. @Override
      9. public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
      10. //登录成功之后,应该有用户的session;
      11. Object loginUser = request.getSession().getAttribute("loginUser");
      12. if (loginUser==null){
      13. request.setAttribute("msg","没有权限,请先登录");
      14. request.getRequestDispatcher("/index.html").forward(request,response);
      15. return false;
      16. }else {
      17. return true;
      18. }
      19. }
      20. }
    2. 在自定义的mvcconfig配置拦截器,放行静态资源和首页

      1. //配置拦截器
      2. @Override
      3. public void addInterceptors(InterceptorRegistry registry) {
      4. registry.addInterceptor(new LoginHandlerinterceptor()).addPathPatterns("/**").excludePathPatterns("/index.html","/","/user/login","/css/**","/js/**","/img/**");
      5. }

发表评论

表情:
评论列表 (有 0 条评论,88人围观)

还没有评论,来说两句吧...

相关阅读