學習筆記:Spring Boot實現用戶登錄功能(idea)


1idea-new-project-spring initializr

 

 

 2.選中web功能。然后next默認創建工程

 

 

 3.所有 /webjars/** ,都去 classpath:/META-INF/resources/webjars/ 找資源;==webjars:以jar包的方式引入靜態資源(可能復制的代碼格式有問題導致pom報錯,出現這種情況建議官網直接復制相關代碼即可)

<!--        引入jquery-webjar在訪問的時候只需要寫webjars下面資源的名稱即可
        https://mvnrepository.com/artifact/org.webjars/jquery &ndash;&gt;-->
        
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>3.3.1</version>
        </dependency>
View Code

4."/**" 訪問當前項目的任何資源,都去(靜態資源的文件夾)找映射==

  "classpath:/META-INF/resources/",
  "classpath:/resources/",
  "classpath:/static/",
  "classpath:/public/"
  "/":當前項目的根路徑

5.模板引擎:使用SpringBoot推薦的Thymeleaf;

6.實現用戶登錄功能:

(1)html頁面的的form表單中設置action屬性:例如:<form class="form-signin" action="dashboard.html" th:action="@{/user/login}" method="post"> 中的 th:action="@{/user/login}"

<form class="form-signin" action="dashboard.html" th:action="@{/user/login}" method="post">

(2)在controller包中新建一個logincontroller.java,並在類方法前添加@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 "dashboard";
        }else{
            //登陸失敗

            map.put("msg","用戶名密碼錯誤");
            return  "login";
        }

    }
}
View Code
(3)如果登錄顯示400錯誤:HTML中的用戶名input出中的name屬性沒寫:如下照片的: name="username"
<input type="text"  name="username" class="form-control" placeholder="Username" th:placeholder="#{login.username}" required="" autofocus="">

  同理,密碼同樣處理

<input type="password" name="password" class="form-control" placeholder="Password" th:placeholder="#{login.password}" required="">

(4)禁用緩存后,頁面會實時生效,方便處理,在src/main/resources/application.properties中設置,頁面修改完成以后ctrl+f9:重新編譯

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

(5)實現顯示登錄錯誤信息效果,在如下處插入一個P標簽  <p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>

    <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>

(6)重定向的使用,在 src/main/java/com/azuma/springboot/config/MyMvcConfig.java中的addViewControllers方法添加一個識圖解釋器:registry.addViewController("/main.html").setViewName("dashboard")

            @Override
            public void addViewControllers(ViewControllerRegistry registry) {
                registry.addViewController("/").setViewName("login");
                registry.addViewController("/index.html").setViewName("login");
                //添加視圖解釋器
                registry.addViewController("/main.html").setViewName("dashboard");
            }

(7)然后在src/main/java/com/azuma/springboot/controller/LoginController.java中的login方法中,在登錄成功處進行重定向

    @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";
        }

    }

(8)啟動瀏覽器,輸入http://localhost:8080/crud/ 進行登錄測試

 

7.添加用戶登錄攔截功能

(1)在src/main/java/com/azuma/springboot/controller/LoginController.java的login方法中添加一個session(上面已經添加過了)

session.setAttribute("loginUser",username);

(2)添加一個攔截器的類:src/main/java/com/azuma/springboot/component/LoginHandlerInterceptor.java

package com.azuma.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 {

    }
}

(3)攔截器類寫好后要記得在src/main/java/com/azuma/springboot/config/MyMvcConfig.java中進行配置(注意在Spring 5.0 中,已經將 WebMvcConfigurerAdapter 抽象類加上 @Deprecated 注解 記為過時)所以src/main/java/com/azuma/springboot/config/MyMvcConfig.java中的WebMvcConfigurerAdapter被划掉了

解決方法:

spring5以上版本不建議使用,所以把原來的繼承 WebMvcConfigurerAdapter改為

public class CustomWebConigurer implements WebMvcConfigurer
可以實現相同的功能。

是1.8以后接口中可以不必實現接口的抽象方法才變化的。 

WebMvcConfigurerAdapter 其實也是實現了 WebMvcConfigurer接口的

(4)由上可知,修改:src/main/java/com/azuma/springboot/config/MyMvcConfig.java中的extend WebMvcConfigurerAdapter修改成implements WebMvcConfigurer

package com.azuma.springboot.config;

import com.azuma.springboot.component.LoginHandlerInterceptor;
import com.azuma.springboot.component.MyLocaleResolver;
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.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

//使用WebMvcConfigurerAdapter可以來擴展SpringMVC的功能
//@EnableWebMvc   不要接管SpringMVC
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {



    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
       // super.addViewControllers(registry);
        //瀏覽器發送 /atguigu 請求來到 success
        registry.addViewController("/azuma").setViewName("success");
    }

    //所有的WebMvcConfigurerAdapter組件都會一起起作用
    @Bean //將組件注冊在容器
    public WebMvcConfigurer WebMvcConfigurer(){
        WebMvcConfigurer adapter = new WebMvcConfigurer() {
            @Override
            public void addViewControllers(ViewControllerRegistry registry) {
                registry.addViewController("/").setViewName("login");
                registry.addViewController("/index.html").setViewName("login");
                registry.addViewController("/main.html").setViewName("dashboard");
            }

    //注冊攔截器,配置過濾靜態資源
    //靜態資源;  *.css , *.js
    //SpringBoot已經做好了靜態資源映射
     @Override
     public void addInterceptors(InterceptorRegistry registry) {
                registry.addInterceptor(new LoginHandlerInterceptor())
                        .addPathPatterns("/**")
                        .excludePathPatterns("/index.html","/","/user/login","/static/**", "/webjars/**", "/asserts/**");
            }

        };
        return adapter;
    }

    @Bean
    public LocaleResolver localeResolver(){

        return new MyLocaleResolver();
    }


}
View Code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM