使用SpringBoot2.x+Themleaf3.0完成用户登录的开发

原创
2018/10/09 19:29
阅读数 840

首先创建一个SpringBoot的web项目,并添加themleaf的依赖 & webjars:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

<!--引入jquery-webjar-->
<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>jquery</artifactId>
    <version>3.3.1</version>
</dependency>

<!--引入bootstrap-->
<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>bootstrap</artifactId>
    <version>4.0.0</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

期望前端通过一个form提交表单的形式,进行登录验证,POST请求 /user/login

<div class="body">
    <form class="form-auth-small" action="index.html" th:action="@{/user/login}" method="post">
        <p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
        <div class="form-group">
            <label for="signin-email" class="control-label sr-only" th:text="#{login.username}">username</label>
            <input type="text" name="username" class="form-control" id="signin-email" value=""
                   placeholder="User Name" th:placeholder="#{login.username}">
        </div>
        <div class="form-group">
            <label for="signin-password" class="control-label sr-only" th:text="#{login.password}">Password</label>
            <input type="password" name="password" class="form-control" id="signin-password" value=""
                   placeholder="Password" th:placeholder="#{login.password}">
        </div>
        <div class="form-group clearfix">
            <label class="fancy-checkbox element-left">
                <input type="checkbox">
                <span>Remember me</span>
            </label>
        </div>
        <button type="submit" class="btn btn-primary btn-lg btn-block" th:text="#{login.btn}">LOGIN</button>
    </form>
</div>

服务端通过Controller层的接口进行Mapping

@PostMapping(value = "/user/login")
public String login(@RequestParam("username") String username, @RequestParam("password") String password,
                    Map map, HttpSession session) {

    if (this.userName.equals(username) && this.password.equals(password)) {
        //用户名和密码完成校验
        session.setAttribute("userLogin", username);  //缓存session
        return "redirect:/main.html"; //跳转至main.html
    } else {
       //用户名和密码未完成校验
        map.put("msg", "用户名或密码错误");
        return "light/page-login";
    }
}

通过实现接口WebMvcConfigurer,完成对SpringMVC的扩展,实现对Controller到View的映射,以及对URL的拦截,而index.html和静态资源不进行拦截。

@Configuration
public class UserMvcConfigure implements WebMvcConfigurer {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("light/page-login");
        registry.addViewController("/index.html").setViewName("light/page-login");
        registry.addViewController("/main.html").setViewName("light/index");
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**")
                .excludePathPatterns("/", "/index.html", "/user/login", "/assets/**", "/light/assets/**", "/webjars/**");
    }

    @Bean
    public LocaleResolver getLocaleResolver() {
        return new UserLocaleResolver();
    }
}

具体拦截代码实现为:

public class LoginHandlerInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object userLogin = request.getSession().getAttribute("userLogin");
        if (userLogin == 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 {

    }
}

至此,可以完成一个简单的登录验证。

备注:

        resources/static目录:存放静态资源文件,即*.js *.css *.jpg等

        resources/templates目录:存放themleaf的模板文件,即*.html

        前端代码中使用webjars的@引入静态资源的好处是:访问路径改变之后,前段代码会自动添加该路径。

 

展开阅读全文
打赏
0
1 收藏
分享
加载中
更多评论
打赏
0 评论
1 收藏
0
分享
返回顶部
顶部