一、Mybatis整合
(1)导入依赖
<!-- mybatis自己的启动器-->
<!-- mybatis-spring-boot-starter -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
(2)编写Mapper接口
@Mapper
@Repository
public interface UserMapper {
List<User> query();
}
(3)编写Mapper.xml放在resources/mybatis/mapper
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.aguo.mapper.UserMapper">
<select id="query" resultType="User">
select * from bookuser;
</select>
</mapper>
(4)配置别名和扫描路径
mybatis:
type-aliases-package: com.aguo.pojo
mapper-locations: classpath:mybatis/mapper/*.xml
(5)使用
@Autowired
UserMapper userMapper;
(6)配置事务
在方法体上加入@transactional注解即可!
@Service
public class UserService {
@Autowired
UserMapper userMapper;
@Transactional
List<User> query(){
return null;
}
}
二、SpringSecurity
依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
一、user实体类
package com.aguo.pojo;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class User implements UserDetails {
private Integer id;
private String userName;
private String passWord;
private String email;
/* 接着创建用户表对应的实体类。用户实体类需要实现 UserDetails 接口,并实现该接口中的 7 个方法:
(1)用户根据实际情况设置这 7 个方法的返回值。
默认情况下不需要开发者自己进行密码角色等信息的比对,开发者只需要提供相关信息即可,例如:
getPassword() 方法返回的密码和用户输入的登录密码不匹配,会自动抛出 BadCredentialsException 异常
isAccountNonLocked() 方法返回了 false,会自动抛出 AccountExpiredException 异常。
(2)getAuthorities 方法用来获取当前用户所具有的角色信息,
本案例中,用户所具有的角色存储在 roles 属性中,因此该方法直接遍历 roles属性,
然后构造 SimpleGrantedAuthority 集合并返回。
*/
/** getAuthorities():获取当前用户对象所具有的角色信息
* 务必要加前缀 ROLE_
* @return
*/
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
List<SimpleGrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority("ROLE_vip1"));
authorities.add(new SimpleGrantedAuthority("ROLE_vip2"));
// authorities.add(new SimpleGrantedAuthority("ROLE_vip3"));
return authorities;
}
/**
*getPassword():获取当前用户对象的密码
* @return
*/
@Override
public String getPassword() {
// 这里返回从数据库取出来的密码
// 实例化加密类
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
// 假设从数据库取出的密码是123456
String encode = encoder.encode("123456");
return encode;
}
/**
* getUsername():获取当前用户对象的用户名
* @return
*/
@Override
public String getUsername() {
return userName;
}
/**
* isAccountNonExpired():当前账户是否未过期
* @return true=未过期
*/
@Override
public boolean isAccountNonExpired() {
return true;
}
/**
* isAccountNonLocked():当前账户是否未锁定
* @return true = 未锁定
*/
@Override
public boolean isAccountNonLocked() {
return true;
}
/**
* isCredentialsNonExpired():当前账户密码是否未过期
* @return true = 密码未过期
*/
@Override
public boolean isCredentialsNonExpired() {
return true;
}
/** isEnabled():当前账户是否可用
*
* @return true =可用
*/
@Override
public boolean isEnabled() {
return true;
}
}
二,创建 UserService
定义的 UserService 实现 UserDetailsService 接口,并实现该接口的 loadUserByUsername 方法,该方法将在用户登录时自动调用。
package com.aguo.service;
import com.aguo.mapper.UserMapper;
import com.aguo.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;
import java.util.Collection;
import java.util.List;
@Service
@EnableGlobalMethodSecurity(prePostEnabled=true)
/* 该注解作用如下,【写在controller的方法】之上
只能user角色可以访问
@PreAuthorize ("hasAnyRole('user')")
user 角色或者 admin 角色都可访问
@PreAuthorize ("hasAnyRole('user') or hasAnyRole('admin')")
同时拥有 user 和 admin 角色才能访问
@PreAuthorize ("hasAnyRole('user') and hasAnyRole('admin')")
限制只能查询 id 小于 10 的用户
@PreAuthorize("#id < 10")
User findById(int id);
只能查询自己的信息
@PreAuthorize("principal.username.equals(#username)")
User find(String username);
限制只能新增用户名称为abc的用户
@PreAuthorize("#user.name.equals('abc')")
void add(User user)
*/
public class UserService implements UserDetailsService {
@Autowired
UserMapper userMapper;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = new User();
user.setUserName(username);
System.out.println("用户名为:"+user.getUsername());
return user;
}
}
三、配置类
package com.aguo.config;
import com.aguo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
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;
import org.springframework.security.crypto.password.DelegatingPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import sun.security.provider.MD5;
@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
UserService userService;
@Bean
public PasswordEncoder passwordEncoder() {
// 加密类型
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()// 开启 HttpSecurity 配置
.antMatchers(
HttpMethod.GET,
"/**/*.js",
"/**/*.css",
"/",
"/index",
"/index.html"
).permitAll() //放行静态、首页资源。避免当用户点击需要验证的页面后跳转至登录页面,登录成功后返回的并不是原先点击的页面,而是404或者js或者css等静态资源
.antMatchers("/level1/**").access("hasAnyRole('vip1','vip2','vip3','ROLE_USER')")
.antMatchers("/level2/**").access("hasAnyRole('vip2','vip3')")
.antMatchers("/level3/**").hasRole("vip3")
.anyRequest().authenticated() // 用户访问其它URL都必须认证后访问(登录后访问)
.and().formLogin().loginPage("/toLogin").loginProcessingUrl("/login")
.failureUrl("/loginError?error")//登录失败后访问 controller中requestMapper("loginError")即可
.permitAll() // 开启表单登录并配置登录接口
.and().csrf().disable();
// 注销
http.logout().logoutUrl("/logout")
.logoutSuccessUrl("/")
.deleteCookies("remove")
.invalidateHttpSession(true);
//记住我
http.rememberMe().rememberMeParameter("rememberMe");
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService);
}
}
四、剔除内置的Tomcat
(1)修改pom.xml文件
1. 改为war包方式(在文件上方加)
<packaging>war</packaging>
2. 剔除Tomcat,加入servlet依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<!-- 剔除Tomcat,为了开发方便-->
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--添加servlet的依赖-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
3. 修改下方的插件配置
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.3.0</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
</build>
(2)修改启动类
@SpringBootApplication
public class YifudaoApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(YifudaoApplication.class, args);
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
// 配置Springboot的应用环境
SpringApplicationBuilder sources = builder.sources(YifudaoApplication.class);
return sources;
}
}