SpringBoot+thymeleaf+security+vue搭建后台框架 基礎篇(一)


剛剛接觸SpringBoot,說說踩過的坑,主要的還是要記錄下來,供以后反省反省!

今天主要講講 thymeleaf+security 的搭建,SpringBoot的項目搭建應該比較簡單,這里就不多說了。可以去網上找到很多。

一:首先,你需要有一個SpringBoot的基礎項目!我這里用的是SpringBoot+mybasit來搭建的基礎框架

  基礎的部分可以看看這個人的博客   http://blog.csdn.net/forezp?viewmode=contents 寫的很詳情,

  需要注意的幾點如下:

  

二:springboot在整合多個生產環境的配置:

  在springboot中,通過@profileActive@ 來獲取maven中的值,注意springboot中 用@@ 替代了${}

   

  在maven中 配置 profileActive 

<profiles>
   <profile>
      <id>localhost</id>
      <properties>
          <profileActive>localhost</profileActive>
      </properties>
      <activation>
          <activeByDefault>true</activeByDefault>
      </activation>
   </profile>
   <profile>
      <id>dev</id>
      <properties>
         <profileActive>dev</profileActive>
      </properties>
   </profile>
   <profile>
      <id>master</id>
      <properties>
         <profileActive>master</profileActive>
      </properties>
   </profile>
</profiles> 

 三:Springboot整合 配置 Web模板  thymeleaf

  3.1 基本需求

Thymeleaf除了基本的模板引擎,還提供了一套Spring集成技術使得在Spring MVC中能夠使用它完全替代JSP作為模板引擎,它的功能特性如下:

    • Spring MVC中@Controller中的方法可以直接返回模板名稱,接下來Thymeleaf模板引擎會自動進行渲染
    • 模板中的表達式支持Spring表達式語言(Spring EL)
    • 表單支持,並兼容Spring MVC的數據綁定與驗證機制
    • 國際化支持

如果你還不了解Thymeleaf,請一定先閱讀新一代Java模板引擎Thymeleaf

 

  其引入方式很簡單:在maven中添加依賴

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

thymeleaf默認的資源文件的約定目錄結構 

Maven的資源文件目錄:/src/Java/resources 
spring-boot項目靜態文件目錄:/src/java/resources/static 
spring-boot項目模板文件目錄:/src/java/resources/templates 

所以在默認的情況下  你的.html頁面 需要放在這三個目錄下面中的某一個中 ,當然你也可以自己指定資源模板位置,其在application.yml中的配置如下:

spring:
thymeleaf:
prefix: classpath:/page/ //指定模板加載位置
suffix: .html //指定走綴類型
mode: HTML5
encoding: UTF-8     //指定編碼
content-type: text/html
cache: false //頁面不緩存

這個時候 你的靜態頁面就放在page里面


3.2:另外就是.html格式的不同:

Command對象用來在Spring MVC中綁定表單與后端對象,Thymeleaf提供的th:object屬性可以用來指定Command對象:
而且:html文件中 需要引入 模板
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>index</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>

html標簽上使用th:開頭標識作為前綴。

通過@{}引入web靜態文件。


3.3:一個完整的例子如下:
  
@Controller
@RequestMapping("/")
public class TestController {

    @RequestMapping("")
    public String index(Model model) {

        UserEntity boy = new UserEntity();
        boy.setUserName("weber");
        boy.setNumber("1235");

        model.addAttribute("user", boy);
        return "index";
    }
}

我的index.html頁面在 /src/Java/resources/page中

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>index</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>

<div style="text-align: center;margin:0 auto;width: 1000px; ">
    你的名稱 <span th:text="${user.userName}"></span>
    你的編號 <span th:text="${user.number}"></span>
</div>
</body>
</html>

  結果是:

這樣 你就完成了thymeleaf基礎模板的引用


 四:Springboot整合 配置 security權限框架

  詳情可參考:http://emacoo.cn/backend/spring-boot-security/
  

首先需要引入依賴 

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

在自己配置Spring Security  

package com.coocaa.weather.admin.configs;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * Create by yugaofeng on 2017/11/30
 */

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {



    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests().antMatchers("/fail", "/login","/").permitAll().anyRequest().authenticated() //不攔截的請求
                .and().formLogin().loginPage("/login").permitAll().successForwardUrl("/success").failureUrl("/fail")
                .and().logout().permitAll();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/js/**", "/css/**", "/images/**", "/**/favicon.ico"); //靜態資源地址
    }

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .inMemoryAuthentication()
                .withUser("user").password("password").roles("USER","USER2");    //配置的用戶信息地址 
   
    }


}

此時,你還需要一個web頁面 和 地址跳轉

   跳轉到 login頁面  因為在 .and().formLogin().loginPage("/login").permitAll().配置了  未登錄的直接跳轉這個地址

  web頁面  把數據提交到 /login中 框架會自動幫你驗證登陸  用戶名是 user  密碼是 password 權限類別是USER 

  

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>index</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<div style="text-align: center;margin:0 auto;width: 1000px; ">
        <form th:action="@{/login}" method="post">
            <div>
               用戶名: <input type="text" name="username"/>
            </div>
            <div>
                密碼: <input type="text" name="password"/>
            </div>
            <div>
               <input type="submit" value="登陸"/>
            </div>
        </form>
</div>
</body>
</html>

這個時候 你就可以登陸了,,成功的話執行 /success接口 失敗調用 /fail接口

 

這個時候 我們也可以通過配置Service來驗證登陸  修改 SecurityConfig 中的 public void configure(AuthenticationManagerBuilder auth) throws Exception  方法

 

    

添加一個Service方法:

package com.coocaa.weather.admin.configs;

import com.coocaa.fire.utils.StringUtils;
import com.coocaa.weather.admin.entity.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Create by yugaofeng on 2017/11/30
 */
@Component
public class MyUserDetailsService implements UserDetailsService {


    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {

        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority("USER"));


        //查詢賬號是否存在,是就返回一個UserDetails的對象,否就拋出異常!
        return new org.springframework.security.core.userdetails.User(
                "yugaofeng", new BCryptPasswordEncoder().encode("654321"),true, true, true, true, authorities);
    }


}

 

 

需要注意的是 這里的密碼 需要用  new BCryptPasswordEncoder().encode("654321") 進行加密。因為你在 auth.userDetailsService(detailsService).passwordEncoder(new BCryptPasswordEncoder());添加了加密。。。所以在正式開發過程中 你需要用    new BCryptPasswordEncoder().encode(password)來加密用戶注冊時候的密碼:

在后面的controller中  通過添加角色信息 來完成 頁面的權限 例如  test地址 只有USER的權限  test2 只用USER2的權限

 

 

 

。。。。。持續更新中

 

 

 

 

 

 
        

 

 

 

 


免責聲明!

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



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