SpringBoot簡單實現登陸功能

登錄

開發期間模板引擎頁面修改之後,要實時生效css

1)、禁用模板引擎的緩存html

# 禁用緩存 spring.thymeleaf.cache=false 

2)、頁面修改完成之後ctrl+f9:從新編譯;java

 

登錄錯誤消息的顯示web

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

login.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <meta name="description" content="">
        <meta name="author" content="">
        <title>Signin Template for Bootstrap</title>
        <!-- Bootstrap core CSS -->
        <link href="asserts/css/bootstrap.min.css" th:href="@{/webjars/bootstrap/4.0.0/css/bootstrap.css}" rel="stylesheet">
        <!-- Custom styles for this template -->
        <link href="asserts/css/signin.css" th:href="@{/asserts/css/signin.css}" rel="stylesheet">
    </head>
    <body class="text-center">
        <form class="form-signin" action="dashboard.html" th:action="@{/user/login}" method="post">
            <img class="mb-4" th:src="@{/asserts/img/bootstrap-solid.svg}" src="asserts/img/bootstrap-solid.svg" alt="" width="72" height="72">
            <h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}">Please sign in</h1>
            <!--判斷-->
            <p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
            <label class="sr-only" th:text="#{login.username}">Username</label>
            <input type="text" name="username" class="form-control" placeholder="Username" th:placeholder="#{login.username}" required="" autofocus="">
            <label class="sr-only" th:text="#{login.password}">Password</label>
            <input type="password" name="password" class="form-control" placeholder="Password" th:placeholder="#{login.password}" required="">
            <div class="checkbox mb-3">
                <label>
                      <input type="checkbox" value="remember-me"/> [[#{login.remember}]] </label>
            </div>
            <button class="btn btn-lg btn-primary btn-block" type="submit" th:text="#{login.btn}">Sign in</button>
            <p class="mt-5 mb-3 text-muted">© 2017-2018</p>
            <a class="btn btn-sm" th:href="@{/index.html(l='zh_CN')}">中文</a>
            <a class="btn btn-sm" th:href="@{/index.html(l='en_US')}">English</a>
        </form>
    </body>

</html>

4)、Controller層

  LoginController:spring

package com.atguigu.springboot.controller; import org.springframework.stereotype.Controller; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpSession; import java.util.Map; @Controller public class LoginController { // @DeleteMapping // @PutMapping // @GetMapping //@RequestMapping(value = "/user/login",method = RequestMethod.POST)
    @PostMapping(value = "/user/login") public String login(@RequestParam("username") String username, @RequestParam("password") String password, Map<String,Object> map, HttpSession session){ if(!StringUtils.isEmpty(username) && "123456".equals(password)){ //登錄成功,防止表單重複提交,能夠重定向到主頁
            session.setAttribute("loginUser",username); return "redirect:/main.html"; }else{ //登錄失敗
 map.put("msg","用戶名密碼錯誤"); return  "login"; } } }

 

4)、攔截器進行登錄檢查

攔截器bootstrap

package com.atguigu.springboot.component; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 登錄檢查, */
public class LoginHandlerInterceptor implements HandlerInterceptor { //目標方法執行以前
 @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { Object user = request.getSession().getAttribute("loginUser"); if(user == 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 { } 
}

註冊攔截器:
package com.atguigu.springboot.config;import com.atguigu.springboot.component.LoginHandlerInterceptor;import com.atguigu.springboot.component.MyLocaleResolver;import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.LocaleResolver;import org.springframework.web.servlet.config.annotation.EnableWebMvc;import org.springframework.web.servlet.config.annotation.InterceptorRegistry;import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;//使用WebMvcConfigurerAdapter能夠來擴展SpringMVC的功能//@EnableWebMvc   //不要接管SpringMVC@Configurationpublic class MyMvcConfig extends WebMvcConfigurerAdapter {    @Override    public void addViewControllers(ViewControllerRegistry registry) {       // super.addViewControllers(registry);        //瀏覽器發送 /atguigu 請求來到 success        registry.addViewController("/atguigu").setViewName("success");    }    //全部的WebMvcConfigurerAdapter組件都會一塊兒起做用    @Bean //將組件註冊在容器    public WebMvcConfigurerAdapter webMvcConfigurerAdapter(){        WebMvcConfigurerAdapter adapter = new WebMvcConfigurerAdapter() {            @Override            public void addViewControllers(ViewControllerRegistry registry) {                registry.addViewController("/").setViewName("login");                registry.addViewController("/index.html").setViewName("login");                registry.addViewController("/main.html").setViewName("dashboard");            }            //註冊攔截器            @Override            public void addInterceptors(InterceptorRegistry registry) {                //super.addInterceptors(registry);                //靜態資源;  *.css , *.js                //SpringBoot已經作好了靜態資源映射                registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**")                        .excludePathPatterns("/index.html","/","/user/login");            }        };        return adapter;    }    @Bean    public LocaleResolver localeResolver(){        return new MyLocaleResolver();    }}
相關文章
相關標籤/搜索