SpringBoot+thymeleaf+security+vue搭建後臺框架 基礎篇(一)

剛剛接觸SpringBoot,說說踩過的坑,主要的仍是要記錄下來,供之後檢討檢討!css

今天主要講講 thymeleaf+security 的搭建,SpringBoot的項目搭建應該比較簡單,這裏就很少說了。能夠去網上找到不少。html

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

  基礎的部分能夠看看這我的的博客   http://blog.csdn.net/forezp?viewmode=contents 寫的很詳情,web

  須要注意的幾點以下:spring

  

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

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

   

  在maven中 配置 profileActive springboot

<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模板  thymeleafapp

  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提供的屬性能夠用來指定Command對象:
並且:html文件中 須要引入 模板th:object
<!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的權限

 

 

 

。。。。。持續更新中

相關文章
相關標籤/搜索