springBoot+mybatis+springsecurity整合!

首先項目是maven工程,創建maven工程相信大家一定不陌生了。下面咱們直接進入主題。

首先搭建springBoot工程,pom.xml裏面添加這些jar信息,就足夠了,因爲springBoot非常強大,

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.5.RELEASE</version>
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>

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

創建啓動類
@SpringBootApplication
public class Application extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}

public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
}

}

創建配置文件application.properties,因爲springBoot會默認取加載這個配置文件
項目根路徑
server.context-path=/bry
項目端口號
server.port=8090
是不是非常簡單,下面在創建頁面,通過controller訪問頁面,這一套跟springMVC就很像了,
咱們使用thymeleaf模板來處理頁面,代替視圖解析器,
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

在src/main/resources下面創建static和templates包,默認的靜態資源是放在static裏面的,頁面是放在
templates裏面的,當然可以自己去配置目錄,但是沒有必要,既然springBoot給我們提供了這麼好的便利,我們爲什麼不用呢?

接下來,在templates裏面定義一個index.html
在定義一個controller,加一個跳轉的方法
@RequestMapping(value = { “index”}, method = RequestMethod.GET)
public String gotoIndex(Model model) {
return “index”;
}
這樣就可以跳轉到頁面了,因爲我們使用了強大的thymeleaf,一切他幫助我們處理了,
現在最簡單的工程我們已經搭建起來了,是不是超級簡單!

下面來說一下怎麼整合mybatis:
1.還是整合jar,也就是編寫pom.xml,
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>

2.聲明Mapper 接口和實現Mapper 的xml, 注意接口需要加上@Mapper,會自動掃描注入,例如:
@Mapper
public interface UserMapper (){}
然後定義UserMapper.xml,裏面的內容跟mybatis寫法一致,不在囉嗦.

3.application.properties加入連接數據庫的信息:
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://IP:3306/springSecurityTest?characterEncoding=utf8&useSSL=true
spring.datasource.username=root
spring.datasource.password=root

spring.datasource.max-active=20
spring.datasource.max-idle=8
spring.datasource.min-idle=8
spring.datasource.initial-size=10

spring.datasource.validation-query=SELECT 1
spring.datasource.test-while-idle=true
spring.datasource.time-between-eviction-runs-millis=27800

如此簡單就整合了mybatis,看看springBoot是不是非常牛氣啊,真的得說太讚了,不用想以前那麼繁瑣的配置了

最後來說一下怎麼整合springsecurity.
1.還是老規矩,配置pom.xml

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

application.properties什麼都不用配置就行.

2.接下來的步驟有點繁瑣,首先爲了看到效果我們創建幾個表和對應的實體類
sys_role表 字段id,name
sys_user表 字段id,username,password
sys_role_user表 字段id,Sys_User_id,Sys_Role_id

3.插入幾條數據
INSERT INTO sys_role VALUES ('1', 'ROLE_ADMIN');
INSERT INTO sys_role VALUES ('2', 'ROLE_USER');

INSERT INTO sys_user VALUES ('1', 'admin', '6d789d4353c72e4f625d21c6b7ac2982');
INSERT INTO sys_user VALUES ('2', 'user', '36f1cab655c5252fc4f163a1409500b8');

INSERT INTO sys_role_user VALUES ('1', '1', '1');
INSERT INTO sys_role_user VALUES ('2', '2', '2');

4.創建對應的實體類:

public class SysRole {
private Integer id;
private String name;

public Integer getId() {
    return id;
}

public void setId(Integer id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

}

public class SysUser {
private Integer id;
private String username;
private String password;

private List<SysRole> roles;

public Integer getId() {
    return id;
}

public void setId(Integer id) {
    this.id = id;
}

public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

public List<SysRole> getRoles() {
    return roles;
}

public void setRoles(List<SysRole> roles) {
    this.roles = roles;
}

}

5.接下來是配置類WebSecurityConfig

@Configuration //必須加這個註解,用於生成一個配置類,
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true) //啓用Security註解
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Bean
UserDetailsService customUserService() { // 註冊UserDetailsService 的bean
return new CustomUserService();
}

/**
 * 配置.忽略的靜態文件,不加的話,登錄之前頁面的css,js不能正常使用,得登錄之後才能正常.
 */

@Override
public void configure(WebSecurity web) throws Exception {
    // 忽略URL
    web.ignoring().antMatchers("/**/*.js", "/lang/*.json", "/**/*.css", "/**/*.js", "/**/*.map", "/**/*.html",
            "/**/*.png");
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(customUserService()).passwordEncoder(new PasswordEncoder(){
        //使用MD5獲取加密之後的密碼
        @Override
        public String encode(CharSequence rawPassword) {
            return MD5Util.encode((String)rawPassword);
        }
        //驗證密碼
        @Override 
        public boolean matches(CharSequence rawPassword, String encodedPassword) {
            return encodedPassword.equals(MD5Util.encode((String)rawPassword));
        }}); //user Details Service驗證
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
            .antMatchers("/").permitAll()  //首頁任意訪問
            .anyRequest().authenticated() // //其他所有資源都需要認證,登陸後才能訪問
            .and()
            .formLogin()
            .loginPage("/login")
            .defaultSuccessUrl("/", true)//登錄成功之後跳轉首頁
            .failureUrl("/login?error") //登錄失敗 返回error
            .permitAll() // 登錄頁面用戶任意訪問
            .and()
            .logout().permitAll(); // 註銷行爲任意訪問

}

}

6.其中用到了md5加密工具 ,這個經常用,不再囉嗦,你也可以使用別的加密方式,
例如 BCryptPasswordEncoder
public class MD5Util {

private static final String SALT = "tamboo";

public static String encode(String password) {
    password = password + SALT;
    MessageDigest md5 = null;
    try {
        md5 = MessageDigest.getInstance("MD5");
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    char[] charArray = password.toCharArray();
    byte[] byteArray = new byte[charArray.length];

    for (int i = 0; i < charArray.length; i++)
        byteArray[i] = (byte) charArray[i];
    byte[] md5Bytes = md5.digest(byteArray);
    StringBuffer hexValue = new StringBuffer();
    for (int i = 0; i < md5Bytes.length; i++) {
        int val = ((int) md5Bytes[i]) & 0xff;
        if (val < 16) {
            hexValue.append("0");
        }

        hexValue.append(Integer.toHexString(val));
    }
    return hexValue.toString();
}
public static void main(String[] args) {
    System.out.println(MD5Util.encode("admin"));
    System.out.println(MD5Util.encode("user"));

}

}

7.新建 CustomUserService 用於將用戶權限交給 springsecurity 進行管控;
@Service
public class CustomUserService implements UserDetailsService {
@Autowired
UserMapper userMapper;

@Override
public UserDetails loadUserByUsername(String username) { // 重寫loadUserByUsername 方法獲得 userdetails  類型用戶

    SysUser  user = userMapper.findByUserName(username);
    if (user == null) {
        throw new UsernameNotFoundException("用戶名不存在");
    }
    List<SimpleGrantedAuthority> authorities = new ArrayList<>();
    // 用於添加用戶的權限。只要把用戶權限添加到authorities 就萬事大吉。
    for (SysRole role : user.getRoles()) {
        authorities.add(new SimpleGrantedAuthority(role.getName()));
    }
    return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), authorities);
}

}

8.定義controller 我們的配置裏面配置了登錄成功之後跳轉到首頁
跳轉到登錄頁面
@RequestMapping(value = “/login”)
public String login() {
return “login”;
}
跳轉到主頁
@RequestMapping(value = {“/”,}, method = RequestMethod.GET)
public String gotohome() {
return “home”;
}

9.最後你可以自定義html頁面,很簡單了,這裏不再囉嗦!

10.配置完springsecurity之後,你的controller就可以加權限了
@RequestMapping("/getuser")
//必須有這個權限纔可以使用
@Secured("ROLE_USER")
@ResponseBody
public User getUser() {
User user = new User();
user.setName("test");
return user;
}

11.如果你想使用 BCryptPasswordEncoder加密,配置文件需要修改成下面這樣
@Autowired
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(customUserService).passwordEncoder(new BCryptPasswordEncoder());
}

存入數據庫的加密方法如下:
public SysUser create(User u user){
//進行加密
BCryptPasswordEncoder encoder =new BCryptPasswordEncoder();
sysUser.setPassword(encoder.encode(user.getRawPassword().trim()));
userDao.create(user);
return sysUser;
}

end……..

發佈了20 篇原創文章 · 獲贊 14 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章